Add instruction selection for ffloor of vectors when SSE4.1 or AVX is enabled.
[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   ArrayRef<int> MaskVals = SVOp->getMask();
6034
6035   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6036
6037   if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() || !V2IsUndef)
6038     return SDValue();
6039
6040   SmallVector<SDValue,32> pshufbMask;
6041   for (unsigned i = 0; i != 32; i++) {
6042     int EltIdx = MaskVals[i];
6043     if (EltIdx < 0 || EltIdx >= 32)
6044       EltIdx = 0x80;
6045     else {
6046       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6047         // Cross lane is not allowed.
6048         return SDValue();
6049       EltIdx &= 0xf;
6050     }
6051     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6052   }
6053   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6054                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6055                                   MVT::v32i8, &pshufbMask[0], 32));
6056 }
6057
6058 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6059 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6060 /// done when every pair / quad of shuffle mask elements point to elements in
6061 /// the right sequence. e.g.
6062 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6063 static
6064 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6065                                  SelectionDAG &DAG, DebugLoc dl) {
6066   MVT VT = SVOp->getValueType(0).getSimpleVT();
6067   unsigned NumElems = VT.getVectorNumElements();
6068   MVT NewVT;
6069   unsigned Scale;
6070   switch (VT.SimpleTy) {
6071   default: llvm_unreachable("Unexpected!");
6072   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6073   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6074   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6075   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6076   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6077   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6078   }
6079
6080   SmallVector<int, 8> MaskVec;
6081   for (unsigned i = 0; i != NumElems; i += Scale) {
6082     int StartIdx = -1;
6083     for (unsigned j = 0; j != Scale; ++j) {
6084       int EltIdx = SVOp->getMaskElt(i+j);
6085       if (EltIdx < 0)
6086         continue;
6087       if (StartIdx < 0)
6088         StartIdx = (EltIdx / Scale);
6089       if (EltIdx != (int)(StartIdx*Scale + j))
6090         return SDValue();
6091     }
6092     MaskVec.push_back(StartIdx);
6093   }
6094
6095   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6096   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6097   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6098 }
6099
6100 /// getVZextMovL - Return a zero-extending vector move low node.
6101 ///
6102 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6103                             SDValue SrcOp, SelectionDAG &DAG,
6104                             const X86Subtarget *Subtarget, DebugLoc dl) {
6105   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6106     LoadSDNode *LD = NULL;
6107     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6108       LD = dyn_cast<LoadSDNode>(SrcOp);
6109     if (!LD) {
6110       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6111       // instead.
6112       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6113       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6114           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6115           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6116           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6117         // PR2108
6118         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6119         return DAG.getNode(ISD::BITCAST, dl, VT,
6120                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6121                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6122                                                    OpVT,
6123                                                    SrcOp.getOperand(0)
6124                                                           .getOperand(0))));
6125       }
6126     }
6127   }
6128
6129   return DAG.getNode(ISD::BITCAST, dl, VT,
6130                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6131                                  DAG.getNode(ISD::BITCAST, dl,
6132                                              OpVT, SrcOp)));
6133 }
6134
6135 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6136 /// which could not be matched by any known target speficic shuffle
6137 static SDValue
6138 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6139
6140   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6141   if (NewOp.getNode())
6142     return NewOp;
6143
6144   EVT VT = SVOp->getValueType(0);
6145
6146   unsigned NumElems = VT.getVectorNumElements();
6147   unsigned NumLaneElems = NumElems / 2;
6148
6149   DebugLoc dl = SVOp->getDebugLoc();
6150   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6151   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6152   SDValue Output[2];
6153
6154   SmallVector<int, 16> Mask;
6155   for (unsigned l = 0; l < 2; ++l) {
6156     // Build a shuffle mask for the output, discovering on the fly which
6157     // input vectors to use as shuffle operands (recorded in InputUsed).
6158     // If building a suitable shuffle vector proves too hard, then bail
6159     // out with UseBuildVector set.
6160     bool UseBuildVector = false;
6161     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6162     unsigned LaneStart = l * NumLaneElems;
6163     for (unsigned i = 0; i != NumLaneElems; ++i) {
6164       // The mask element.  This indexes into the input.
6165       int Idx = SVOp->getMaskElt(i+LaneStart);
6166       if (Idx < 0) {
6167         // the mask element does not index into any input vector.
6168         Mask.push_back(-1);
6169         continue;
6170       }
6171
6172       // The input vector this mask element indexes into.
6173       int Input = Idx / NumLaneElems;
6174
6175       // Turn the index into an offset from the start of the input vector.
6176       Idx -= Input * NumLaneElems;
6177
6178       // Find or create a shuffle vector operand to hold this input.
6179       unsigned OpNo;
6180       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6181         if (InputUsed[OpNo] == Input)
6182           // This input vector is already an operand.
6183           break;
6184         if (InputUsed[OpNo] < 0) {
6185           // Create a new operand for this input vector.
6186           InputUsed[OpNo] = Input;
6187           break;
6188         }
6189       }
6190
6191       if (OpNo >= array_lengthof(InputUsed)) {
6192         // More than two input vectors used!  Give up on trying to create a
6193         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6194         UseBuildVector = true;
6195         break;
6196       }
6197
6198       // Add the mask index for the new shuffle vector.
6199       Mask.push_back(Idx + OpNo * NumLaneElems);
6200     }
6201
6202     if (UseBuildVector) {
6203       SmallVector<SDValue, 16> SVOps;
6204       for (unsigned i = 0; i != NumLaneElems; ++i) {
6205         // The mask element.  This indexes into the input.
6206         int Idx = SVOp->getMaskElt(i+LaneStart);
6207         if (Idx < 0) {
6208           SVOps.push_back(DAG.getUNDEF(EltVT));
6209           continue;
6210         }
6211
6212         // The input vector this mask element indexes into.
6213         int Input = Idx / NumElems;
6214
6215         // Turn the index into an offset from the start of the input vector.
6216         Idx -= Input * NumElems;
6217
6218         // Extract the vector element by hand.
6219         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6220                                     SVOp->getOperand(Input),
6221                                     DAG.getIntPtrConstant(Idx)));
6222       }
6223
6224       // Construct the output using a BUILD_VECTOR.
6225       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6226                               SVOps.size());
6227     } else if (InputUsed[0] < 0) {
6228       // No input vectors were used! The result is undefined.
6229       Output[l] = DAG.getUNDEF(NVT);
6230     } else {
6231       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6232                                         (InputUsed[0] % 2) * NumLaneElems,
6233                                         DAG, dl);
6234       // If only one input was used, use an undefined vector for the other.
6235       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6236         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6237                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6238       // At least one input vector was used. Create a new shuffle vector.
6239       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6240     }
6241
6242     Mask.clear();
6243   }
6244
6245   // Concatenate the result back
6246   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6247 }
6248
6249 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6250 /// 4 elements, and match them with several different shuffle types.
6251 static SDValue
6252 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6253   SDValue V1 = SVOp->getOperand(0);
6254   SDValue V2 = SVOp->getOperand(1);
6255   DebugLoc dl = SVOp->getDebugLoc();
6256   EVT VT = SVOp->getValueType(0);
6257
6258   assert(VT.is128BitVector() && "Unsupported vector size");
6259
6260   std::pair<int, int> Locs[4];
6261   int Mask1[] = { -1, -1, -1, -1 };
6262   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6263
6264   unsigned NumHi = 0;
6265   unsigned NumLo = 0;
6266   for (unsigned i = 0; i != 4; ++i) {
6267     int Idx = PermMask[i];
6268     if (Idx < 0) {
6269       Locs[i] = std::make_pair(-1, -1);
6270     } else {
6271       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6272       if (Idx < 4) {
6273         Locs[i] = std::make_pair(0, NumLo);
6274         Mask1[NumLo] = Idx;
6275         NumLo++;
6276       } else {
6277         Locs[i] = std::make_pair(1, NumHi);
6278         if (2+NumHi < 4)
6279           Mask1[2+NumHi] = Idx;
6280         NumHi++;
6281       }
6282     }
6283   }
6284
6285   if (NumLo <= 2 && NumHi <= 2) {
6286     // If no more than two elements come from either vector. This can be
6287     // implemented with two shuffles. First shuffle gather the elements.
6288     // The second shuffle, which takes the first shuffle as both of its
6289     // vector operands, put the elements into the right order.
6290     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6291
6292     int Mask2[] = { -1, -1, -1, -1 };
6293
6294     for (unsigned i = 0; i != 4; ++i)
6295       if (Locs[i].first != -1) {
6296         unsigned Idx = (i < 2) ? 0 : 4;
6297         Idx += Locs[i].first * 2 + Locs[i].second;
6298         Mask2[i] = Idx;
6299       }
6300
6301     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6302   }
6303
6304   if (NumLo == 3 || NumHi == 3) {
6305     // Otherwise, we must have three elements from one vector, call it X, and
6306     // one element from the other, call it Y.  First, use a shufps to build an
6307     // intermediate vector with the one element from Y and the element from X
6308     // that will be in the same half in the final destination (the indexes don't
6309     // matter). Then, use a shufps to build the final vector, taking the half
6310     // containing the element from Y from the intermediate, and the other half
6311     // from X.
6312     if (NumHi == 3) {
6313       // Normalize it so the 3 elements come from V1.
6314       CommuteVectorShuffleMask(PermMask, 4);
6315       std::swap(V1, V2);
6316     }
6317
6318     // Find the element from V2.
6319     unsigned HiIndex;
6320     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6321       int Val = PermMask[HiIndex];
6322       if (Val < 0)
6323         continue;
6324       if (Val >= 4)
6325         break;
6326     }
6327
6328     Mask1[0] = PermMask[HiIndex];
6329     Mask1[1] = -1;
6330     Mask1[2] = PermMask[HiIndex^1];
6331     Mask1[3] = -1;
6332     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6333
6334     if (HiIndex >= 2) {
6335       Mask1[0] = PermMask[0];
6336       Mask1[1] = PermMask[1];
6337       Mask1[2] = HiIndex & 1 ? 6 : 4;
6338       Mask1[3] = HiIndex & 1 ? 4 : 6;
6339       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6340     }
6341
6342     Mask1[0] = HiIndex & 1 ? 2 : 0;
6343     Mask1[1] = HiIndex & 1 ? 0 : 2;
6344     Mask1[2] = PermMask[2];
6345     Mask1[3] = PermMask[3];
6346     if (Mask1[2] >= 0)
6347       Mask1[2] += 4;
6348     if (Mask1[3] >= 0)
6349       Mask1[3] += 4;
6350     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6351   }
6352
6353   // Break it into (shuffle shuffle_hi, shuffle_lo).
6354   int LoMask[] = { -1, -1, -1, -1 };
6355   int HiMask[] = { -1, -1, -1, -1 };
6356
6357   int *MaskPtr = LoMask;
6358   unsigned MaskIdx = 0;
6359   unsigned LoIdx = 0;
6360   unsigned HiIdx = 2;
6361   for (unsigned i = 0; i != 4; ++i) {
6362     if (i == 2) {
6363       MaskPtr = HiMask;
6364       MaskIdx = 1;
6365       LoIdx = 0;
6366       HiIdx = 2;
6367     }
6368     int Idx = PermMask[i];
6369     if (Idx < 0) {
6370       Locs[i] = std::make_pair(-1, -1);
6371     } else if (Idx < 4) {
6372       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6373       MaskPtr[LoIdx] = Idx;
6374       LoIdx++;
6375     } else {
6376       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6377       MaskPtr[HiIdx] = Idx;
6378       HiIdx++;
6379     }
6380   }
6381
6382   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6383   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6384   int MaskOps[] = { -1, -1, -1, -1 };
6385   for (unsigned i = 0; i != 4; ++i)
6386     if (Locs[i].first != -1)
6387       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6388   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6389 }
6390
6391 static bool MayFoldVectorLoad(SDValue V) {
6392   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6393     V = V.getOperand(0);
6394   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6395     V = V.getOperand(0);
6396   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6397       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6398     // BUILD_VECTOR (load), undef
6399     V = V.getOperand(0);
6400   if (MayFoldLoad(V))
6401     return true;
6402   return false;
6403 }
6404
6405 // FIXME: the version above should always be used. Since there's
6406 // a bug where several vector shuffles can't be folded because the
6407 // DAG is not updated during lowering and a node claims to have two
6408 // uses while it only has one, use this version, and let isel match
6409 // another instruction if the load really happens to have more than
6410 // one use. Remove this version after this bug get fixed.
6411 // rdar://8434668, PR8156
6412 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6413   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6414     V = V.getOperand(0);
6415   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6416     V = V.getOperand(0);
6417   if (ISD::isNormalLoad(V.getNode()))
6418     return true;
6419   return false;
6420 }
6421
6422 static
6423 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6424   EVT VT = Op.getValueType();
6425
6426   // Canonizalize to v2f64.
6427   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6428   return DAG.getNode(ISD::BITCAST, dl, VT,
6429                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6430                                           V1, DAG));
6431 }
6432
6433 static
6434 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6435                         bool HasSSE2) {
6436   SDValue V1 = Op.getOperand(0);
6437   SDValue V2 = Op.getOperand(1);
6438   EVT VT = Op.getValueType();
6439
6440   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6441
6442   if (HasSSE2 && VT == MVT::v2f64)
6443     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6444
6445   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6446   return DAG.getNode(ISD::BITCAST, dl, VT,
6447                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6448                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6449                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6450 }
6451
6452 static
6453 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6454   SDValue V1 = Op.getOperand(0);
6455   SDValue V2 = Op.getOperand(1);
6456   EVT VT = Op.getValueType();
6457
6458   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6459          "unsupported shuffle type");
6460
6461   if (V2.getOpcode() == ISD::UNDEF)
6462     V2 = V1;
6463
6464   // v4i32 or v4f32
6465   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6466 }
6467
6468 static
6469 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6470   SDValue V1 = Op.getOperand(0);
6471   SDValue V2 = Op.getOperand(1);
6472   EVT VT = Op.getValueType();
6473   unsigned NumElems = VT.getVectorNumElements();
6474
6475   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6476   // operand of these instructions is only memory, so check if there's a
6477   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6478   // same masks.
6479   bool CanFoldLoad = false;
6480
6481   // Trivial case, when V2 comes from a load.
6482   if (MayFoldVectorLoad(V2))
6483     CanFoldLoad = true;
6484
6485   // When V1 is a load, it can be folded later into a store in isel, example:
6486   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6487   //    turns into:
6488   //  (MOVLPSmr addr:$src1, VR128:$src2)
6489   // So, recognize this potential and also use MOVLPS or MOVLPD
6490   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6491     CanFoldLoad = true;
6492
6493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6494   if (CanFoldLoad) {
6495     if (HasSSE2 && NumElems == 2)
6496       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6497
6498     if (NumElems == 4)
6499       // If we don't care about the second element, proceed to use movss.
6500       if (SVOp->getMaskElt(1) != -1)
6501         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6502   }
6503
6504   // movl and movlp will both match v2i64, but v2i64 is never matched by
6505   // movl earlier because we make it strict to avoid messing with the movlp load
6506   // folding logic (see the code above getMOVLP call). Match it here then,
6507   // this is horrible, but will stay like this until we move all shuffle
6508   // matching to x86 specific nodes. Note that for the 1st condition all
6509   // types are matched with movsd.
6510   if (HasSSE2) {
6511     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6512     // as to remove this logic from here, as much as possible
6513     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6514       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6515     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6516   }
6517
6518   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6519
6520   // Invert the operand order and use SHUFPS to match it.
6521   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6522                               getShuffleSHUFImmediate(SVOp), DAG);
6523 }
6524
6525 SDValue
6526 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6527   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6528   EVT VT = Op.getValueType();
6529   DebugLoc dl = Op.getDebugLoc();
6530   SDValue V1 = Op.getOperand(0);
6531   SDValue V2 = Op.getOperand(1);
6532
6533   if (isZeroShuffle(SVOp))
6534     return getZeroVector(VT, Subtarget, DAG, dl);
6535
6536   // Handle splat operations
6537   if (SVOp->isSplat()) {
6538     unsigned NumElem = VT.getVectorNumElements();
6539     int Size = VT.getSizeInBits();
6540
6541     // Use vbroadcast whenever the splat comes from a foldable load
6542     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6543     if (Broadcast.getNode())
6544       return Broadcast;
6545
6546     // Handle splats by matching through known shuffle masks
6547     if ((Size == 128 && NumElem <= 4) ||
6548         (Size == 256 && NumElem < 8))
6549       return SDValue();
6550
6551     // All remaning splats are promoted to target supported vector shuffles.
6552     return PromoteSplat(SVOp, DAG);
6553   }
6554
6555   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6556   // do it!
6557   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6558       VT == MVT::v16i16 || VT == MVT::v32i8) {
6559     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6560     if (NewOp.getNode())
6561       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6562   } else if ((VT == MVT::v4i32 ||
6563              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6564     // FIXME: Figure out a cleaner way to do this.
6565     // Try to make use of movq to zero out the top part.
6566     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6567       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6568       if (NewOp.getNode()) {
6569         EVT NewVT = NewOp.getValueType();
6570         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6571                                NewVT, true, false))
6572           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6573                               DAG, Subtarget, dl);
6574       }
6575     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6576       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6577       if (NewOp.getNode()) {
6578         EVT NewVT = NewOp.getValueType();
6579         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6580           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6581                               DAG, Subtarget, dl);
6582       }
6583     }
6584   }
6585   return SDValue();
6586 }
6587
6588 SDValue
6589 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6590   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6591   SDValue V1 = Op.getOperand(0);
6592   SDValue V2 = Op.getOperand(1);
6593   EVT VT = Op.getValueType();
6594   DebugLoc dl = Op.getDebugLoc();
6595   unsigned NumElems = VT.getVectorNumElements();
6596   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6597   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6598   bool V1IsSplat = false;
6599   bool V2IsSplat = false;
6600   bool HasSSE2 = Subtarget->hasSSE2();
6601   bool HasAVX    = Subtarget->hasAVX();
6602   bool HasAVX2   = Subtarget->hasAVX2();
6603   MachineFunction &MF = DAG.getMachineFunction();
6604   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6605
6606   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6607
6608   if (V1IsUndef && V2IsUndef)
6609     return DAG.getUNDEF(VT);
6610
6611   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6612
6613   // Vector shuffle lowering takes 3 steps:
6614   //
6615   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6616   //    narrowing and commutation of operands should be handled.
6617   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6618   //    shuffle nodes.
6619   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6620   //    so the shuffle can be broken into other shuffles and the legalizer can
6621   //    try the lowering again.
6622   //
6623   // The general idea is that no vector_shuffle operation should be left to
6624   // be matched during isel, all of them must be converted to a target specific
6625   // node here.
6626
6627   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6628   // narrowing and commutation of operands should be handled. The actual code
6629   // doesn't include all of those, work in progress...
6630   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6631   if (NewOp.getNode())
6632     return NewOp;
6633
6634   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6635
6636   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6637   // unpckh_undef). Only use pshufd if speed is more important than size.
6638   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6639     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6640   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6641     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6642
6643   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6644       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6645     return getMOVDDup(Op, dl, V1, DAG);
6646
6647   if (isMOVHLPS_v_undef_Mask(M, VT))
6648     return getMOVHighToLow(Op, dl, DAG);
6649
6650   // Use to match splats
6651   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6652       (VT == MVT::v2f64 || VT == MVT::v2i64))
6653     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6654
6655   if (isPSHUFDMask(M, VT)) {
6656     // The actual implementation will match the mask in the if above and then
6657     // during isel it can match several different instructions, not only pshufd
6658     // as its name says, sad but true, emulate the behavior for now...
6659     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6660       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6661
6662     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6663
6664     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6665       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6666
6667     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6668       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6669
6670     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6671                                 TargetMask, DAG);
6672   }
6673
6674   // Check if this can be converted into a logical shift.
6675   bool isLeft = false;
6676   unsigned ShAmt = 0;
6677   SDValue ShVal;
6678   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6679   if (isShift && ShVal.hasOneUse()) {
6680     // If the shifted value has multiple uses, it may be cheaper to use
6681     // v_set0 + movlhps or movhlps, etc.
6682     EVT EltVT = VT.getVectorElementType();
6683     ShAmt *= EltVT.getSizeInBits();
6684     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6685   }
6686
6687   if (isMOVLMask(M, VT)) {
6688     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6689       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6690     if (!isMOVLPMask(M, VT)) {
6691       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6692         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6693
6694       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6695         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6696     }
6697   }
6698
6699   // FIXME: fold these into legal mask.
6700   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6701     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6702
6703   if (isMOVHLPSMask(M, VT))
6704     return getMOVHighToLow(Op, dl, DAG);
6705
6706   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6707     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6708
6709   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6710     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6711
6712   if (isMOVLPMask(M, VT))
6713     return getMOVLP(Op, dl, DAG, HasSSE2);
6714
6715   if (ShouldXformToMOVHLPS(M, VT) ||
6716       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6717     return CommuteVectorShuffle(SVOp, DAG);
6718
6719   if (isShift) {
6720     // No better options. Use a vshldq / vsrldq.
6721     EVT EltVT = VT.getVectorElementType();
6722     ShAmt *= EltVT.getSizeInBits();
6723     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6724   }
6725
6726   bool Commuted = false;
6727   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6728   // 1,1,1,1 -> v8i16 though.
6729   V1IsSplat = isSplatVector(V1.getNode());
6730   V2IsSplat = isSplatVector(V2.getNode());
6731
6732   // Canonicalize the splat or undef, if present, to be on the RHS.
6733   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6734     CommuteVectorShuffleMask(M, NumElems);
6735     std::swap(V1, V2);
6736     std::swap(V1IsSplat, V2IsSplat);
6737     Commuted = true;
6738   }
6739
6740   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6741     // Shuffling low element of v1 into undef, just return v1.
6742     if (V2IsUndef)
6743       return V1;
6744     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6745     // the instruction selector will not match, so get a canonical MOVL with
6746     // swapped operands to undo the commute.
6747     return getMOVL(DAG, dl, VT, V2, V1);
6748   }
6749
6750   if (isUNPCKLMask(M, VT, HasAVX2))
6751     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6752
6753   if (isUNPCKHMask(M, VT, HasAVX2))
6754     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6755
6756   if (V2IsSplat) {
6757     // Normalize mask so all entries that point to V2 points to its first
6758     // element then try to match unpck{h|l} again. If match, return a
6759     // new vector_shuffle with the corrected mask.p
6760     SmallVector<int, 8> NewMask(M.begin(), M.end());
6761     NormalizeMask(NewMask, NumElems);
6762     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6763       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6764     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6765       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6766   }
6767
6768   if (Commuted) {
6769     // Commute is back and try unpck* again.
6770     // FIXME: this seems wrong.
6771     CommuteVectorShuffleMask(M, NumElems);
6772     std::swap(V1, V2);
6773     std::swap(V1IsSplat, V2IsSplat);
6774     Commuted = false;
6775
6776     if (isUNPCKLMask(M, VT, HasAVX2))
6777       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6778
6779     if (isUNPCKHMask(M, VT, HasAVX2))
6780       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6781   }
6782
6783   // Normalize the node to match x86 shuffle ops if needed
6784   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6785     return CommuteVectorShuffle(SVOp, DAG);
6786
6787   // The checks below are all present in isShuffleMaskLegal, but they are
6788   // inlined here right now to enable us to directly emit target specific
6789   // nodes, and remove one by one until they don't return Op anymore.
6790
6791   if (isPALIGNRMask(M, VT, Subtarget))
6792     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6793                                 getShufflePALIGNRImmediate(SVOp),
6794                                 DAG);
6795
6796   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6797       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6798     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6799       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6800   }
6801
6802   if (isPSHUFHWMask(M, VT, HasAVX2))
6803     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6804                                 getShufflePSHUFHWImmediate(SVOp),
6805                                 DAG);
6806
6807   if (isPSHUFLWMask(M, VT, HasAVX2))
6808     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6809                                 getShufflePSHUFLWImmediate(SVOp),
6810                                 DAG);
6811
6812   if (isSHUFPMask(M, VT, HasAVX))
6813     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6814                                 getShuffleSHUFImmediate(SVOp), DAG);
6815
6816   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6817     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6818   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6819     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6820
6821   //===--------------------------------------------------------------------===//
6822   // Generate target specific nodes for 128 or 256-bit shuffles only
6823   // supported in the AVX instruction set.
6824   //
6825
6826   // Handle VMOVDDUPY permutations
6827   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6828     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6829
6830   // Handle VPERMILPS/D* permutations
6831   if (isVPERMILPMask(M, VT, HasAVX)) {
6832     if (HasAVX2 && VT == MVT::v8i32)
6833       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6834                                   getShuffleSHUFImmediate(SVOp), DAG);
6835     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6836                                 getShuffleSHUFImmediate(SVOp), DAG);
6837   }
6838
6839   // Handle VPERM2F128/VPERM2I128 permutations
6840   if (isVPERM2X128Mask(M, VT, HasAVX))
6841     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6842                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6843
6844   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6845   if (BlendOp.getNode())
6846     return BlendOp;
6847
6848   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6849     SmallVector<SDValue, 8> permclMask;
6850     for (unsigned i = 0; i != 8; ++i) {
6851       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6852     }
6853     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6854                                &permclMask[0], 8);
6855     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6856     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6857                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6858   }
6859
6860   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6861     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6862                                 getShuffleCLImmediate(SVOp), DAG);
6863
6864
6865   //===--------------------------------------------------------------------===//
6866   // Since no target specific shuffle was selected for this generic one,
6867   // lower it into other known shuffles. FIXME: this isn't true yet, but
6868   // this is the plan.
6869   //
6870
6871   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6872   if (VT == MVT::v8i16) {
6873     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6874     if (NewOp.getNode())
6875       return NewOp;
6876   }
6877
6878   if (VT == MVT::v16i8) {
6879     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6880     if (NewOp.getNode())
6881       return NewOp;
6882   }
6883
6884   if (VT == MVT::v32i8) {
6885     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6886     if (NewOp.getNode())
6887       return NewOp;
6888   }
6889
6890   // Handle all 128-bit wide vectors with 4 elements, and match them with
6891   // several different shuffle types.
6892   if (NumElems == 4 && VT.is128BitVector())
6893     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6894
6895   // Handle general 256-bit shuffles
6896   if (VT.is256BitVector())
6897     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6898
6899   return SDValue();
6900 }
6901
6902 SDValue
6903 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6904                                                 SelectionDAG &DAG) const {
6905   EVT VT = Op.getValueType();
6906   DebugLoc dl = Op.getDebugLoc();
6907
6908   if (!Op.getOperand(0).getValueType().is128BitVector())
6909     return SDValue();
6910
6911   if (VT.getSizeInBits() == 8) {
6912     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6913                                     Op.getOperand(0), Op.getOperand(1));
6914     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6915                                     DAG.getValueType(VT));
6916     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6917   }
6918
6919   if (VT.getSizeInBits() == 16) {
6920     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6921     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6922     if (Idx == 0)
6923       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6924                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6925                                      DAG.getNode(ISD::BITCAST, dl,
6926                                                  MVT::v4i32,
6927                                                  Op.getOperand(0)),
6928                                      Op.getOperand(1)));
6929     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6930                                     Op.getOperand(0), Op.getOperand(1));
6931     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6932                                     DAG.getValueType(VT));
6933     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6934   }
6935
6936   if (VT == MVT::f32) {
6937     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6938     // the result back to FR32 register. It's only worth matching if the
6939     // result has a single use which is a store or a bitcast to i32.  And in
6940     // the case of a store, it's not worth it if the index is a constant 0,
6941     // because a MOVSSmr can be used instead, which is smaller and faster.
6942     if (!Op.hasOneUse())
6943       return SDValue();
6944     SDNode *User = *Op.getNode()->use_begin();
6945     if ((User->getOpcode() != ISD::STORE ||
6946          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6947           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6948         (User->getOpcode() != ISD::BITCAST ||
6949          User->getValueType(0) != MVT::i32))
6950       return SDValue();
6951     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6952                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6953                                               Op.getOperand(0)),
6954                                               Op.getOperand(1));
6955     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6956   }
6957
6958   if (VT == MVT::i32 || VT == MVT::i64) {
6959     // ExtractPS/pextrq works with constant index.
6960     if (isa<ConstantSDNode>(Op.getOperand(1)))
6961       return Op;
6962   }
6963   return SDValue();
6964 }
6965
6966
6967 SDValue
6968 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6969                                            SelectionDAG &DAG) const {
6970   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6971     return SDValue();
6972
6973   SDValue Vec = Op.getOperand(0);
6974   EVT VecVT = Vec.getValueType();
6975
6976   // If this is a 256-bit vector result, first extract the 128-bit vector and
6977   // then extract the element from the 128-bit vector.
6978   if (VecVT.is256BitVector()) {
6979     DebugLoc dl = Op.getNode()->getDebugLoc();
6980     unsigned NumElems = VecVT.getVectorNumElements();
6981     SDValue Idx = Op.getOperand(1);
6982     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6983
6984     // Get the 128-bit vector.
6985     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6986
6987     if (IdxVal >= NumElems/2)
6988       IdxVal -= NumElems/2;
6989     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6990                        DAG.getConstant(IdxVal, MVT::i32));
6991   }
6992
6993   assert(VecVT.is128BitVector() && "Unexpected vector length");
6994
6995   if (Subtarget->hasSSE41()) {
6996     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6997     if (Res.getNode())
6998       return Res;
6999   }
7000
7001   EVT VT = Op.getValueType();
7002   DebugLoc dl = Op.getDebugLoc();
7003   // TODO: handle v16i8.
7004   if (VT.getSizeInBits() == 16) {
7005     SDValue Vec = Op.getOperand(0);
7006     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7007     if (Idx == 0)
7008       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7009                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7010                                      DAG.getNode(ISD::BITCAST, dl,
7011                                                  MVT::v4i32, Vec),
7012                                      Op.getOperand(1)));
7013     // Transform it so it match pextrw which produces a 32-bit result.
7014     EVT EltVT = MVT::i32;
7015     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7016                                     Op.getOperand(0), Op.getOperand(1));
7017     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7018                                     DAG.getValueType(VT));
7019     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7020   }
7021
7022   if (VT.getSizeInBits() == 32) {
7023     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7024     if (Idx == 0)
7025       return Op;
7026
7027     // SHUFPS the element to the lowest double word, then movss.
7028     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7029     EVT VVT = Op.getOperand(0).getValueType();
7030     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7031                                        DAG.getUNDEF(VVT), Mask);
7032     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7033                        DAG.getIntPtrConstant(0));
7034   }
7035
7036   if (VT.getSizeInBits() == 64) {
7037     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7038     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7039     //        to match extract_elt for f64.
7040     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7041     if (Idx == 0)
7042       return Op;
7043
7044     // UNPCKHPD the element to the lowest double word, then movsd.
7045     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7046     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7047     int Mask[2] = { 1, -1 };
7048     EVT VVT = Op.getOperand(0).getValueType();
7049     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7050                                        DAG.getUNDEF(VVT), Mask);
7051     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7052                        DAG.getIntPtrConstant(0));
7053   }
7054
7055   return SDValue();
7056 }
7057
7058 SDValue
7059 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7060                                                SelectionDAG &DAG) const {
7061   EVT VT = Op.getValueType();
7062   EVT EltVT = VT.getVectorElementType();
7063   DebugLoc dl = Op.getDebugLoc();
7064
7065   SDValue N0 = Op.getOperand(0);
7066   SDValue N1 = Op.getOperand(1);
7067   SDValue N2 = Op.getOperand(2);
7068
7069   if (!VT.is128BitVector())
7070     return SDValue();
7071
7072   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7073       isa<ConstantSDNode>(N2)) {
7074     unsigned Opc;
7075     if (VT == MVT::v8i16)
7076       Opc = X86ISD::PINSRW;
7077     else if (VT == MVT::v16i8)
7078       Opc = X86ISD::PINSRB;
7079     else
7080       Opc = X86ISD::PINSRB;
7081
7082     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7083     // argument.
7084     if (N1.getValueType() != MVT::i32)
7085       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7086     if (N2.getValueType() != MVT::i32)
7087       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7088     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7089   }
7090
7091   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7092     // Bits [7:6] of the constant are the source select.  This will always be
7093     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7094     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7095     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7096     // Bits [5:4] of the constant are the destination select.  This is the
7097     //  value of the incoming immediate.
7098     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7099     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7100     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7101     // Create this as a scalar to vector..
7102     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7103     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7104   }
7105
7106   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7107     // PINSR* works with constant index.
7108     return Op;
7109   }
7110   return SDValue();
7111 }
7112
7113 SDValue
7114 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7115   EVT VT = Op.getValueType();
7116   EVT EltVT = VT.getVectorElementType();
7117
7118   DebugLoc dl = Op.getDebugLoc();
7119   SDValue N0 = Op.getOperand(0);
7120   SDValue N1 = Op.getOperand(1);
7121   SDValue N2 = Op.getOperand(2);
7122
7123   // If this is a 256-bit vector result, first extract the 128-bit vector,
7124   // insert the element into the extracted half and then place it back.
7125   if (VT.is256BitVector()) {
7126     if (!isa<ConstantSDNode>(N2))
7127       return SDValue();
7128
7129     // Get the desired 128-bit vector half.
7130     unsigned NumElems = VT.getVectorNumElements();
7131     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7132     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7133
7134     // Insert the element into the desired half.
7135     bool Upper = IdxVal >= NumElems/2;
7136     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7137                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7138
7139     // Insert the changed part back to the 256-bit vector
7140     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7141   }
7142
7143   if (Subtarget->hasSSE41())
7144     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7145
7146   if (EltVT == MVT::i8)
7147     return SDValue();
7148
7149   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7150     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7151     // as its second argument.
7152     if (N1.getValueType() != MVT::i32)
7153       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7154     if (N2.getValueType() != MVT::i32)
7155       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7156     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7157   }
7158   return SDValue();
7159 }
7160
7161 SDValue
7162 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7163   LLVMContext *Context = DAG.getContext();
7164   DebugLoc dl = Op.getDebugLoc();
7165   EVT OpVT = Op.getValueType();
7166
7167   // If this is a 256-bit vector result, first insert into a 128-bit
7168   // vector and then insert into the 256-bit vector.
7169   if (!OpVT.is128BitVector()) {
7170     // Insert into a 128-bit vector.
7171     EVT VT128 = EVT::getVectorVT(*Context,
7172                                  OpVT.getVectorElementType(),
7173                                  OpVT.getVectorNumElements() / 2);
7174
7175     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7176
7177     // Insert the 128-bit vector.
7178     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7179   }
7180
7181   if (OpVT == MVT::v1i64 &&
7182       Op.getOperand(0).getValueType() == MVT::i64)
7183     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7184
7185   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7186   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7187   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7188                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7189 }
7190
7191 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7192 // a simple subregister reference or explicit instructions to grab
7193 // upper bits of a vector.
7194 SDValue
7195 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7196   if (Subtarget->hasAVX()) {
7197     DebugLoc dl = Op.getNode()->getDebugLoc();
7198     SDValue Vec = Op.getNode()->getOperand(0);
7199     SDValue Idx = Op.getNode()->getOperand(1);
7200
7201     if (Op.getNode()->getValueType(0).is128BitVector() &&
7202         Vec.getNode()->getValueType(0).is256BitVector() &&
7203         isa<ConstantSDNode>(Idx)) {
7204       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7205       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7206     }
7207   }
7208   return SDValue();
7209 }
7210
7211 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7212 // simple superregister reference or explicit instructions to insert
7213 // the upper bits of a vector.
7214 SDValue
7215 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7216   if (Subtarget->hasAVX()) {
7217     DebugLoc dl = Op.getNode()->getDebugLoc();
7218     SDValue Vec = Op.getNode()->getOperand(0);
7219     SDValue SubVec = Op.getNode()->getOperand(1);
7220     SDValue Idx = Op.getNode()->getOperand(2);
7221
7222     if (Op.getNode()->getValueType(0).is256BitVector() &&
7223         SubVec.getNode()->getValueType(0).is128BitVector() &&
7224         isa<ConstantSDNode>(Idx)) {
7225       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7226       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7227     }
7228   }
7229   return SDValue();
7230 }
7231
7232 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7233 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7234 // one of the above mentioned nodes. It has to be wrapped because otherwise
7235 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7236 // be used to form addressing mode. These wrapped nodes will be selected
7237 // into MOV32ri.
7238 SDValue
7239 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7240   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7241
7242   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7243   // global base reg.
7244   unsigned char OpFlag = 0;
7245   unsigned WrapperKind = X86ISD::Wrapper;
7246   CodeModel::Model M = getTargetMachine().getCodeModel();
7247
7248   if (Subtarget->isPICStyleRIPRel() &&
7249       (M == CodeModel::Small || M == CodeModel::Kernel))
7250     WrapperKind = X86ISD::WrapperRIP;
7251   else if (Subtarget->isPICStyleGOT())
7252     OpFlag = X86II::MO_GOTOFF;
7253   else if (Subtarget->isPICStyleStubPIC())
7254     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7255
7256   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7257                                              CP->getAlignment(),
7258                                              CP->getOffset(), OpFlag);
7259   DebugLoc DL = CP->getDebugLoc();
7260   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7261   // With PIC, the address is actually $g + Offset.
7262   if (OpFlag) {
7263     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7264                          DAG.getNode(X86ISD::GlobalBaseReg,
7265                                      DebugLoc(), getPointerTy()),
7266                          Result);
7267   }
7268
7269   return Result;
7270 }
7271
7272 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7273   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7274
7275   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7276   // global base reg.
7277   unsigned char OpFlag = 0;
7278   unsigned WrapperKind = X86ISD::Wrapper;
7279   CodeModel::Model M = getTargetMachine().getCodeModel();
7280
7281   if (Subtarget->isPICStyleRIPRel() &&
7282       (M == CodeModel::Small || M == CodeModel::Kernel))
7283     WrapperKind = X86ISD::WrapperRIP;
7284   else if (Subtarget->isPICStyleGOT())
7285     OpFlag = X86II::MO_GOTOFF;
7286   else if (Subtarget->isPICStyleStubPIC())
7287     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7288
7289   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7290                                           OpFlag);
7291   DebugLoc DL = JT->getDebugLoc();
7292   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7293
7294   // With PIC, the address is actually $g + Offset.
7295   if (OpFlag)
7296     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7297                          DAG.getNode(X86ISD::GlobalBaseReg,
7298                                      DebugLoc(), getPointerTy()),
7299                          Result);
7300
7301   return Result;
7302 }
7303
7304 SDValue
7305 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7306   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7307
7308   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7309   // global base reg.
7310   unsigned char OpFlag = 0;
7311   unsigned WrapperKind = X86ISD::Wrapper;
7312   CodeModel::Model M = getTargetMachine().getCodeModel();
7313
7314   if (Subtarget->isPICStyleRIPRel() &&
7315       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7316     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7317       OpFlag = X86II::MO_GOTPCREL;
7318     WrapperKind = X86ISD::WrapperRIP;
7319   } else if (Subtarget->isPICStyleGOT()) {
7320     OpFlag = X86II::MO_GOT;
7321   } else if (Subtarget->isPICStyleStubPIC()) {
7322     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7323   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7324     OpFlag = X86II::MO_DARWIN_NONLAZY;
7325   }
7326
7327   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7328
7329   DebugLoc DL = Op.getDebugLoc();
7330   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7331
7332
7333   // With PIC, the address is actually $g + Offset.
7334   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7335       !Subtarget->is64Bit()) {
7336     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7337                          DAG.getNode(X86ISD::GlobalBaseReg,
7338                                      DebugLoc(), getPointerTy()),
7339                          Result);
7340   }
7341
7342   // For symbols that require a load from a stub to get the address, emit the
7343   // load.
7344   if (isGlobalStubReference(OpFlag))
7345     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7346                          MachinePointerInfo::getGOT(), false, false, false, 0);
7347
7348   return Result;
7349 }
7350
7351 SDValue
7352 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7353   // Create the TargetBlockAddressAddress node.
7354   unsigned char OpFlags =
7355     Subtarget->ClassifyBlockAddressReference();
7356   CodeModel::Model M = getTargetMachine().getCodeModel();
7357   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7358   DebugLoc dl = Op.getDebugLoc();
7359   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7360                                        /*isTarget=*/true, OpFlags);
7361
7362   if (Subtarget->isPICStyleRIPRel() &&
7363       (M == CodeModel::Small || M == CodeModel::Kernel))
7364     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7365   else
7366     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7367
7368   // With PIC, the address is actually $g + Offset.
7369   if (isGlobalRelativeToPICBase(OpFlags)) {
7370     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7371                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7372                          Result);
7373   }
7374
7375   return Result;
7376 }
7377
7378 SDValue
7379 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7380                                       int64_t Offset,
7381                                       SelectionDAG &DAG) const {
7382   // Create the TargetGlobalAddress node, folding in the constant
7383   // offset if it is legal.
7384   unsigned char OpFlags =
7385     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7386   CodeModel::Model M = getTargetMachine().getCodeModel();
7387   SDValue Result;
7388   if (OpFlags == X86II::MO_NO_FLAG &&
7389       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7390     // A direct static reference to a global.
7391     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7392     Offset = 0;
7393   } else {
7394     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7395   }
7396
7397   if (Subtarget->isPICStyleRIPRel() &&
7398       (M == CodeModel::Small || M == CodeModel::Kernel))
7399     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7400   else
7401     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7402
7403   // With PIC, the address is actually $g + Offset.
7404   if (isGlobalRelativeToPICBase(OpFlags)) {
7405     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7406                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7407                          Result);
7408   }
7409
7410   // For globals that require a load from a stub to get the address, emit the
7411   // load.
7412   if (isGlobalStubReference(OpFlags))
7413     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7414                          MachinePointerInfo::getGOT(), false, false, false, 0);
7415
7416   // If there was a non-zero offset that we didn't fold, create an explicit
7417   // addition for it.
7418   if (Offset != 0)
7419     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7420                          DAG.getConstant(Offset, getPointerTy()));
7421
7422   return Result;
7423 }
7424
7425 SDValue
7426 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7427   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7428   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7429   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7430 }
7431
7432 static SDValue
7433 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7434            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7435            unsigned char OperandFlags, bool LocalDynamic = false) {
7436   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7437   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7438   DebugLoc dl = GA->getDebugLoc();
7439   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7440                                            GA->getValueType(0),
7441                                            GA->getOffset(),
7442                                            OperandFlags);
7443
7444   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7445                                            : X86ISD::TLSADDR;
7446
7447   if (InFlag) {
7448     SDValue Ops[] = { Chain,  TGA, *InFlag };
7449     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7450   } else {
7451     SDValue Ops[]  = { Chain, TGA };
7452     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7453   }
7454
7455   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7456   MFI->setAdjustsStack(true);
7457
7458   SDValue Flag = Chain.getValue(1);
7459   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7460 }
7461
7462 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7463 static SDValue
7464 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7465                                 const EVT PtrVT) {
7466   SDValue InFlag;
7467   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7468   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7469                                      DAG.getNode(X86ISD::GlobalBaseReg,
7470                                                  DebugLoc(), PtrVT), InFlag);
7471   InFlag = Chain.getValue(1);
7472
7473   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7474 }
7475
7476 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7477 static SDValue
7478 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7479                                 const EVT PtrVT) {
7480   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7481                     X86::RAX, X86II::MO_TLSGD);
7482 }
7483
7484 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7485                                            SelectionDAG &DAG,
7486                                            const EVT PtrVT,
7487                                            bool is64Bit) {
7488   DebugLoc dl = GA->getDebugLoc();
7489
7490   // Get the start address of the TLS block for this module.
7491   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7492       .getInfo<X86MachineFunctionInfo>();
7493   MFI->incNumLocalDynamicTLSAccesses();
7494
7495   SDValue Base;
7496   if (is64Bit) {
7497     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7498                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7499   } else {
7500     SDValue InFlag;
7501     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7502         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7503     InFlag = Chain.getValue(1);
7504     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7505                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7506   }
7507
7508   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7509   // of Base.
7510
7511   // Build x@dtpoff.
7512   unsigned char OperandFlags = X86II::MO_DTPOFF;
7513   unsigned WrapperKind = X86ISD::Wrapper;
7514   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7515                                            GA->getValueType(0),
7516                                            GA->getOffset(), OperandFlags);
7517   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7518
7519   // Add x@dtpoff with the base.
7520   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7521 }
7522
7523 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7524 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7525                                    const EVT PtrVT, TLSModel::Model model,
7526                                    bool is64Bit, bool isPIC) {
7527   DebugLoc dl = GA->getDebugLoc();
7528
7529   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7530   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7531                                                          is64Bit ? 257 : 256));
7532
7533   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7534                                       DAG.getIntPtrConstant(0),
7535                                       MachinePointerInfo(Ptr),
7536                                       false, false, false, 0);
7537
7538   unsigned char OperandFlags = 0;
7539   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7540   // initialexec.
7541   unsigned WrapperKind = X86ISD::Wrapper;
7542   if (model == TLSModel::LocalExec) {
7543     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7544   } else if (model == TLSModel::InitialExec) {
7545     if (is64Bit) {
7546       OperandFlags = X86II::MO_GOTTPOFF;
7547       WrapperKind = X86ISD::WrapperRIP;
7548     } else {
7549       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7550     }
7551   } else {
7552     llvm_unreachable("Unexpected model");
7553   }
7554
7555   // emit "addl x@ntpoff,%eax" (local exec)
7556   // or "addl x@indntpoff,%eax" (initial exec)
7557   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7558   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7559                                            GA->getValueType(0),
7560                                            GA->getOffset(), OperandFlags);
7561   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7562
7563   if (model == TLSModel::InitialExec) {
7564     if (isPIC && !is64Bit) {
7565       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7566                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7567                            Offset);
7568     }
7569
7570     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7571                          MachinePointerInfo::getGOT(), false, false, false,
7572                          0);
7573   }
7574
7575   // The address of the thread local variable is the add of the thread
7576   // pointer with the offset of the variable.
7577   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7578 }
7579
7580 SDValue
7581 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7582
7583   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7584   const GlobalValue *GV = GA->getGlobal();
7585
7586   if (Subtarget->isTargetELF()) {
7587     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7588
7589     switch (model) {
7590       case TLSModel::GeneralDynamic:
7591         if (Subtarget->is64Bit())
7592           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7593         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7594       case TLSModel::LocalDynamic:
7595         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7596                                            Subtarget->is64Bit());
7597       case TLSModel::InitialExec:
7598       case TLSModel::LocalExec:
7599         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7600                                    Subtarget->is64Bit(),
7601                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7602     }
7603     llvm_unreachable("Unknown TLS model.");
7604   }
7605
7606   if (Subtarget->isTargetDarwin()) {
7607     // Darwin only has one model of TLS.  Lower to that.
7608     unsigned char OpFlag = 0;
7609     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7610                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7611
7612     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7613     // global base reg.
7614     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7615                   !Subtarget->is64Bit();
7616     if (PIC32)
7617       OpFlag = X86II::MO_TLVP_PIC_BASE;
7618     else
7619       OpFlag = X86II::MO_TLVP;
7620     DebugLoc DL = Op.getDebugLoc();
7621     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7622                                                 GA->getValueType(0),
7623                                                 GA->getOffset(), OpFlag);
7624     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7625
7626     // With PIC32, the address is actually $g + Offset.
7627     if (PIC32)
7628       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7629                            DAG.getNode(X86ISD::GlobalBaseReg,
7630                                        DebugLoc(), getPointerTy()),
7631                            Offset);
7632
7633     // Lowering the machine isd will make sure everything is in the right
7634     // location.
7635     SDValue Chain = DAG.getEntryNode();
7636     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7637     SDValue Args[] = { Chain, Offset };
7638     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7639
7640     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7641     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7642     MFI->setAdjustsStack(true);
7643
7644     // And our return value (tls address) is in the standard call return value
7645     // location.
7646     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7647     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7648                               Chain.getValue(1));
7649   }
7650
7651   if (Subtarget->isTargetWindows()) {
7652     // Just use the implicit TLS architecture
7653     // Need to generate someting similar to:
7654     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7655     //                                  ; from TEB
7656     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7657     //   mov     rcx, qword [rdx+rcx*8]
7658     //   mov     eax, .tls$:tlsvar
7659     //   [rax+rcx] contains the address
7660     // Windows 64bit: gs:0x58
7661     // Windows 32bit: fs:__tls_array
7662
7663     // If GV is an alias then use the aliasee for determining
7664     // thread-localness.
7665     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7666       GV = GA->resolveAliasedGlobal(false);
7667     DebugLoc dl = GA->getDebugLoc();
7668     SDValue Chain = DAG.getEntryNode();
7669
7670     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7671     // %gs:0x58 (64-bit).
7672     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7673                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7674                                                              256)
7675                                         : Type::getInt32PtrTy(*DAG.getContext(),
7676                                                               257));
7677
7678     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7679                                         Subtarget->is64Bit()
7680                                         ? DAG.getIntPtrConstant(0x58)
7681                                         : DAG.getExternalSymbol("_tls_array",
7682                                                                 getPointerTy()),
7683                                         MachinePointerInfo(Ptr),
7684                                         false, false, false, 0);
7685
7686     // Load the _tls_index variable
7687     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7688     if (Subtarget->is64Bit())
7689       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7690                            IDX, MachinePointerInfo(), MVT::i32,
7691                            false, false, 0);
7692     else
7693       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7694                         false, false, false, 0);
7695
7696     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7697                                     getPointerTy());
7698     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7699
7700     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7701     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7702                       false, false, false, 0);
7703
7704     // Get the offset of start of .tls section
7705     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7706                                              GA->getValueType(0),
7707                                              GA->getOffset(), X86II::MO_SECREL);
7708     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7709
7710     // The address of the thread local variable is the add of the thread
7711     // pointer with the offset of the variable.
7712     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7713   }
7714
7715   llvm_unreachable("TLS not implemented for this target.");
7716 }
7717
7718
7719 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7720 /// and take a 2 x i32 value to shift plus a shift amount.
7721 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7722   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7723   EVT VT = Op.getValueType();
7724   unsigned VTBits = VT.getSizeInBits();
7725   DebugLoc dl = Op.getDebugLoc();
7726   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7727   SDValue ShOpLo = Op.getOperand(0);
7728   SDValue ShOpHi = Op.getOperand(1);
7729   SDValue ShAmt  = Op.getOperand(2);
7730   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7731                                      DAG.getConstant(VTBits - 1, MVT::i8))
7732                        : DAG.getConstant(0, VT);
7733
7734   SDValue Tmp2, Tmp3;
7735   if (Op.getOpcode() == ISD::SHL_PARTS) {
7736     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7737     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7738   } else {
7739     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7740     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7741   }
7742
7743   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7744                                 DAG.getConstant(VTBits, MVT::i8));
7745   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7746                              AndNode, DAG.getConstant(0, MVT::i8));
7747
7748   SDValue Hi, Lo;
7749   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7750   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7751   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7752
7753   if (Op.getOpcode() == ISD::SHL_PARTS) {
7754     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7755     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7756   } else {
7757     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7758     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7759   }
7760
7761   SDValue Ops[2] = { Lo, Hi };
7762   return DAG.getMergeValues(Ops, 2, dl);
7763 }
7764
7765 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7766                                            SelectionDAG &DAG) const {
7767   EVT SrcVT = Op.getOperand(0).getValueType();
7768
7769   if (SrcVT.isVector())
7770     return SDValue();
7771
7772   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7773          "Unknown SINT_TO_FP to lower!");
7774
7775   // These are really Legal; return the operand so the caller accepts it as
7776   // Legal.
7777   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7778     return Op;
7779   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7780       Subtarget->is64Bit()) {
7781     return Op;
7782   }
7783
7784   DebugLoc dl = Op.getDebugLoc();
7785   unsigned Size = SrcVT.getSizeInBits()/8;
7786   MachineFunction &MF = DAG.getMachineFunction();
7787   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7788   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7789   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7790                                StackSlot,
7791                                MachinePointerInfo::getFixedStack(SSFI),
7792                                false, false, 0);
7793   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7794 }
7795
7796 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7797                                      SDValue StackSlot,
7798                                      SelectionDAG &DAG) const {
7799   // Build the FILD
7800   DebugLoc DL = Op.getDebugLoc();
7801   SDVTList Tys;
7802   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7803   if (useSSE)
7804     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7805   else
7806     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7807
7808   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7809
7810   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7811   MachineMemOperand *MMO;
7812   if (FI) {
7813     int SSFI = FI->getIndex();
7814     MMO =
7815       DAG.getMachineFunction()
7816       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7817                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7818   } else {
7819     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7820     StackSlot = StackSlot.getOperand(1);
7821   }
7822   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7823   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7824                                            X86ISD::FILD, DL,
7825                                            Tys, Ops, array_lengthof(Ops),
7826                                            SrcVT, MMO);
7827
7828   if (useSSE) {
7829     Chain = Result.getValue(1);
7830     SDValue InFlag = Result.getValue(2);
7831
7832     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7833     // shouldn't be necessary except that RFP cannot be live across
7834     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7835     MachineFunction &MF = DAG.getMachineFunction();
7836     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7837     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7838     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7839     Tys = DAG.getVTList(MVT::Other);
7840     SDValue Ops[] = {
7841       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7842     };
7843     MachineMemOperand *MMO =
7844       DAG.getMachineFunction()
7845       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7846                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7847
7848     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7849                                     Ops, array_lengthof(Ops),
7850                                     Op.getValueType(), MMO);
7851     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7852                          MachinePointerInfo::getFixedStack(SSFI),
7853                          false, false, false, 0);
7854   }
7855
7856   return Result;
7857 }
7858
7859 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7860 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7861                                                SelectionDAG &DAG) const {
7862   // This algorithm is not obvious. Here it is what we're trying to output:
7863   /*
7864      movq       %rax,  %xmm0
7865      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7866      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7867      #ifdef __SSE3__
7868        haddpd   %xmm0, %xmm0
7869      #else
7870        pshufd   $0x4e, %xmm0, %xmm1
7871        addpd    %xmm1, %xmm0
7872      #endif
7873   */
7874
7875   DebugLoc dl = Op.getDebugLoc();
7876   LLVMContext *Context = DAG.getContext();
7877
7878   // Build some magic constants.
7879   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7880   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7881   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7882
7883   SmallVector<Constant*,2> CV1;
7884   CV1.push_back(
7885         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7886   CV1.push_back(
7887         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7888   Constant *C1 = ConstantVector::get(CV1);
7889   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7890
7891   // Load the 64-bit value into an XMM register.
7892   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7893                             Op.getOperand(0));
7894   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7895                               MachinePointerInfo::getConstantPool(),
7896                               false, false, false, 16);
7897   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7898                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7899                               CLod0);
7900
7901   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7902                               MachinePointerInfo::getConstantPool(),
7903                               false, false, false, 16);
7904   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7905   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7906   SDValue Result;
7907
7908   if (Subtarget->hasSSE3()) {
7909     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7910     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7911   } else {
7912     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7913     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7914                                            S2F, 0x4E, DAG);
7915     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7916                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7917                          Sub);
7918   }
7919
7920   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7921                      DAG.getIntPtrConstant(0));
7922 }
7923
7924 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7925 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7926                                                SelectionDAG &DAG) const {
7927   DebugLoc dl = Op.getDebugLoc();
7928   // FP constant to bias correct the final result.
7929   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7930                                    MVT::f64);
7931
7932   // Load the 32-bit value into an XMM register.
7933   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7934                              Op.getOperand(0));
7935
7936   // Zero out the upper parts of the register.
7937   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7938
7939   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7940                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7941                      DAG.getIntPtrConstant(0));
7942
7943   // Or the load with the bias.
7944   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7945                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7946                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7947                                                    MVT::v2f64, Load)),
7948                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7949                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7950                                                    MVT::v2f64, Bias)));
7951   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7952                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7953                    DAG.getIntPtrConstant(0));
7954
7955   // Subtract the bias.
7956   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7957
7958   // Handle final rounding.
7959   EVT DestVT = Op.getValueType();
7960
7961   if (DestVT.bitsLT(MVT::f64))
7962     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7963                        DAG.getIntPtrConstant(0));
7964   if (DestVT.bitsGT(MVT::f64))
7965     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7966
7967   // Handle final rounding.
7968   return Sub;
7969 }
7970
7971 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7972                                            SelectionDAG &DAG) const {
7973   SDValue N0 = Op.getOperand(0);
7974   DebugLoc dl = Op.getDebugLoc();
7975
7976   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7977   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7978   // the optimization here.
7979   if (DAG.SignBitIsZero(N0))
7980     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7981
7982   EVT SrcVT = N0.getValueType();
7983   EVT DstVT = Op.getValueType();
7984   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7985     return LowerUINT_TO_FP_i64(Op, DAG);
7986   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7987     return LowerUINT_TO_FP_i32(Op, DAG);
7988   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7989     return SDValue();
7990
7991   // Make a 64-bit buffer, and use it to build an FILD.
7992   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7993   if (SrcVT == MVT::i32) {
7994     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7995     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7996                                      getPointerTy(), StackSlot, WordOff);
7997     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7998                                   StackSlot, MachinePointerInfo(),
7999                                   false, false, 0);
8000     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8001                                   OffsetSlot, MachinePointerInfo(),
8002                                   false, false, 0);
8003     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8004     return Fild;
8005   }
8006
8007   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8008   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8009                                StackSlot, MachinePointerInfo(),
8010                                false, false, 0);
8011   // For i64 source, we need to add the appropriate power of 2 if the input
8012   // was negative.  This is the same as the optimization in
8013   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8014   // we must be careful to do the computation in x87 extended precision, not
8015   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8016   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8017   MachineMemOperand *MMO =
8018     DAG.getMachineFunction()
8019     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8020                           MachineMemOperand::MOLoad, 8, 8);
8021
8022   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8023   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8024   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8025                                          MVT::i64, MMO);
8026
8027   APInt FF(32, 0x5F800000ULL);
8028
8029   // Check whether the sign bit is set.
8030   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8031                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8032                                  ISD::SETLT);
8033
8034   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8035   SDValue FudgePtr = DAG.getConstantPool(
8036                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8037                                          getPointerTy());
8038
8039   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8040   SDValue Zero = DAG.getIntPtrConstant(0);
8041   SDValue Four = DAG.getIntPtrConstant(4);
8042   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8043                                Zero, Four);
8044   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8045
8046   // Load the value out, extending it from f32 to f80.
8047   // FIXME: Avoid the extend by constructing the right constant pool?
8048   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8049                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8050                                  MVT::f32, false, false, 4);
8051   // Extend everything to 80 bits to force it to be done on x87.
8052   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8053   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8054 }
8055
8056 std::pair<SDValue,SDValue> X86TargetLowering::
8057 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8058   DebugLoc DL = Op.getDebugLoc();
8059
8060   EVT DstTy = Op.getValueType();
8061
8062   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8063     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8064     DstTy = MVT::i64;
8065   }
8066
8067   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8068          DstTy.getSimpleVT() >= MVT::i16 &&
8069          "Unknown FP_TO_INT to lower!");
8070
8071   // These are really Legal.
8072   if (DstTy == MVT::i32 &&
8073       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8074     return std::make_pair(SDValue(), SDValue());
8075   if (Subtarget->is64Bit() &&
8076       DstTy == MVT::i64 &&
8077       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8078     return std::make_pair(SDValue(), SDValue());
8079
8080   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8081   // stack slot, or into the FTOL runtime function.
8082   MachineFunction &MF = DAG.getMachineFunction();
8083   unsigned MemSize = DstTy.getSizeInBits()/8;
8084   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8085   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8086
8087   unsigned Opc;
8088   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8089     Opc = X86ISD::WIN_FTOL;
8090   else
8091     switch (DstTy.getSimpleVT().SimpleTy) {
8092     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8093     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8094     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8095     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8096     }
8097
8098   SDValue Chain = DAG.getEntryNode();
8099   SDValue Value = Op.getOperand(0);
8100   EVT TheVT = Op.getOperand(0).getValueType();
8101   // FIXME This causes a redundant load/store if the SSE-class value is already
8102   // in memory, such as if it is on the callstack.
8103   if (isScalarFPTypeInSSEReg(TheVT)) {
8104     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8105     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8106                          MachinePointerInfo::getFixedStack(SSFI),
8107                          false, false, 0);
8108     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8109     SDValue Ops[] = {
8110       Chain, StackSlot, DAG.getValueType(TheVT)
8111     };
8112
8113     MachineMemOperand *MMO =
8114       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8115                               MachineMemOperand::MOLoad, MemSize, MemSize);
8116     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8117                                     DstTy, MMO);
8118     Chain = Value.getValue(1);
8119     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8120     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8121   }
8122
8123   MachineMemOperand *MMO =
8124     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8125                             MachineMemOperand::MOStore, MemSize, MemSize);
8126
8127   if (Opc != X86ISD::WIN_FTOL) {
8128     // Build the FP_TO_INT*_IN_MEM
8129     SDValue Ops[] = { Chain, Value, StackSlot };
8130     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8131                                            Ops, 3, DstTy, MMO);
8132     return std::make_pair(FIST, StackSlot);
8133   } else {
8134     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8135       DAG.getVTList(MVT::Other, MVT::Glue),
8136       Chain, Value);
8137     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8138       MVT::i32, ftol.getValue(1));
8139     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8140       MVT::i32, eax.getValue(2));
8141     SDValue Ops[] = { eax, edx };
8142     SDValue pair = IsReplace
8143       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8144       : DAG.getMergeValues(Ops, 2, DL);
8145     return std::make_pair(pair, SDValue());
8146   }
8147 }
8148
8149 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8150                                            SelectionDAG &DAG) const {
8151   if (Op.getValueType().isVector())
8152     return SDValue();
8153
8154   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8155     /*IsSigned=*/ true, /*IsReplace=*/ false);
8156   SDValue FIST = Vals.first, StackSlot = Vals.second;
8157   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8158   if (FIST.getNode() == 0) return Op;
8159
8160   if (StackSlot.getNode())
8161     // Load the result.
8162     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8163                        FIST, StackSlot, MachinePointerInfo(),
8164                        false, false, false, 0);
8165
8166   // The node is the result.
8167   return FIST;
8168 }
8169
8170 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8171                                            SelectionDAG &DAG) const {
8172   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8173     /*IsSigned=*/ false, /*IsReplace=*/ false);
8174   SDValue FIST = Vals.first, StackSlot = Vals.second;
8175   assert(FIST.getNode() && "Unexpected failure");
8176
8177   if (StackSlot.getNode())
8178     // Load the result.
8179     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8180                        FIST, StackSlot, MachinePointerInfo(),
8181                        false, false, false, 0);
8182
8183   // The node is the result.
8184   return FIST;
8185 }
8186
8187 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8188   LLVMContext *Context = DAG.getContext();
8189   DebugLoc dl = Op.getDebugLoc();
8190   EVT VT = Op.getValueType();
8191   EVT EltVT = VT;
8192   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8193   if (VT.isVector()) {
8194     EltVT = VT.getVectorElementType();
8195     NumElts = VT.getVectorNumElements();
8196   }
8197   Constant *C;
8198   if (EltVT == MVT::f64)
8199     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8200   else
8201     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8202   C = ConstantVector::getSplat(NumElts, C);
8203   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8204   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8205   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8206                              MachinePointerInfo::getConstantPool(),
8207                              false, false, false, Alignment);
8208   if (VT.isVector()) {
8209     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8210     return DAG.getNode(ISD::BITCAST, dl, VT,
8211                        DAG.getNode(ISD::AND, dl, ANDVT,
8212                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8213                                                Op.getOperand(0)),
8214                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8215   }
8216   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8217 }
8218
8219 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8220   LLVMContext *Context = DAG.getContext();
8221   DebugLoc dl = Op.getDebugLoc();
8222   EVT VT = Op.getValueType();
8223   EVT EltVT = VT;
8224   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8225   if (VT.isVector()) {
8226     EltVT = VT.getVectorElementType();
8227     NumElts = VT.getVectorNumElements();
8228   }
8229   Constant *C;
8230   if (EltVT == MVT::f64)
8231     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8232   else
8233     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8234   C = ConstantVector::getSplat(NumElts, C);
8235   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8236   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8237   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8238                              MachinePointerInfo::getConstantPool(),
8239                              false, false, false, Alignment);
8240   if (VT.isVector()) {
8241     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8242     return DAG.getNode(ISD::BITCAST, dl, VT,
8243                        DAG.getNode(ISD::XOR, dl, XORVT,
8244                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8245                                                Op.getOperand(0)),
8246                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8247   }
8248
8249   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8250 }
8251
8252 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8253   LLVMContext *Context = DAG.getContext();
8254   SDValue Op0 = Op.getOperand(0);
8255   SDValue Op1 = Op.getOperand(1);
8256   DebugLoc dl = Op.getDebugLoc();
8257   EVT VT = Op.getValueType();
8258   EVT SrcVT = Op1.getValueType();
8259
8260   // If second operand is smaller, extend it first.
8261   if (SrcVT.bitsLT(VT)) {
8262     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8263     SrcVT = VT;
8264   }
8265   // And if it is bigger, shrink it first.
8266   if (SrcVT.bitsGT(VT)) {
8267     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8268     SrcVT = VT;
8269   }
8270
8271   // At this point the operands and the result should have the same
8272   // type, and that won't be f80 since that is not custom lowered.
8273
8274   // First get the sign bit of second operand.
8275   SmallVector<Constant*,4> CV;
8276   if (SrcVT == MVT::f64) {
8277     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8278     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8279   } else {
8280     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8281     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8282     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8283     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8284   }
8285   Constant *C = ConstantVector::get(CV);
8286   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8287   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8288                               MachinePointerInfo::getConstantPool(),
8289                               false, false, false, 16);
8290   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8291
8292   // Shift sign bit right or left if the two operands have different types.
8293   if (SrcVT.bitsGT(VT)) {
8294     // Op0 is MVT::f32, Op1 is MVT::f64.
8295     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8296     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8297                           DAG.getConstant(32, MVT::i32));
8298     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8299     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8300                           DAG.getIntPtrConstant(0));
8301   }
8302
8303   // Clear first operand sign bit.
8304   CV.clear();
8305   if (VT == MVT::f64) {
8306     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8307     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8308   } else {
8309     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8310     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8311     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8312     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8313   }
8314   C = ConstantVector::get(CV);
8315   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8316   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8317                               MachinePointerInfo::getConstantPool(),
8318                               false, false, false, 16);
8319   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8320
8321   // Or the value with the sign bit.
8322   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8323 }
8324
8325 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8326   SDValue N0 = Op.getOperand(0);
8327   DebugLoc dl = Op.getDebugLoc();
8328   EVT VT = Op.getValueType();
8329
8330   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8331   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8332                                   DAG.getConstant(1, VT));
8333   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8334 }
8335
8336 /// Emit nodes that will be selected as "test Op0,Op0", or something
8337 /// equivalent.
8338 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8339                                     SelectionDAG &DAG) const {
8340   DebugLoc dl = Op.getDebugLoc();
8341
8342   // CF and OF aren't always set the way we want. Determine which
8343   // of these we need.
8344   bool NeedCF = false;
8345   bool NeedOF = false;
8346   switch (X86CC) {
8347   default: break;
8348   case X86::COND_A: case X86::COND_AE:
8349   case X86::COND_B: case X86::COND_BE:
8350     NeedCF = true;
8351     break;
8352   case X86::COND_G: case X86::COND_GE:
8353   case X86::COND_L: case X86::COND_LE:
8354   case X86::COND_O: case X86::COND_NO:
8355     NeedOF = true;
8356     break;
8357   }
8358
8359   // See if we can use the EFLAGS value from the operand instead of
8360   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8361   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8362   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8363     // Emit a CMP with 0, which is the TEST pattern.
8364     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8365                        DAG.getConstant(0, Op.getValueType()));
8366
8367   unsigned Opcode = 0;
8368   unsigned NumOperands = 0;
8369
8370   // Truncate operations may prevent the merge of the SETCC instruction
8371   // and the arithmetic intruction before it. Attempt to truncate the operands
8372   // of the arithmetic instruction and use a reduced bit-width instruction.
8373   bool NeedTruncation = false;
8374   SDValue ArithOp = Op;
8375   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8376     SDValue Arith = Op->getOperand(0);
8377     // Both the trunc and the arithmetic op need to have one user each.
8378     if (Arith->hasOneUse())
8379       switch (Arith.getOpcode()) {
8380         default: break;
8381         case ISD::ADD:
8382         case ISD::SUB:
8383         case ISD::AND:
8384         case ISD::OR:
8385         case ISD::XOR: {
8386           NeedTruncation = true;
8387           ArithOp = Arith;
8388         }
8389       }
8390   }
8391
8392   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8393   // which may be the result of a CAST.  We use the variable 'Op', which is the
8394   // non-casted variable when we check for possible users.
8395   switch (ArithOp.getOpcode()) {
8396   case ISD::ADD:
8397     // Due to an isel shortcoming, be conservative if this add is likely to be
8398     // selected as part of a load-modify-store instruction. When the root node
8399     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8400     // uses of other nodes in the match, such as the ADD in this case. This
8401     // leads to the ADD being left around and reselected, with the result being
8402     // two adds in the output.  Alas, even if none our users are stores, that
8403     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8404     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8405     // climbing the DAG back to the root, and it doesn't seem to be worth the
8406     // effort.
8407     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8408          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8409       if (UI->getOpcode() != ISD::CopyToReg &&
8410           UI->getOpcode() != ISD::SETCC &&
8411           UI->getOpcode() != ISD::STORE)
8412         goto default_case;
8413
8414     if (ConstantSDNode *C =
8415         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8416       // An add of one will be selected as an INC.
8417       if (C->getAPIntValue() == 1) {
8418         Opcode = X86ISD::INC;
8419         NumOperands = 1;
8420         break;
8421       }
8422
8423       // An add of negative one (subtract of one) will be selected as a DEC.
8424       if (C->getAPIntValue().isAllOnesValue()) {
8425         Opcode = X86ISD::DEC;
8426         NumOperands = 1;
8427         break;
8428       }
8429     }
8430
8431     // Otherwise use a regular EFLAGS-setting add.
8432     Opcode = X86ISD::ADD;
8433     NumOperands = 2;
8434     break;
8435   case ISD::AND: {
8436     // If the primary and result isn't used, don't bother using X86ISD::AND,
8437     // because a TEST instruction will be better.
8438     bool NonFlagUse = false;
8439     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8440            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8441       SDNode *User = *UI;
8442       unsigned UOpNo = UI.getOperandNo();
8443       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8444         // Look pass truncate.
8445         UOpNo = User->use_begin().getOperandNo();
8446         User = *User->use_begin();
8447       }
8448
8449       if (User->getOpcode() != ISD::BRCOND &&
8450           User->getOpcode() != ISD::SETCC &&
8451           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8452         NonFlagUse = true;
8453         break;
8454       }
8455     }
8456
8457     if (!NonFlagUse)
8458       break;
8459   }
8460     // FALL THROUGH
8461   case ISD::SUB:
8462   case ISD::OR:
8463   case ISD::XOR:
8464     // Due to the ISEL shortcoming noted above, be conservative if this op is
8465     // likely to be selected as part of a load-modify-store instruction.
8466     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8467            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8468       if (UI->getOpcode() == ISD::STORE)
8469         goto default_case;
8470
8471     // Otherwise use a regular EFLAGS-setting instruction.
8472     switch (ArithOp.getOpcode()) {
8473     default: llvm_unreachable("unexpected operator!");
8474     case ISD::SUB: Opcode = X86ISD::SUB; break;
8475     case ISD::OR:  Opcode = X86ISD::OR;  break;
8476     case ISD::XOR: Opcode = X86ISD::XOR; break;
8477     case ISD::AND: Opcode = X86ISD::AND; break;
8478     }
8479
8480     NumOperands = 2;
8481     break;
8482   case X86ISD::ADD:
8483   case X86ISD::SUB:
8484   case X86ISD::INC:
8485   case X86ISD::DEC:
8486   case X86ISD::OR:
8487   case X86ISD::XOR:
8488   case X86ISD::AND:
8489     return SDValue(Op.getNode(), 1);
8490   default:
8491   default_case:
8492     break;
8493   }
8494
8495   // If we found that truncation is beneficial, perform the truncation and
8496   // update 'Op'.
8497   if (NeedTruncation) {
8498     EVT VT = Op.getValueType();
8499     SDValue WideVal = Op->getOperand(0);
8500     EVT WideVT = WideVal.getValueType();
8501     unsigned ConvertedOp = 0;
8502     // Use a target machine opcode to prevent further DAGCombine
8503     // optimizations that may separate the arithmetic operations
8504     // from the setcc node.
8505     switch (WideVal.getOpcode()) {
8506       default: break;
8507       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8508       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8509       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8510       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8511       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8512     }
8513
8514     if (ConvertedOp) {
8515       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8516       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8517         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8518         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8519         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8520       }
8521     }
8522   }
8523
8524   if (Opcode == 0)
8525     // Emit a CMP with 0, which is the TEST pattern.
8526     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8527                        DAG.getConstant(0, Op.getValueType()));
8528
8529   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8530   SmallVector<SDValue, 4> Ops;
8531   for (unsigned i = 0; i != NumOperands; ++i)
8532     Ops.push_back(Op.getOperand(i));
8533
8534   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8535   DAG.ReplaceAllUsesWith(Op, New);
8536   return SDValue(New.getNode(), 1);
8537 }
8538
8539 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8540 /// equivalent.
8541 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8542                                    SelectionDAG &DAG) const {
8543   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8544     if (C->getAPIntValue() == 0)
8545       return EmitTest(Op0, X86CC, DAG);
8546
8547   DebugLoc dl = Op0.getDebugLoc();
8548   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8549        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8550     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8551     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8552     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8553                               Op0, Op1);
8554     return SDValue(Sub.getNode(), 1);
8555   }
8556   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8557 }
8558
8559 /// Convert a comparison if required by the subtarget.
8560 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8561                                                  SelectionDAG &DAG) const {
8562   // If the subtarget does not support the FUCOMI instruction, floating-point
8563   // comparisons have to be converted.
8564   if (Subtarget->hasCMov() ||
8565       Cmp.getOpcode() != X86ISD::CMP ||
8566       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8567       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8568     return Cmp;
8569
8570   // The instruction selector will select an FUCOM instruction instead of
8571   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8572   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8573   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8574   DebugLoc dl = Cmp.getDebugLoc();
8575   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8576   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8577   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8578                             DAG.getConstant(8, MVT::i8));
8579   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8580   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8581 }
8582
8583 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8584 /// if it's possible.
8585 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8586                                      DebugLoc dl, SelectionDAG &DAG) const {
8587   SDValue Op0 = And.getOperand(0);
8588   SDValue Op1 = And.getOperand(1);
8589   if (Op0.getOpcode() == ISD::TRUNCATE)
8590     Op0 = Op0.getOperand(0);
8591   if (Op1.getOpcode() == ISD::TRUNCATE)
8592     Op1 = Op1.getOperand(0);
8593
8594   SDValue LHS, RHS;
8595   if (Op1.getOpcode() == ISD::SHL)
8596     std::swap(Op0, Op1);
8597   if (Op0.getOpcode() == ISD::SHL) {
8598     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8599       if (And00C->getZExtValue() == 1) {
8600         // If we looked past a truncate, check that it's only truncating away
8601         // known zeros.
8602         unsigned BitWidth = Op0.getValueSizeInBits();
8603         unsigned AndBitWidth = And.getValueSizeInBits();
8604         if (BitWidth > AndBitWidth) {
8605           APInt Zeros, Ones;
8606           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8607           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8608             return SDValue();
8609         }
8610         LHS = Op1;
8611         RHS = Op0.getOperand(1);
8612       }
8613   } else if (Op1.getOpcode() == ISD::Constant) {
8614     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8615     uint64_t AndRHSVal = AndRHS->getZExtValue();
8616     SDValue AndLHS = Op0;
8617
8618     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8619       LHS = AndLHS.getOperand(0);
8620       RHS = AndLHS.getOperand(1);
8621     }
8622
8623     // Use BT if the immediate can't be encoded in a TEST instruction.
8624     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8625       LHS = AndLHS;
8626       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8627     }
8628   }
8629
8630   if (LHS.getNode()) {
8631     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8632     // instruction.  Since the shift amount is in-range-or-undefined, we know
8633     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8634     // the encoding for the i16 version is larger than the i32 version.
8635     // Also promote i16 to i32 for performance / code size reason.
8636     if (LHS.getValueType() == MVT::i8 ||
8637         LHS.getValueType() == MVT::i16)
8638       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8639
8640     // If the operand types disagree, extend the shift amount to match.  Since
8641     // BT ignores high bits (like shifts) we can use anyextend.
8642     if (LHS.getValueType() != RHS.getValueType())
8643       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8644
8645     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8646     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8647     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8648                        DAG.getConstant(Cond, MVT::i8), BT);
8649   }
8650
8651   return SDValue();
8652 }
8653
8654 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8655
8656   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8657
8658   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8659   SDValue Op0 = Op.getOperand(0);
8660   SDValue Op1 = Op.getOperand(1);
8661   DebugLoc dl = Op.getDebugLoc();
8662   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8663
8664   // Optimize to BT if possible.
8665   // Lower (X & (1 << N)) == 0 to BT(X, N).
8666   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8667   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8668   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8669       Op1.getOpcode() == ISD::Constant &&
8670       cast<ConstantSDNode>(Op1)->isNullValue() &&
8671       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8672     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8673     if (NewSetCC.getNode())
8674       return NewSetCC;
8675   }
8676
8677   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8678   // these.
8679   if (Op1.getOpcode() == ISD::Constant &&
8680       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8681        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8682       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8683
8684     // If the input is a setcc, then reuse the input setcc or use a new one with
8685     // the inverted condition.
8686     if (Op0.getOpcode() == X86ISD::SETCC) {
8687       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8688       bool Invert = (CC == ISD::SETNE) ^
8689         cast<ConstantSDNode>(Op1)->isNullValue();
8690       if (!Invert) return Op0;
8691
8692       CCode = X86::GetOppositeBranchCondition(CCode);
8693       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8694                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8695     }
8696   }
8697
8698   bool isFP = Op1.getValueType().isFloatingPoint();
8699   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8700   if (X86CC == X86::COND_INVALID)
8701     return SDValue();
8702
8703   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8704   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8705   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8706                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8707 }
8708
8709 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8710 // ones, and then concatenate the result back.
8711 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8712   EVT VT = Op.getValueType();
8713
8714   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8715          "Unsupported value type for operation");
8716
8717   unsigned NumElems = VT.getVectorNumElements();
8718   DebugLoc dl = Op.getDebugLoc();
8719   SDValue CC = Op.getOperand(2);
8720
8721   // Extract the LHS vectors
8722   SDValue LHS = Op.getOperand(0);
8723   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8724   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8725
8726   // Extract the RHS vectors
8727   SDValue RHS = Op.getOperand(1);
8728   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8729   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8730
8731   // Issue the operation on the smaller types and concatenate the result back
8732   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8733   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8734   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8735                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8736                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8737 }
8738
8739
8740 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8741   SDValue Cond;
8742   SDValue Op0 = Op.getOperand(0);
8743   SDValue Op1 = Op.getOperand(1);
8744   SDValue CC = Op.getOperand(2);
8745   EVT VT = Op.getValueType();
8746   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8747   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8748   DebugLoc dl = Op.getDebugLoc();
8749
8750   if (isFP) {
8751 #ifndef NDEBUG
8752     EVT EltVT = Op0.getValueType().getVectorElementType();
8753     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8754 #endif
8755
8756     unsigned SSECC;
8757     bool Swap = false;
8758
8759     // SSE Condition code mapping:
8760     //  0 - EQ
8761     //  1 - LT
8762     //  2 - LE
8763     //  3 - UNORD
8764     //  4 - NEQ
8765     //  5 - NLT
8766     //  6 - NLE
8767     //  7 - ORD
8768     switch (SetCCOpcode) {
8769     default: llvm_unreachable("Unexpected SETCC condition");
8770     case ISD::SETOEQ:
8771     case ISD::SETEQ:  SSECC = 0; break;
8772     case ISD::SETOGT:
8773     case ISD::SETGT: Swap = true; // Fallthrough
8774     case ISD::SETLT:
8775     case ISD::SETOLT: SSECC = 1; break;
8776     case ISD::SETOGE:
8777     case ISD::SETGE: Swap = true; // Fallthrough
8778     case ISD::SETLE:
8779     case ISD::SETOLE: SSECC = 2; break;
8780     case ISD::SETUO:  SSECC = 3; break;
8781     case ISD::SETUNE:
8782     case ISD::SETNE:  SSECC = 4; break;
8783     case ISD::SETULE: Swap = true; // Fallthrough
8784     case ISD::SETUGE: SSECC = 5; break;
8785     case ISD::SETULT: Swap = true; // Fallthrough
8786     case ISD::SETUGT: SSECC = 6; break;
8787     case ISD::SETO:   SSECC = 7; break;
8788     case ISD::SETUEQ:
8789     case ISD::SETONE: SSECC = 8; break;
8790     }
8791     if (Swap)
8792       std::swap(Op0, Op1);
8793
8794     // In the two special cases we can't handle, emit two comparisons.
8795     if (SSECC == 8) {
8796       unsigned CC0, CC1;
8797       unsigned CombineOpc;
8798       if (SetCCOpcode == ISD::SETUEQ) {
8799         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8800       } else {
8801         assert(SetCCOpcode == ISD::SETONE);
8802         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8803       }
8804
8805       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8806                                  DAG.getConstant(CC0, MVT::i8));
8807       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8808                                  DAG.getConstant(CC1, MVT::i8));
8809       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8810     }
8811     // Handle all other FP comparisons here.
8812     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8813                        DAG.getConstant(SSECC, MVT::i8));
8814   }
8815
8816   // Break 256-bit integer vector compare into smaller ones.
8817   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8818     return Lower256IntVSETCC(Op, DAG);
8819
8820   // We are handling one of the integer comparisons here.  Since SSE only has
8821   // GT and EQ comparisons for integer, swapping operands and multiple
8822   // operations may be required for some comparisons.
8823   unsigned Opc;
8824   bool Swap = false, Invert = false, FlipSigns = false;
8825
8826   switch (SetCCOpcode) {
8827   default: llvm_unreachable("Unexpected SETCC condition");
8828   case ISD::SETNE:  Invert = true;
8829   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8830   case ISD::SETLT:  Swap = true;
8831   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8832   case ISD::SETGE:  Swap = true;
8833   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8834   case ISD::SETULT: Swap = true;
8835   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8836   case ISD::SETUGE: Swap = true;
8837   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8838   }
8839   if (Swap)
8840     std::swap(Op0, Op1);
8841
8842   // Check that the operation in question is available (most are plain SSE2,
8843   // but PCMPGTQ and PCMPEQQ have different requirements).
8844   if (VT == MVT::v2i64) {
8845     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8846       return SDValue();
8847     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8848       return SDValue();
8849   }
8850
8851   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8852   // bits of the inputs before performing those operations.
8853   if (FlipSigns) {
8854     EVT EltVT = VT.getVectorElementType();
8855     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8856                                       EltVT);
8857     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8858     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8859                                     SignBits.size());
8860     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8861     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8862   }
8863
8864   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8865
8866   // If the logical-not of the result is required, perform that now.
8867   if (Invert)
8868     Result = DAG.getNOT(dl, Result, VT);
8869
8870   return Result;
8871 }
8872
8873 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8874 static bool isX86LogicalCmp(SDValue Op) {
8875   unsigned Opc = Op.getNode()->getOpcode();
8876   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8877       Opc == X86ISD::SAHF)
8878     return true;
8879   if (Op.getResNo() == 1 &&
8880       (Opc == X86ISD::ADD ||
8881        Opc == X86ISD::SUB ||
8882        Opc == X86ISD::ADC ||
8883        Opc == X86ISD::SBB ||
8884        Opc == X86ISD::SMUL ||
8885        Opc == X86ISD::UMUL ||
8886        Opc == X86ISD::INC ||
8887        Opc == X86ISD::DEC ||
8888        Opc == X86ISD::OR ||
8889        Opc == X86ISD::XOR ||
8890        Opc == X86ISD::AND))
8891     return true;
8892
8893   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8894     return true;
8895
8896   return false;
8897 }
8898
8899 static bool isZero(SDValue V) {
8900   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8901   return C && C->isNullValue();
8902 }
8903
8904 static bool isAllOnes(SDValue V) {
8905   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8906   return C && C->isAllOnesValue();
8907 }
8908
8909 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8910   if (V.getOpcode() != ISD::TRUNCATE)
8911     return false;
8912
8913   SDValue VOp0 = V.getOperand(0);
8914   unsigned InBits = VOp0.getValueSizeInBits();
8915   unsigned Bits = V.getValueSizeInBits();
8916   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8917 }
8918
8919 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8920   bool addTest = true;
8921   SDValue Cond  = Op.getOperand(0);
8922   SDValue Op1 = Op.getOperand(1);
8923   SDValue Op2 = Op.getOperand(2);
8924   DebugLoc DL = Op.getDebugLoc();
8925   SDValue CC;
8926
8927   if (Cond.getOpcode() == ISD::SETCC) {
8928     SDValue NewCond = LowerSETCC(Cond, DAG);
8929     if (NewCond.getNode())
8930       Cond = NewCond;
8931   }
8932
8933   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8934   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8935   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8936   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8937   if (Cond.getOpcode() == X86ISD::SETCC &&
8938       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8939       isZero(Cond.getOperand(1).getOperand(1))) {
8940     SDValue Cmp = Cond.getOperand(1);
8941
8942     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8943
8944     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8945         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8946       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8947
8948       SDValue CmpOp0 = Cmp.getOperand(0);
8949       // Apply further optimizations for special cases
8950       // (select (x != 0), -1, 0) -> neg & sbb
8951       // (select (x == 0), 0, -1) -> neg & sbb
8952       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8953         if (YC->isNullValue() &&
8954             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8955           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8956           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8957                                     DAG.getConstant(0, CmpOp0.getValueType()),
8958                                     CmpOp0);
8959           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8960                                     DAG.getConstant(X86::COND_B, MVT::i8),
8961                                     SDValue(Neg.getNode(), 1));
8962           return Res;
8963         }
8964
8965       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8966                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8967       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8968
8969       SDValue Res =   // Res = 0 or -1.
8970         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8971                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8972
8973       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8974         Res = DAG.getNOT(DL, Res, Res.getValueType());
8975
8976       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8977       if (N2C == 0 || !N2C->isNullValue())
8978         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8979       return Res;
8980     }
8981   }
8982
8983   // Look past (and (setcc_carry (cmp ...)), 1).
8984   if (Cond.getOpcode() == ISD::AND &&
8985       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8986     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8987     if (C && C->getAPIntValue() == 1)
8988       Cond = Cond.getOperand(0);
8989   }
8990
8991   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8992   // setting operand in place of the X86ISD::SETCC.
8993   unsigned CondOpcode = Cond.getOpcode();
8994   if (CondOpcode == X86ISD::SETCC ||
8995       CondOpcode == X86ISD::SETCC_CARRY) {
8996     CC = Cond.getOperand(0);
8997
8998     SDValue Cmp = Cond.getOperand(1);
8999     unsigned Opc = Cmp.getOpcode();
9000     EVT VT = Op.getValueType();
9001
9002     bool IllegalFPCMov = false;
9003     if (VT.isFloatingPoint() && !VT.isVector() &&
9004         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9005       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9006
9007     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9008         Opc == X86ISD::BT) { // FIXME
9009       Cond = Cmp;
9010       addTest = false;
9011     }
9012   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9013              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9014              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9015               Cond.getOperand(0).getValueType() != MVT::i8)) {
9016     SDValue LHS = Cond.getOperand(0);
9017     SDValue RHS = Cond.getOperand(1);
9018     unsigned X86Opcode;
9019     unsigned X86Cond;
9020     SDVTList VTs;
9021     switch (CondOpcode) {
9022     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9023     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9024     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9025     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9026     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9027     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9028     default: llvm_unreachable("unexpected overflowing operator");
9029     }
9030     if (CondOpcode == ISD::UMULO)
9031       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9032                           MVT::i32);
9033     else
9034       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9035
9036     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9037
9038     if (CondOpcode == ISD::UMULO)
9039       Cond = X86Op.getValue(2);
9040     else
9041       Cond = X86Op.getValue(1);
9042
9043     CC = DAG.getConstant(X86Cond, MVT::i8);
9044     addTest = false;
9045   }
9046
9047   if (addTest) {
9048     // Look pass the truncate if the high bits are known zero.
9049     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9050         Cond = Cond.getOperand(0);
9051
9052     // We know the result of AND is compared against zero. Try to match
9053     // it to BT.
9054     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9055       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9056       if (NewSetCC.getNode()) {
9057         CC = NewSetCC.getOperand(0);
9058         Cond = NewSetCC.getOperand(1);
9059         addTest = false;
9060       }
9061     }
9062   }
9063
9064   if (addTest) {
9065     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9066     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9067   }
9068
9069   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9070   // a <  b ?  0 : -1 -> RES = setcc_carry
9071   // a >= b ? -1 :  0 -> RES = setcc_carry
9072   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9073   if (Cond.getOpcode() == X86ISD::SUB) {
9074     Cond = ConvertCmpIfNecessary(Cond, DAG);
9075     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9076
9077     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9078         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9079       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9080                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9081       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9082         return DAG.getNOT(DL, Res, Res.getValueType());
9083       return Res;
9084     }
9085   }
9086
9087   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9088   // condition is true.
9089   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9090   SDValue Ops[] = { Op2, Op1, CC, Cond };
9091   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9092 }
9093
9094 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9095 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9096 // from the AND / OR.
9097 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9098   Opc = Op.getOpcode();
9099   if (Opc != ISD::OR && Opc != ISD::AND)
9100     return false;
9101   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9102           Op.getOperand(0).hasOneUse() &&
9103           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9104           Op.getOperand(1).hasOneUse());
9105 }
9106
9107 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9108 // 1 and that the SETCC node has a single use.
9109 static bool isXor1OfSetCC(SDValue Op) {
9110   if (Op.getOpcode() != ISD::XOR)
9111     return false;
9112   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9113   if (N1C && N1C->getAPIntValue() == 1) {
9114     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9115       Op.getOperand(0).hasOneUse();
9116   }
9117   return false;
9118 }
9119
9120 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9121   bool addTest = true;
9122   SDValue Chain = Op.getOperand(0);
9123   SDValue Cond  = Op.getOperand(1);
9124   SDValue Dest  = Op.getOperand(2);
9125   DebugLoc dl = Op.getDebugLoc();
9126   SDValue CC;
9127   bool Inverted = false;
9128
9129   if (Cond.getOpcode() == ISD::SETCC) {
9130     // Check for setcc([su]{add,sub,mul}o == 0).
9131     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9132         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9133         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9134         Cond.getOperand(0).getResNo() == 1 &&
9135         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9136          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9137          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9138          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9139          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9140          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9141       Inverted = true;
9142       Cond = Cond.getOperand(0);
9143     } else {
9144       SDValue NewCond = LowerSETCC(Cond, DAG);
9145       if (NewCond.getNode())
9146         Cond = NewCond;
9147     }
9148   }
9149 #if 0
9150   // FIXME: LowerXALUO doesn't handle these!!
9151   else if (Cond.getOpcode() == X86ISD::ADD  ||
9152            Cond.getOpcode() == X86ISD::SUB  ||
9153            Cond.getOpcode() == X86ISD::SMUL ||
9154            Cond.getOpcode() == X86ISD::UMUL)
9155     Cond = LowerXALUO(Cond, DAG);
9156 #endif
9157
9158   // Look pass (and (setcc_carry (cmp ...)), 1).
9159   if (Cond.getOpcode() == ISD::AND &&
9160       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9161     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9162     if (C && C->getAPIntValue() == 1)
9163       Cond = Cond.getOperand(0);
9164   }
9165
9166   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9167   // setting operand in place of the X86ISD::SETCC.
9168   unsigned CondOpcode = Cond.getOpcode();
9169   if (CondOpcode == X86ISD::SETCC ||
9170       CondOpcode == X86ISD::SETCC_CARRY) {
9171     CC = Cond.getOperand(0);
9172
9173     SDValue Cmp = Cond.getOperand(1);
9174     unsigned Opc = Cmp.getOpcode();
9175     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9176     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9177       Cond = Cmp;
9178       addTest = false;
9179     } else {
9180       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9181       default: break;
9182       case X86::COND_O:
9183       case X86::COND_B:
9184         // These can only come from an arithmetic instruction with overflow,
9185         // e.g. SADDO, UADDO.
9186         Cond = Cond.getNode()->getOperand(1);
9187         addTest = false;
9188         break;
9189       }
9190     }
9191   }
9192   CondOpcode = Cond.getOpcode();
9193   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9194       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9195       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9196        Cond.getOperand(0).getValueType() != MVT::i8)) {
9197     SDValue LHS = Cond.getOperand(0);
9198     SDValue RHS = Cond.getOperand(1);
9199     unsigned X86Opcode;
9200     unsigned X86Cond;
9201     SDVTList VTs;
9202     switch (CondOpcode) {
9203     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9204     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9205     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9206     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9207     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9208     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9209     default: llvm_unreachable("unexpected overflowing operator");
9210     }
9211     if (Inverted)
9212       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9213     if (CondOpcode == ISD::UMULO)
9214       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9215                           MVT::i32);
9216     else
9217       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9218
9219     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9220
9221     if (CondOpcode == ISD::UMULO)
9222       Cond = X86Op.getValue(2);
9223     else
9224       Cond = X86Op.getValue(1);
9225
9226     CC = DAG.getConstant(X86Cond, MVT::i8);
9227     addTest = false;
9228   } else {
9229     unsigned CondOpc;
9230     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9231       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9232       if (CondOpc == ISD::OR) {
9233         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9234         // two branches instead of an explicit OR instruction with a
9235         // separate test.
9236         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9237             isX86LogicalCmp(Cmp)) {
9238           CC = Cond.getOperand(0).getOperand(0);
9239           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9240                               Chain, Dest, CC, Cmp);
9241           CC = Cond.getOperand(1).getOperand(0);
9242           Cond = Cmp;
9243           addTest = false;
9244         }
9245       } else { // ISD::AND
9246         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9247         // two branches instead of an explicit AND instruction with a
9248         // separate test. However, we only do this if this block doesn't
9249         // have a fall-through edge, because this requires an explicit
9250         // jmp when the condition is false.
9251         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9252             isX86LogicalCmp(Cmp) &&
9253             Op.getNode()->hasOneUse()) {
9254           X86::CondCode CCode =
9255             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9256           CCode = X86::GetOppositeBranchCondition(CCode);
9257           CC = DAG.getConstant(CCode, MVT::i8);
9258           SDNode *User = *Op.getNode()->use_begin();
9259           // Look for an unconditional branch following this conditional branch.
9260           // We need this because we need to reverse the successors in order
9261           // to implement FCMP_OEQ.
9262           if (User->getOpcode() == ISD::BR) {
9263             SDValue FalseBB = User->getOperand(1);
9264             SDNode *NewBR =
9265               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9266             assert(NewBR == User);
9267             (void)NewBR;
9268             Dest = FalseBB;
9269
9270             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9271                                 Chain, Dest, CC, Cmp);
9272             X86::CondCode CCode =
9273               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9274             CCode = X86::GetOppositeBranchCondition(CCode);
9275             CC = DAG.getConstant(CCode, MVT::i8);
9276             Cond = Cmp;
9277             addTest = false;
9278           }
9279         }
9280       }
9281     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9282       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9283       // It should be transformed during dag combiner except when the condition
9284       // is set by a arithmetics with overflow node.
9285       X86::CondCode CCode =
9286         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9287       CCode = X86::GetOppositeBranchCondition(CCode);
9288       CC = DAG.getConstant(CCode, MVT::i8);
9289       Cond = Cond.getOperand(0).getOperand(1);
9290       addTest = false;
9291     } else if (Cond.getOpcode() == ISD::SETCC &&
9292                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9293       // For FCMP_OEQ, we can emit
9294       // two branches instead of an explicit AND instruction with a
9295       // separate test. However, we only do this if this block doesn't
9296       // have a fall-through edge, because this requires an explicit
9297       // jmp when the condition is false.
9298       if (Op.getNode()->hasOneUse()) {
9299         SDNode *User = *Op.getNode()->use_begin();
9300         // Look for an unconditional branch following this conditional branch.
9301         // We need this because we need to reverse the successors in order
9302         // to implement FCMP_OEQ.
9303         if (User->getOpcode() == ISD::BR) {
9304           SDValue FalseBB = User->getOperand(1);
9305           SDNode *NewBR =
9306             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9307           assert(NewBR == User);
9308           (void)NewBR;
9309           Dest = FalseBB;
9310
9311           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9312                                     Cond.getOperand(0), Cond.getOperand(1));
9313           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9314           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9315           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9316                               Chain, Dest, CC, Cmp);
9317           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9318           Cond = Cmp;
9319           addTest = false;
9320         }
9321       }
9322     } else if (Cond.getOpcode() == ISD::SETCC &&
9323                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9324       // For FCMP_UNE, we can emit
9325       // two branches instead of an explicit AND instruction with a
9326       // separate test. However, we only do this if this block doesn't
9327       // have a fall-through edge, because this requires an explicit
9328       // jmp when the condition is false.
9329       if (Op.getNode()->hasOneUse()) {
9330         SDNode *User = *Op.getNode()->use_begin();
9331         // Look for an unconditional branch following this conditional branch.
9332         // We need this because we need to reverse the successors in order
9333         // to implement FCMP_UNE.
9334         if (User->getOpcode() == ISD::BR) {
9335           SDValue FalseBB = User->getOperand(1);
9336           SDNode *NewBR =
9337             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9338           assert(NewBR == User);
9339           (void)NewBR;
9340
9341           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9342                                     Cond.getOperand(0), Cond.getOperand(1));
9343           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9344           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9345           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9346                               Chain, Dest, CC, Cmp);
9347           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9348           Cond = Cmp;
9349           addTest = false;
9350           Dest = FalseBB;
9351         }
9352       }
9353     }
9354   }
9355
9356   if (addTest) {
9357     // Look pass the truncate if the high bits are known zero.
9358     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9359         Cond = Cond.getOperand(0);
9360
9361     // We know the result of AND is compared against zero. Try to match
9362     // it to BT.
9363     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9364       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9365       if (NewSetCC.getNode()) {
9366         CC = NewSetCC.getOperand(0);
9367         Cond = NewSetCC.getOperand(1);
9368         addTest = false;
9369       }
9370     }
9371   }
9372
9373   if (addTest) {
9374     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9375     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9376   }
9377   Cond = ConvertCmpIfNecessary(Cond, DAG);
9378   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9379                      Chain, Dest, CC, Cond);
9380 }
9381
9382
9383 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9384 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9385 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9386 // that the guard pages used by the OS virtual memory manager are allocated in
9387 // correct sequence.
9388 SDValue
9389 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9390                                            SelectionDAG &DAG) const {
9391   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9392           getTargetMachine().Options.EnableSegmentedStacks) &&
9393          "This should be used only on Windows targets or when segmented stacks "
9394          "are being used");
9395   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9396   DebugLoc dl = Op.getDebugLoc();
9397
9398   // Get the inputs.
9399   SDValue Chain = Op.getOperand(0);
9400   SDValue Size  = Op.getOperand(1);
9401   // FIXME: Ensure alignment here
9402
9403   bool Is64Bit = Subtarget->is64Bit();
9404   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9405
9406   if (getTargetMachine().Options.EnableSegmentedStacks) {
9407     MachineFunction &MF = DAG.getMachineFunction();
9408     MachineRegisterInfo &MRI = MF.getRegInfo();
9409
9410     if (Is64Bit) {
9411       // The 64 bit implementation of segmented stacks needs to clobber both r10
9412       // r11. This makes it impossible to use it along with nested parameters.
9413       const Function *F = MF.getFunction();
9414
9415       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9416            I != E; ++I)
9417         if (I->hasNestAttr())
9418           report_fatal_error("Cannot use segmented stacks with functions that "
9419                              "have nested arguments.");
9420     }
9421
9422     const TargetRegisterClass *AddrRegClass =
9423       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9424     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9425     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9426     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9427                                 DAG.getRegister(Vreg, SPTy));
9428     SDValue Ops1[2] = { Value, Chain };
9429     return DAG.getMergeValues(Ops1, 2, dl);
9430   } else {
9431     SDValue Flag;
9432     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9433
9434     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9435     Flag = Chain.getValue(1);
9436     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9437
9438     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9439     Flag = Chain.getValue(1);
9440
9441     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9442
9443     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9444     return DAG.getMergeValues(Ops1, 2, dl);
9445   }
9446 }
9447
9448 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9449   MachineFunction &MF = DAG.getMachineFunction();
9450   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9451
9452   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9453   DebugLoc DL = Op.getDebugLoc();
9454
9455   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9456     // vastart just stores the address of the VarArgsFrameIndex slot into the
9457     // memory location argument.
9458     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9459                                    getPointerTy());
9460     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9461                         MachinePointerInfo(SV), false, false, 0);
9462   }
9463
9464   // __va_list_tag:
9465   //   gp_offset         (0 - 6 * 8)
9466   //   fp_offset         (48 - 48 + 8 * 16)
9467   //   overflow_arg_area (point to parameters coming in memory).
9468   //   reg_save_area
9469   SmallVector<SDValue, 8> MemOps;
9470   SDValue FIN = Op.getOperand(1);
9471   // Store gp_offset
9472   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9473                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9474                                                MVT::i32),
9475                                FIN, MachinePointerInfo(SV), false, false, 0);
9476   MemOps.push_back(Store);
9477
9478   // Store fp_offset
9479   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9480                     FIN, DAG.getIntPtrConstant(4));
9481   Store = DAG.getStore(Op.getOperand(0), DL,
9482                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9483                                        MVT::i32),
9484                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9485   MemOps.push_back(Store);
9486
9487   // Store ptr to overflow_arg_area
9488   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9489                     FIN, DAG.getIntPtrConstant(4));
9490   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9491                                     getPointerTy());
9492   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9493                        MachinePointerInfo(SV, 8),
9494                        false, false, 0);
9495   MemOps.push_back(Store);
9496
9497   // Store ptr to reg_save_area.
9498   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9499                     FIN, DAG.getIntPtrConstant(8));
9500   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9501                                     getPointerTy());
9502   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9503                        MachinePointerInfo(SV, 16), false, false, 0);
9504   MemOps.push_back(Store);
9505   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9506                      &MemOps[0], MemOps.size());
9507 }
9508
9509 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9510   assert(Subtarget->is64Bit() &&
9511          "LowerVAARG only handles 64-bit va_arg!");
9512   assert((Subtarget->isTargetLinux() ||
9513           Subtarget->isTargetDarwin()) &&
9514           "Unhandled target in LowerVAARG");
9515   assert(Op.getNode()->getNumOperands() == 4);
9516   SDValue Chain = Op.getOperand(0);
9517   SDValue SrcPtr = Op.getOperand(1);
9518   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9519   unsigned Align = Op.getConstantOperandVal(3);
9520   DebugLoc dl = Op.getDebugLoc();
9521
9522   EVT ArgVT = Op.getNode()->getValueType(0);
9523   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9524   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9525   uint8_t ArgMode;
9526
9527   // Decide which area this value should be read from.
9528   // TODO: Implement the AMD64 ABI in its entirety. This simple
9529   // selection mechanism works only for the basic types.
9530   if (ArgVT == MVT::f80) {
9531     llvm_unreachable("va_arg for f80 not yet implemented");
9532   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9533     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9534   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9535     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9536   } else {
9537     llvm_unreachable("Unhandled argument type in LowerVAARG");
9538   }
9539
9540   if (ArgMode == 2) {
9541     // Sanity Check: Make sure using fp_offset makes sense.
9542     assert(!getTargetMachine().Options.UseSoftFloat &&
9543            !(DAG.getMachineFunction()
9544                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9545            Subtarget->hasSSE1());
9546   }
9547
9548   // Insert VAARG_64 node into the DAG
9549   // VAARG_64 returns two values: Variable Argument Address, Chain
9550   SmallVector<SDValue, 11> InstOps;
9551   InstOps.push_back(Chain);
9552   InstOps.push_back(SrcPtr);
9553   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9554   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9555   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9556   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9557   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9558                                           VTs, &InstOps[0], InstOps.size(),
9559                                           MVT::i64,
9560                                           MachinePointerInfo(SV),
9561                                           /*Align=*/0,
9562                                           /*Volatile=*/false,
9563                                           /*ReadMem=*/true,
9564                                           /*WriteMem=*/true);
9565   Chain = VAARG.getValue(1);
9566
9567   // Load the next argument and return it
9568   return DAG.getLoad(ArgVT, dl,
9569                      Chain,
9570                      VAARG,
9571                      MachinePointerInfo(),
9572                      false, false, false, 0);
9573 }
9574
9575 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9576   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9577   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9578   SDValue Chain = Op.getOperand(0);
9579   SDValue DstPtr = Op.getOperand(1);
9580   SDValue SrcPtr = Op.getOperand(2);
9581   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9582   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9583   DebugLoc DL = Op.getDebugLoc();
9584
9585   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9586                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9587                        false,
9588                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9589 }
9590
9591 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9592 // may or may not be a constant. Takes immediate version of shift as input.
9593 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9594                                    SDValue SrcOp, SDValue ShAmt,
9595                                    SelectionDAG &DAG) {
9596   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9597
9598   if (isa<ConstantSDNode>(ShAmt)) {
9599     // Constant may be a TargetConstant. Use a regular constant.
9600     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9601     switch (Opc) {
9602       default: llvm_unreachable("Unknown target vector shift node");
9603       case X86ISD::VSHLI:
9604       case X86ISD::VSRLI:
9605       case X86ISD::VSRAI:
9606         return DAG.getNode(Opc, dl, VT, SrcOp,
9607                            DAG.getConstant(ShiftAmt, MVT::i32));
9608     }
9609   }
9610
9611   // Change opcode to non-immediate version
9612   switch (Opc) {
9613     default: llvm_unreachable("Unknown target vector shift node");
9614     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9615     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9616     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9617   }
9618
9619   // Need to build a vector containing shift amount
9620   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9621   SDValue ShOps[4];
9622   ShOps[0] = ShAmt;
9623   ShOps[1] = DAG.getConstant(0, MVT::i32);
9624   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9625   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9626
9627   // The return type has to be a 128-bit type with the same element
9628   // type as the input type.
9629   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9630   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9631
9632   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9633   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9634 }
9635
9636 SDValue
9637 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9638   DebugLoc dl = Op.getDebugLoc();
9639   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9640   switch (IntNo) {
9641   default: return SDValue();    // Don't custom lower most intrinsics.
9642   // Comparison intrinsics.
9643   case Intrinsic::x86_sse_comieq_ss:
9644   case Intrinsic::x86_sse_comilt_ss:
9645   case Intrinsic::x86_sse_comile_ss:
9646   case Intrinsic::x86_sse_comigt_ss:
9647   case Intrinsic::x86_sse_comige_ss:
9648   case Intrinsic::x86_sse_comineq_ss:
9649   case Intrinsic::x86_sse_ucomieq_ss:
9650   case Intrinsic::x86_sse_ucomilt_ss:
9651   case Intrinsic::x86_sse_ucomile_ss:
9652   case Intrinsic::x86_sse_ucomigt_ss:
9653   case Intrinsic::x86_sse_ucomige_ss:
9654   case Intrinsic::x86_sse_ucomineq_ss:
9655   case Intrinsic::x86_sse2_comieq_sd:
9656   case Intrinsic::x86_sse2_comilt_sd:
9657   case Intrinsic::x86_sse2_comile_sd:
9658   case Intrinsic::x86_sse2_comigt_sd:
9659   case Intrinsic::x86_sse2_comige_sd:
9660   case Intrinsic::x86_sse2_comineq_sd:
9661   case Intrinsic::x86_sse2_ucomieq_sd:
9662   case Intrinsic::x86_sse2_ucomilt_sd:
9663   case Intrinsic::x86_sse2_ucomile_sd:
9664   case Intrinsic::x86_sse2_ucomigt_sd:
9665   case Intrinsic::x86_sse2_ucomige_sd:
9666   case Intrinsic::x86_sse2_ucomineq_sd: {
9667     unsigned Opc;
9668     ISD::CondCode CC;
9669     switch (IntNo) {
9670     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9671     case Intrinsic::x86_sse_comieq_ss:
9672     case Intrinsic::x86_sse2_comieq_sd:
9673       Opc = X86ISD::COMI;
9674       CC = ISD::SETEQ;
9675       break;
9676     case Intrinsic::x86_sse_comilt_ss:
9677     case Intrinsic::x86_sse2_comilt_sd:
9678       Opc = X86ISD::COMI;
9679       CC = ISD::SETLT;
9680       break;
9681     case Intrinsic::x86_sse_comile_ss:
9682     case Intrinsic::x86_sse2_comile_sd:
9683       Opc = X86ISD::COMI;
9684       CC = ISD::SETLE;
9685       break;
9686     case Intrinsic::x86_sse_comigt_ss:
9687     case Intrinsic::x86_sse2_comigt_sd:
9688       Opc = X86ISD::COMI;
9689       CC = ISD::SETGT;
9690       break;
9691     case Intrinsic::x86_sse_comige_ss:
9692     case Intrinsic::x86_sse2_comige_sd:
9693       Opc = X86ISD::COMI;
9694       CC = ISD::SETGE;
9695       break;
9696     case Intrinsic::x86_sse_comineq_ss:
9697     case Intrinsic::x86_sse2_comineq_sd:
9698       Opc = X86ISD::COMI;
9699       CC = ISD::SETNE;
9700       break;
9701     case Intrinsic::x86_sse_ucomieq_ss:
9702     case Intrinsic::x86_sse2_ucomieq_sd:
9703       Opc = X86ISD::UCOMI;
9704       CC = ISD::SETEQ;
9705       break;
9706     case Intrinsic::x86_sse_ucomilt_ss:
9707     case Intrinsic::x86_sse2_ucomilt_sd:
9708       Opc = X86ISD::UCOMI;
9709       CC = ISD::SETLT;
9710       break;
9711     case Intrinsic::x86_sse_ucomile_ss:
9712     case Intrinsic::x86_sse2_ucomile_sd:
9713       Opc = X86ISD::UCOMI;
9714       CC = ISD::SETLE;
9715       break;
9716     case Intrinsic::x86_sse_ucomigt_ss:
9717     case Intrinsic::x86_sse2_ucomigt_sd:
9718       Opc = X86ISD::UCOMI;
9719       CC = ISD::SETGT;
9720       break;
9721     case Intrinsic::x86_sse_ucomige_ss:
9722     case Intrinsic::x86_sse2_ucomige_sd:
9723       Opc = X86ISD::UCOMI;
9724       CC = ISD::SETGE;
9725       break;
9726     case Intrinsic::x86_sse_ucomineq_ss:
9727     case Intrinsic::x86_sse2_ucomineq_sd:
9728       Opc = X86ISD::UCOMI;
9729       CC = ISD::SETNE;
9730       break;
9731     }
9732
9733     SDValue LHS = Op.getOperand(1);
9734     SDValue RHS = Op.getOperand(2);
9735     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9736     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9737     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9738     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9739                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9740     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9741   }
9742
9743   // Arithmetic intrinsics.
9744   case Intrinsic::x86_sse2_pmulu_dq:
9745   case Intrinsic::x86_avx2_pmulu_dq:
9746     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9747                        Op.getOperand(1), Op.getOperand(2));
9748
9749   // SSE3/AVX horizontal add/sub intrinsics
9750   case Intrinsic::x86_sse3_hadd_ps:
9751   case Intrinsic::x86_sse3_hadd_pd:
9752   case Intrinsic::x86_avx_hadd_ps_256:
9753   case Intrinsic::x86_avx_hadd_pd_256:
9754   case Intrinsic::x86_sse3_hsub_ps:
9755   case Intrinsic::x86_sse3_hsub_pd:
9756   case Intrinsic::x86_avx_hsub_ps_256:
9757   case Intrinsic::x86_avx_hsub_pd_256:
9758   case Intrinsic::x86_ssse3_phadd_w_128:
9759   case Intrinsic::x86_ssse3_phadd_d_128:
9760   case Intrinsic::x86_avx2_phadd_w:
9761   case Intrinsic::x86_avx2_phadd_d:
9762   case Intrinsic::x86_ssse3_phsub_w_128:
9763   case Intrinsic::x86_ssse3_phsub_d_128:
9764   case Intrinsic::x86_avx2_phsub_w:
9765   case Intrinsic::x86_avx2_phsub_d: {
9766     unsigned Opcode;
9767     switch (IntNo) {
9768     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9769     case Intrinsic::x86_sse3_hadd_ps:
9770     case Intrinsic::x86_sse3_hadd_pd:
9771     case Intrinsic::x86_avx_hadd_ps_256:
9772     case Intrinsic::x86_avx_hadd_pd_256:
9773       Opcode = X86ISD::FHADD;
9774       break;
9775     case Intrinsic::x86_sse3_hsub_ps:
9776     case Intrinsic::x86_sse3_hsub_pd:
9777     case Intrinsic::x86_avx_hsub_ps_256:
9778     case Intrinsic::x86_avx_hsub_pd_256:
9779       Opcode = X86ISD::FHSUB;
9780       break;
9781     case Intrinsic::x86_ssse3_phadd_w_128:
9782     case Intrinsic::x86_ssse3_phadd_d_128:
9783     case Intrinsic::x86_avx2_phadd_w:
9784     case Intrinsic::x86_avx2_phadd_d:
9785       Opcode = X86ISD::HADD;
9786       break;
9787     case Intrinsic::x86_ssse3_phsub_w_128:
9788     case Intrinsic::x86_ssse3_phsub_d_128:
9789     case Intrinsic::x86_avx2_phsub_w:
9790     case Intrinsic::x86_avx2_phsub_d:
9791       Opcode = X86ISD::HSUB;
9792       break;
9793     }
9794     return DAG.getNode(Opcode, dl, Op.getValueType(),
9795                        Op.getOperand(1), Op.getOperand(2));
9796   }
9797
9798   // AVX2 variable shift intrinsics
9799   case Intrinsic::x86_avx2_psllv_d:
9800   case Intrinsic::x86_avx2_psllv_q:
9801   case Intrinsic::x86_avx2_psllv_d_256:
9802   case Intrinsic::x86_avx2_psllv_q_256:
9803   case Intrinsic::x86_avx2_psrlv_d:
9804   case Intrinsic::x86_avx2_psrlv_q:
9805   case Intrinsic::x86_avx2_psrlv_d_256:
9806   case Intrinsic::x86_avx2_psrlv_q_256:
9807   case Intrinsic::x86_avx2_psrav_d:
9808   case Intrinsic::x86_avx2_psrav_d_256: {
9809     unsigned Opcode;
9810     switch (IntNo) {
9811     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9812     case Intrinsic::x86_avx2_psllv_d:
9813     case Intrinsic::x86_avx2_psllv_q:
9814     case Intrinsic::x86_avx2_psllv_d_256:
9815     case Intrinsic::x86_avx2_psllv_q_256:
9816       Opcode = ISD::SHL;
9817       break;
9818     case Intrinsic::x86_avx2_psrlv_d:
9819     case Intrinsic::x86_avx2_psrlv_q:
9820     case Intrinsic::x86_avx2_psrlv_d_256:
9821     case Intrinsic::x86_avx2_psrlv_q_256:
9822       Opcode = ISD::SRL;
9823       break;
9824     case Intrinsic::x86_avx2_psrav_d:
9825     case Intrinsic::x86_avx2_psrav_d_256:
9826       Opcode = ISD::SRA;
9827       break;
9828     }
9829     return DAG.getNode(Opcode, dl, Op.getValueType(),
9830                        Op.getOperand(1), Op.getOperand(2));
9831   }
9832
9833   case Intrinsic::x86_ssse3_pshuf_b_128:
9834   case Intrinsic::x86_avx2_pshuf_b:
9835     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9836                        Op.getOperand(1), Op.getOperand(2));
9837
9838   case Intrinsic::x86_ssse3_psign_b_128:
9839   case Intrinsic::x86_ssse3_psign_w_128:
9840   case Intrinsic::x86_ssse3_psign_d_128:
9841   case Intrinsic::x86_avx2_psign_b:
9842   case Intrinsic::x86_avx2_psign_w:
9843   case Intrinsic::x86_avx2_psign_d:
9844     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9845                        Op.getOperand(1), Op.getOperand(2));
9846
9847   case Intrinsic::x86_sse41_insertps:
9848     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9849                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9850
9851   case Intrinsic::x86_avx_vperm2f128_ps_256:
9852   case Intrinsic::x86_avx_vperm2f128_pd_256:
9853   case Intrinsic::x86_avx_vperm2f128_si_256:
9854   case Intrinsic::x86_avx2_vperm2i128:
9855     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9856                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9857
9858   case Intrinsic::x86_avx2_permd:
9859   case Intrinsic::x86_avx2_permps:
9860     // Operands intentionally swapped. Mask is last operand to intrinsic,
9861     // but second operand for node/intruction.
9862     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9863                        Op.getOperand(2), Op.getOperand(1));
9864
9865   // ptest and testp intrinsics. The intrinsic these come from are designed to
9866   // return an integer value, not just an instruction so lower it to the ptest
9867   // or testp pattern and a setcc for the result.
9868   case Intrinsic::x86_sse41_ptestz:
9869   case Intrinsic::x86_sse41_ptestc:
9870   case Intrinsic::x86_sse41_ptestnzc:
9871   case Intrinsic::x86_avx_ptestz_256:
9872   case Intrinsic::x86_avx_ptestc_256:
9873   case Intrinsic::x86_avx_ptestnzc_256:
9874   case Intrinsic::x86_avx_vtestz_ps:
9875   case Intrinsic::x86_avx_vtestc_ps:
9876   case Intrinsic::x86_avx_vtestnzc_ps:
9877   case Intrinsic::x86_avx_vtestz_pd:
9878   case Intrinsic::x86_avx_vtestc_pd:
9879   case Intrinsic::x86_avx_vtestnzc_pd:
9880   case Intrinsic::x86_avx_vtestz_ps_256:
9881   case Intrinsic::x86_avx_vtestc_ps_256:
9882   case Intrinsic::x86_avx_vtestnzc_ps_256:
9883   case Intrinsic::x86_avx_vtestz_pd_256:
9884   case Intrinsic::x86_avx_vtestc_pd_256:
9885   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9886     bool IsTestPacked = false;
9887     unsigned X86CC;
9888     switch (IntNo) {
9889     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9890     case Intrinsic::x86_avx_vtestz_ps:
9891     case Intrinsic::x86_avx_vtestz_pd:
9892     case Intrinsic::x86_avx_vtestz_ps_256:
9893     case Intrinsic::x86_avx_vtestz_pd_256:
9894       IsTestPacked = true; // Fallthrough
9895     case Intrinsic::x86_sse41_ptestz:
9896     case Intrinsic::x86_avx_ptestz_256:
9897       // ZF = 1
9898       X86CC = X86::COND_E;
9899       break;
9900     case Intrinsic::x86_avx_vtestc_ps:
9901     case Intrinsic::x86_avx_vtestc_pd:
9902     case Intrinsic::x86_avx_vtestc_ps_256:
9903     case Intrinsic::x86_avx_vtestc_pd_256:
9904       IsTestPacked = true; // Fallthrough
9905     case Intrinsic::x86_sse41_ptestc:
9906     case Intrinsic::x86_avx_ptestc_256:
9907       // CF = 1
9908       X86CC = X86::COND_B;
9909       break;
9910     case Intrinsic::x86_avx_vtestnzc_ps:
9911     case Intrinsic::x86_avx_vtestnzc_pd:
9912     case Intrinsic::x86_avx_vtestnzc_ps_256:
9913     case Intrinsic::x86_avx_vtestnzc_pd_256:
9914       IsTestPacked = true; // Fallthrough
9915     case Intrinsic::x86_sse41_ptestnzc:
9916     case Intrinsic::x86_avx_ptestnzc_256:
9917       // ZF and CF = 0
9918       X86CC = X86::COND_A;
9919       break;
9920     }
9921
9922     SDValue LHS = Op.getOperand(1);
9923     SDValue RHS = Op.getOperand(2);
9924     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9925     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9926     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9927     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9928     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9929   }
9930
9931   // SSE/AVX shift intrinsics
9932   case Intrinsic::x86_sse2_psll_w:
9933   case Intrinsic::x86_sse2_psll_d:
9934   case Intrinsic::x86_sse2_psll_q:
9935   case Intrinsic::x86_avx2_psll_w:
9936   case Intrinsic::x86_avx2_psll_d:
9937   case Intrinsic::x86_avx2_psll_q:
9938   case Intrinsic::x86_sse2_psrl_w:
9939   case Intrinsic::x86_sse2_psrl_d:
9940   case Intrinsic::x86_sse2_psrl_q:
9941   case Intrinsic::x86_avx2_psrl_w:
9942   case Intrinsic::x86_avx2_psrl_d:
9943   case Intrinsic::x86_avx2_psrl_q:
9944   case Intrinsic::x86_sse2_psra_w:
9945   case Intrinsic::x86_sse2_psra_d:
9946   case Intrinsic::x86_avx2_psra_w:
9947   case Intrinsic::x86_avx2_psra_d: {
9948     unsigned Opcode;
9949     switch (IntNo) {
9950     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9951     case Intrinsic::x86_sse2_psll_w:
9952     case Intrinsic::x86_sse2_psll_d:
9953     case Intrinsic::x86_sse2_psll_q:
9954     case Intrinsic::x86_avx2_psll_w:
9955     case Intrinsic::x86_avx2_psll_d:
9956     case Intrinsic::x86_avx2_psll_q:
9957       Opcode = X86ISD::VSHL;
9958       break;
9959     case Intrinsic::x86_sse2_psrl_w:
9960     case Intrinsic::x86_sse2_psrl_d:
9961     case Intrinsic::x86_sse2_psrl_q:
9962     case Intrinsic::x86_avx2_psrl_w:
9963     case Intrinsic::x86_avx2_psrl_d:
9964     case Intrinsic::x86_avx2_psrl_q:
9965       Opcode = X86ISD::VSRL;
9966       break;
9967     case Intrinsic::x86_sse2_psra_w:
9968     case Intrinsic::x86_sse2_psra_d:
9969     case Intrinsic::x86_avx2_psra_w:
9970     case Intrinsic::x86_avx2_psra_d:
9971       Opcode = X86ISD::VSRA;
9972       break;
9973     }
9974     return DAG.getNode(Opcode, dl, Op.getValueType(),
9975                        Op.getOperand(1), Op.getOperand(2));
9976   }
9977
9978   // SSE/AVX immediate shift intrinsics
9979   case Intrinsic::x86_sse2_pslli_w:
9980   case Intrinsic::x86_sse2_pslli_d:
9981   case Intrinsic::x86_sse2_pslli_q:
9982   case Intrinsic::x86_avx2_pslli_w:
9983   case Intrinsic::x86_avx2_pslli_d:
9984   case Intrinsic::x86_avx2_pslli_q:
9985   case Intrinsic::x86_sse2_psrli_w:
9986   case Intrinsic::x86_sse2_psrli_d:
9987   case Intrinsic::x86_sse2_psrli_q:
9988   case Intrinsic::x86_avx2_psrli_w:
9989   case Intrinsic::x86_avx2_psrli_d:
9990   case Intrinsic::x86_avx2_psrli_q:
9991   case Intrinsic::x86_sse2_psrai_w:
9992   case Intrinsic::x86_sse2_psrai_d:
9993   case Intrinsic::x86_avx2_psrai_w:
9994   case Intrinsic::x86_avx2_psrai_d: {
9995     unsigned Opcode;
9996     switch (IntNo) {
9997     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9998     case Intrinsic::x86_sse2_pslli_w:
9999     case Intrinsic::x86_sse2_pslli_d:
10000     case Intrinsic::x86_sse2_pslli_q:
10001     case Intrinsic::x86_avx2_pslli_w:
10002     case Intrinsic::x86_avx2_pslli_d:
10003     case Intrinsic::x86_avx2_pslli_q:
10004       Opcode = X86ISD::VSHLI;
10005       break;
10006     case Intrinsic::x86_sse2_psrli_w:
10007     case Intrinsic::x86_sse2_psrli_d:
10008     case Intrinsic::x86_sse2_psrli_q:
10009     case Intrinsic::x86_avx2_psrli_w:
10010     case Intrinsic::x86_avx2_psrli_d:
10011     case Intrinsic::x86_avx2_psrli_q:
10012       Opcode = X86ISD::VSRLI;
10013       break;
10014     case Intrinsic::x86_sse2_psrai_w:
10015     case Intrinsic::x86_sse2_psrai_d:
10016     case Intrinsic::x86_avx2_psrai_w:
10017     case Intrinsic::x86_avx2_psrai_d:
10018       Opcode = X86ISD::VSRAI;
10019       break;
10020     }
10021     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10022                                Op.getOperand(1), Op.getOperand(2), DAG);
10023   }
10024
10025   case Intrinsic::x86_sse42_pcmpistria128:
10026   case Intrinsic::x86_sse42_pcmpestria128:
10027   case Intrinsic::x86_sse42_pcmpistric128:
10028   case Intrinsic::x86_sse42_pcmpestric128:
10029   case Intrinsic::x86_sse42_pcmpistrio128:
10030   case Intrinsic::x86_sse42_pcmpestrio128:
10031   case Intrinsic::x86_sse42_pcmpistris128:
10032   case Intrinsic::x86_sse42_pcmpestris128:
10033   case Intrinsic::x86_sse42_pcmpistriz128:
10034   case Intrinsic::x86_sse42_pcmpestriz128: {
10035     unsigned Opcode;
10036     unsigned X86CC;
10037     switch (IntNo) {
10038     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10039     case Intrinsic::x86_sse42_pcmpistria128:
10040       Opcode = X86ISD::PCMPISTRI;
10041       X86CC = X86::COND_A;
10042       break;
10043     case Intrinsic::x86_sse42_pcmpestria128:
10044       Opcode = X86ISD::PCMPESTRI;
10045       X86CC = X86::COND_A;
10046       break;
10047     case Intrinsic::x86_sse42_pcmpistric128:
10048       Opcode = X86ISD::PCMPISTRI;
10049       X86CC = X86::COND_B;
10050       break;
10051     case Intrinsic::x86_sse42_pcmpestric128:
10052       Opcode = X86ISD::PCMPESTRI;
10053       X86CC = X86::COND_B;
10054       break;
10055     case Intrinsic::x86_sse42_pcmpistrio128:
10056       Opcode = X86ISD::PCMPISTRI;
10057       X86CC = X86::COND_O;
10058       break;
10059     case Intrinsic::x86_sse42_pcmpestrio128:
10060       Opcode = X86ISD::PCMPESTRI;
10061       X86CC = X86::COND_O;
10062       break;
10063     case Intrinsic::x86_sse42_pcmpistris128:
10064       Opcode = X86ISD::PCMPISTRI;
10065       X86CC = X86::COND_S;
10066       break;
10067     case Intrinsic::x86_sse42_pcmpestris128:
10068       Opcode = X86ISD::PCMPESTRI;
10069       X86CC = X86::COND_S;
10070       break;
10071     case Intrinsic::x86_sse42_pcmpistriz128:
10072       Opcode = X86ISD::PCMPISTRI;
10073       X86CC = X86::COND_E;
10074       break;
10075     case Intrinsic::x86_sse42_pcmpestriz128:
10076       Opcode = X86ISD::PCMPESTRI;
10077       X86CC = X86::COND_E;
10078       break;
10079     }
10080     SmallVector<SDValue, 5> NewOps;
10081     NewOps.append(Op->op_begin()+1, Op->op_end());
10082     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10083     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10084     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10085                                 DAG.getConstant(X86CC, MVT::i8),
10086                                 SDValue(PCMP.getNode(), 1));
10087     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10088   }
10089
10090   case Intrinsic::x86_sse42_pcmpistri128:
10091   case Intrinsic::x86_sse42_pcmpestri128: {
10092     unsigned Opcode;
10093     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10094       Opcode = X86ISD::PCMPISTRI;
10095     else
10096       Opcode = X86ISD::PCMPESTRI;
10097
10098     SmallVector<SDValue, 5> NewOps;
10099     NewOps.append(Op->op_begin()+1, Op->op_end());
10100     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10101     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10102   }
10103   case Intrinsic::x86_fma_vfmadd_ps:
10104   case Intrinsic::x86_fma_vfmadd_pd:
10105   case Intrinsic::x86_fma_vfmsub_ps:
10106   case Intrinsic::x86_fma_vfmsub_pd:
10107   case Intrinsic::x86_fma_vfnmadd_ps:
10108   case Intrinsic::x86_fma_vfnmadd_pd:
10109   case Intrinsic::x86_fma_vfnmsub_ps:
10110   case Intrinsic::x86_fma_vfnmsub_pd:
10111   case Intrinsic::x86_fma_vfmaddsub_ps:
10112   case Intrinsic::x86_fma_vfmaddsub_pd:
10113   case Intrinsic::x86_fma_vfmsubadd_ps:
10114   case Intrinsic::x86_fma_vfmsubadd_pd:
10115   case Intrinsic::x86_fma_vfmadd_ps_256:
10116   case Intrinsic::x86_fma_vfmadd_pd_256:
10117   case Intrinsic::x86_fma_vfmsub_ps_256:
10118   case Intrinsic::x86_fma_vfmsub_pd_256:
10119   case Intrinsic::x86_fma_vfnmadd_ps_256:
10120   case Intrinsic::x86_fma_vfnmadd_pd_256:
10121   case Intrinsic::x86_fma_vfnmsub_ps_256:
10122   case Intrinsic::x86_fma_vfnmsub_pd_256:
10123   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10124   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10125   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10126   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10127     unsigned Opc;
10128     switch (IntNo) {
10129     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10130     case Intrinsic::x86_fma_vfmadd_ps:
10131     case Intrinsic::x86_fma_vfmadd_pd:
10132     case Intrinsic::x86_fma_vfmadd_ps_256:
10133     case Intrinsic::x86_fma_vfmadd_pd_256:
10134       Opc = X86ISD::FMADD;
10135       break;
10136     case Intrinsic::x86_fma_vfmsub_ps:
10137     case Intrinsic::x86_fma_vfmsub_pd:
10138     case Intrinsic::x86_fma_vfmsub_ps_256:
10139     case Intrinsic::x86_fma_vfmsub_pd_256:
10140       Opc = X86ISD::FMSUB;
10141       break;
10142     case Intrinsic::x86_fma_vfnmadd_ps:
10143     case Intrinsic::x86_fma_vfnmadd_pd:
10144     case Intrinsic::x86_fma_vfnmadd_ps_256:
10145     case Intrinsic::x86_fma_vfnmadd_pd_256:
10146       Opc = X86ISD::FNMADD;
10147       break;
10148     case Intrinsic::x86_fma_vfnmsub_ps:
10149     case Intrinsic::x86_fma_vfnmsub_pd:
10150     case Intrinsic::x86_fma_vfnmsub_ps_256:
10151     case Intrinsic::x86_fma_vfnmsub_pd_256:
10152       Opc = X86ISD::FNMSUB;
10153       break;
10154     case Intrinsic::x86_fma_vfmaddsub_ps:
10155     case Intrinsic::x86_fma_vfmaddsub_pd:
10156     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10157     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10158       Opc = X86ISD::FMADDSUB;
10159       break;
10160     case Intrinsic::x86_fma_vfmsubadd_ps:
10161     case Intrinsic::x86_fma_vfmsubadd_pd:
10162     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10163     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10164       Opc = X86ISD::FMSUBADD;
10165       break;
10166     }
10167
10168     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10169                        Op.getOperand(2), Op.getOperand(3));
10170   }
10171   }
10172 }
10173
10174 SDValue
10175 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10176   DebugLoc dl = Op.getDebugLoc();
10177   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10178   switch (IntNo) {
10179   default: return SDValue();    // Don't custom lower most intrinsics.
10180
10181   // RDRAND intrinsics.
10182   case Intrinsic::x86_rdrand_16:
10183   case Intrinsic::x86_rdrand_32:
10184   case Intrinsic::x86_rdrand_64: {
10185     // Emit the node with the right value type.
10186     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10187     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10188
10189     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10190     // return the value from Rand, which is always 0, casted to i32.
10191     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10192                       DAG.getConstant(1, Op->getValueType(1)),
10193                       DAG.getConstant(X86::COND_B, MVT::i32),
10194                       SDValue(Result.getNode(), 1) };
10195     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10196                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10197                                   Ops, 4);
10198
10199     // Return { result, isValid, chain }.
10200     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10201                        SDValue(Result.getNode(), 2));
10202   }
10203   }
10204 }
10205
10206 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10207                                            SelectionDAG &DAG) const {
10208   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10209   MFI->setReturnAddressIsTaken(true);
10210
10211   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10212   DebugLoc dl = Op.getDebugLoc();
10213
10214   if (Depth > 0) {
10215     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10216     SDValue Offset =
10217       DAG.getConstant(TD->getPointerSize(),
10218                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10219     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10220                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10221                                    FrameAddr, Offset),
10222                        MachinePointerInfo(), false, false, false, 0);
10223   }
10224
10225   // Just load the return address.
10226   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10227   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10228                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10229 }
10230
10231 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10232   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10233   MFI->setFrameAddressIsTaken(true);
10234
10235   EVT VT = Op.getValueType();
10236   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10237   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10238   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10239   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10240   while (Depth--)
10241     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10242                             MachinePointerInfo(),
10243                             false, false, false, 0);
10244   return FrameAddr;
10245 }
10246
10247 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10248                                                      SelectionDAG &DAG) const {
10249   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10250 }
10251
10252 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10253   SDValue Chain     = Op.getOperand(0);
10254   SDValue Offset    = Op.getOperand(1);
10255   SDValue Handler   = Op.getOperand(2);
10256   DebugLoc dl       = Op.getDebugLoc();
10257
10258   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10259                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10260                                      getPointerTy());
10261   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10262
10263   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10264                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10265   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10266   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10267                        false, false, 0);
10268   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10269
10270   return DAG.getNode(X86ISD::EH_RETURN, dl,
10271                      MVT::Other,
10272                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10273 }
10274
10275 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10276                                                   SelectionDAG &DAG) const {
10277   return Op.getOperand(0);
10278 }
10279
10280 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10281                                                 SelectionDAG &DAG) const {
10282   SDValue Root = Op.getOperand(0);
10283   SDValue Trmp = Op.getOperand(1); // trampoline
10284   SDValue FPtr = Op.getOperand(2); // nested function
10285   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10286   DebugLoc dl  = Op.getDebugLoc();
10287
10288   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10289
10290   if (Subtarget->is64Bit()) {
10291     SDValue OutChains[6];
10292
10293     // Large code-model.
10294     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10295     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10296
10297     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10298     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10299
10300     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10301
10302     // Load the pointer to the nested function into R11.
10303     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10304     SDValue Addr = Trmp;
10305     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10306                                 Addr, MachinePointerInfo(TrmpAddr),
10307                                 false, false, 0);
10308
10309     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10310                        DAG.getConstant(2, MVT::i64));
10311     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10312                                 MachinePointerInfo(TrmpAddr, 2),
10313                                 false, false, 2);
10314
10315     // Load the 'nest' parameter value into R10.
10316     // R10 is specified in X86CallingConv.td
10317     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10318     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10319                        DAG.getConstant(10, MVT::i64));
10320     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10321                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10322                                 false, false, 0);
10323
10324     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10325                        DAG.getConstant(12, MVT::i64));
10326     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10327                                 MachinePointerInfo(TrmpAddr, 12),
10328                                 false, false, 2);
10329
10330     // Jump to the nested function.
10331     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10332     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10333                        DAG.getConstant(20, MVT::i64));
10334     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10335                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10336                                 false, false, 0);
10337
10338     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10339     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10340                        DAG.getConstant(22, MVT::i64));
10341     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10342                                 MachinePointerInfo(TrmpAddr, 22),
10343                                 false, false, 0);
10344
10345     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10346   } else {
10347     const Function *Func =
10348       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10349     CallingConv::ID CC = Func->getCallingConv();
10350     unsigned NestReg;
10351
10352     switch (CC) {
10353     default:
10354       llvm_unreachable("Unsupported calling convention");
10355     case CallingConv::C:
10356     case CallingConv::X86_StdCall: {
10357       // Pass 'nest' parameter in ECX.
10358       // Must be kept in sync with X86CallingConv.td
10359       NestReg = X86::ECX;
10360
10361       // Check that ECX wasn't needed by an 'inreg' parameter.
10362       FunctionType *FTy = Func->getFunctionType();
10363       const AttrListPtr &Attrs = Func->getAttributes();
10364
10365       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10366         unsigned InRegCount = 0;
10367         unsigned Idx = 1;
10368
10369         for (FunctionType::param_iterator I = FTy->param_begin(),
10370              E = FTy->param_end(); I != E; ++I, ++Idx)
10371           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10372             // FIXME: should only count parameters that are lowered to integers.
10373             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10374
10375         if (InRegCount > 2) {
10376           report_fatal_error("Nest register in use - reduce number of inreg"
10377                              " parameters!");
10378         }
10379       }
10380       break;
10381     }
10382     case CallingConv::X86_FastCall:
10383     case CallingConv::X86_ThisCall:
10384     case CallingConv::Fast:
10385       // Pass 'nest' parameter in EAX.
10386       // Must be kept in sync with X86CallingConv.td
10387       NestReg = X86::EAX;
10388       break;
10389     }
10390
10391     SDValue OutChains[4];
10392     SDValue Addr, Disp;
10393
10394     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10395                        DAG.getConstant(10, MVT::i32));
10396     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10397
10398     // This is storing the opcode for MOV32ri.
10399     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10400     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10401     OutChains[0] = DAG.getStore(Root, dl,
10402                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10403                                 Trmp, MachinePointerInfo(TrmpAddr),
10404                                 false, false, 0);
10405
10406     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10407                        DAG.getConstant(1, MVT::i32));
10408     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10409                                 MachinePointerInfo(TrmpAddr, 1),
10410                                 false, false, 1);
10411
10412     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10413     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10414                        DAG.getConstant(5, MVT::i32));
10415     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10416                                 MachinePointerInfo(TrmpAddr, 5),
10417                                 false, false, 1);
10418
10419     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10420                        DAG.getConstant(6, MVT::i32));
10421     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10422                                 MachinePointerInfo(TrmpAddr, 6),
10423                                 false, false, 1);
10424
10425     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10426   }
10427 }
10428
10429 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10430                                             SelectionDAG &DAG) const {
10431   /*
10432    The rounding mode is in bits 11:10 of FPSR, and has the following
10433    settings:
10434      00 Round to nearest
10435      01 Round to -inf
10436      10 Round to +inf
10437      11 Round to 0
10438
10439   FLT_ROUNDS, on the other hand, expects the following:
10440     -1 Undefined
10441      0 Round to 0
10442      1 Round to nearest
10443      2 Round to +inf
10444      3 Round to -inf
10445
10446   To perform the conversion, we do:
10447     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10448   */
10449
10450   MachineFunction &MF = DAG.getMachineFunction();
10451   const TargetMachine &TM = MF.getTarget();
10452   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10453   unsigned StackAlignment = TFI.getStackAlignment();
10454   EVT VT = Op.getValueType();
10455   DebugLoc DL = Op.getDebugLoc();
10456
10457   // Save FP Control Word to stack slot
10458   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10459   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10460
10461
10462   MachineMemOperand *MMO =
10463    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10464                            MachineMemOperand::MOStore, 2, 2);
10465
10466   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10467   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10468                                           DAG.getVTList(MVT::Other),
10469                                           Ops, 2, MVT::i16, MMO);
10470
10471   // Load FP Control Word from stack slot
10472   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10473                             MachinePointerInfo(), false, false, false, 0);
10474
10475   // Transform as necessary
10476   SDValue CWD1 =
10477     DAG.getNode(ISD::SRL, DL, MVT::i16,
10478                 DAG.getNode(ISD::AND, DL, MVT::i16,
10479                             CWD, DAG.getConstant(0x800, MVT::i16)),
10480                 DAG.getConstant(11, MVT::i8));
10481   SDValue CWD2 =
10482     DAG.getNode(ISD::SRL, DL, MVT::i16,
10483                 DAG.getNode(ISD::AND, DL, MVT::i16,
10484                             CWD, DAG.getConstant(0x400, MVT::i16)),
10485                 DAG.getConstant(9, MVT::i8));
10486
10487   SDValue RetVal =
10488     DAG.getNode(ISD::AND, DL, MVT::i16,
10489                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10490                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10491                             DAG.getConstant(1, MVT::i16)),
10492                 DAG.getConstant(3, MVT::i16));
10493
10494
10495   return DAG.getNode((VT.getSizeInBits() < 16 ?
10496                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10497 }
10498
10499 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10500   EVT VT = Op.getValueType();
10501   EVT OpVT = VT;
10502   unsigned NumBits = VT.getSizeInBits();
10503   DebugLoc dl = Op.getDebugLoc();
10504
10505   Op = Op.getOperand(0);
10506   if (VT == MVT::i8) {
10507     // Zero extend to i32 since there is not an i8 bsr.
10508     OpVT = MVT::i32;
10509     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10510   }
10511
10512   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10513   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10514   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10515
10516   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10517   SDValue Ops[] = {
10518     Op,
10519     DAG.getConstant(NumBits+NumBits-1, OpVT),
10520     DAG.getConstant(X86::COND_E, MVT::i8),
10521     Op.getValue(1)
10522   };
10523   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10524
10525   // Finally xor with NumBits-1.
10526   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10527
10528   if (VT == MVT::i8)
10529     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10530   return Op;
10531 }
10532
10533 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10534                                                 SelectionDAG &DAG) const {
10535   EVT VT = Op.getValueType();
10536   EVT OpVT = VT;
10537   unsigned NumBits = VT.getSizeInBits();
10538   DebugLoc dl = Op.getDebugLoc();
10539
10540   Op = Op.getOperand(0);
10541   if (VT == MVT::i8) {
10542     // Zero extend to i32 since there is not an i8 bsr.
10543     OpVT = MVT::i32;
10544     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10545   }
10546
10547   // Issue a bsr (scan bits in reverse).
10548   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10549   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10550
10551   // And xor with NumBits-1.
10552   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10553
10554   if (VT == MVT::i8)
10555     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10556   return Op;
10557 }
10558
10559 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10560   EVT VT = Op.getValueType();
10561   unsigned NumBits = VT.getSizeInBits();
10562   DebugLoc dl = Op.getDebugLoc();
10563   Op = Op.getOperand(0);
10564
10565   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10566   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10567   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10568
10569   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10570   SDValue Ops[] = {
10571     Op,
10572     DAG.getConstant(NumBits, VT),
10573     DAG.getConstant(X86::COND_E, MVT::i8),
10574     Op.getValue(1)
10575   };
10576   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10577 }
10578
10579 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10580 // ones, and then concatenate the result back.
10581 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10582   EVT VT = Op.getValueType();
10583
10584   assert(VT.is256BitVector() && VT.isInteger() &&
10585          "Unsupported value type for operation");
10586
10587   unsigned NumElems = VT.getVectorNumElements();
10588   DebugLoc dl = Op.getDebugLoc();
10589
10590   // Extract the LHS vectors
10591   SDValue LHS = Op.getOperand(0);
10592   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10593   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10594
10595   // Extract the RHS vectors
10596   SDValue RHS = Op.getOperand(1);
10597   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10598   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10599
10600   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10601   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10602
10603   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10604                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10605                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10606 }
10607
10608 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10609   assert(Op.getValueType().is256BitVector() &&
10610          Op.getValueType().isInteger() &&
10611          "Only handle AVX 256-bit vector integer operation");
10612   return Lower256IntArith(Op, DAG);
10613 }
10614
10615 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10616   assert(Op.getValueType().is256BitVector() &&
10617          Op.getValueType().isInteger() &&
10618          "Only handle AVX 256-bit vector integer operation");
10619   return Lower256IntArith(Op, DAG);
10620 }
10621
10622 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10623   EVT VT = Op.getValueType();
10624
10625   // Decompose 256-bit ops into smaller 128-bit ops.
10626   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10627     return Lower256IntArith(Op, DAG);
10628
10629   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10630          "Only know how to lower V2I64/V4I64 multiply");
10631
10632   DebugLoc dl = Op.getDebugLoc();
10633
10634   //  Ahi = psrlqi(a, 32);
10635   //  Bhi = psrlqi(b, 32);
10636   //
10637   //  AloBlo = pmuludq(a, b);
10638   //  AloBhi = pmuludq(a, Bhi);
10639   //  AhiBlo = pmuludq(Ahi, b);
10640
10641   //  AloBhi = psllqi(AloBhi, 32);
10642   //  AhiBlo = psllqi(AhiBlo, 32);
10643   //  return AloBlo + AloBhi + AhiBlo;
10644
10645   SDValue A = Op.getOperand(0);
10646   SDValue B = Op.getOperand(1);
10647
10648   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10649
10650   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10651   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10652
10653   // Bit cast to 32-bit vectors for MULUDQ
10654   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10655   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10656   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10657   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10658   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10659
10660   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10661   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10662   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10663
10664   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10665   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10666
10667   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10668   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10669 }
10670
10671 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10672
10673   EVT VT = Op.getValueType();
10674   DebugLoc dl = Op.getDebugLoc();
10675   SDValue R = Op.getOperand(0);
10676   SDValue Amt = Op.getOperand(1);
10677   LLVMContext *Context = DAG.getContext();
10678
10679   if (!Subtarget->hasSSE2())
10680     return SDValue();
10681
10682   // Optimize shl/srl/sra with constant shift amount.
10683   if (isSplatVector(Amt.getNode())) {
10684     SDValue SclrAmt = Amt->getOperand(0);
10685     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10686       uint64_t ShiftAmt = C->getZExtValue();
10687
10688       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10689           (Subtarget->hasAVX2() &&
10690            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10691         if (Op.getOpcode() == ISD::SHL)
10692           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10693                              DAG.getConstant(ShiftAmt, MVT::i32));
10694         if (Op.getOpcode() == ISD::SRL)
10695           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10696                              DAG.getConstant(ShiftAmt, MVT::i32));
10697         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10698           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10699                              DAG.getConstant(ShiftAmt, MVT::i32));
10700       }
10701
10702       if (VT == MVT::v16i8) {
10703         if (Op.getOpcode() == ISD::SHL) {
10704           // Make a large shift.
10705           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10706                                     DAG.getConstant(ShiftAmt, MVT::i32));
10707           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10708           // Zero out the rightmost bits.
10709           SmallVector<SDValue, 16> V(16,
10710                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10711                                                      MVT::i8));
10712           return DAG.getNode(ISD::AND, dl, VT, SHL,
10713                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10714         }
10715         if (Op.getOpcode() == ISD::SRL) {
10716           // Make a large shift.
10717           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10718                                     DAG.getConstant(ShiftAmt, MVT::i32));
10719           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10720           // Zero out the leftmost bits.
10721           SmallVector<SDValue, 16> V(16,
10722                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10723                                                      MVT::i8));
10724           return DAG.getNode(ISD::AND, dl, VT, SRL,
10725                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10726         }
10727         if (Op.getOpcode() == ISD::SRA) {
10728           if (ShiftAmt == 7) {
10729             // R s>> 7  ===  R s< 0
10730             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10731             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10732           }
10733
10734           // R s>> a === ((R u>> a) ^ m) - m
10735           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10736           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10737                                                          MVT::i8));
10738           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10739           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10740           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10741           return Res;
10742         }
10743         llvm_unreachable("Unknown shift opcode.");
10744       }
10745
10746       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10747         if (Op.getOpcode() == ISD::SHL) {
10748           // Make a large shift.
10749           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10750                                     DAG.getConstant(ShiftAmt, MVT::i32));
10751           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10752           // Zero out the rightmost bits.
10753           SmallVector<SDValue, 32> V(32,
10754                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10755                                                      MVT::i8));
10756           return DAG.getNode(ISD::AND, dl, VT, SHL,
10757                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10758         }
10759         if (Op.getOpcode() == ISD::SRL) {
10760           // Make a large shift.
10761           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10762                                     DAG.getConstant(ShiftAmt, MVT::i32));
10763           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10764           // Zero out the leftmost bits.
10765           SmallVector<SDValue, 32> V(32,
10766                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10767                                                      MVT::i8));
10768           return DAG.getNode(ISD::AND, dl, VT, SRL,
10769                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10770         }
10771         if (Op.getOpcode() == ISD::SRA) {
10772           if (ShiftAmt == 7) {
10773             // R s>> 7  ===  R s< 0
10774             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10775             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10776           }
10777
10778           // R s>> a === ((R u>> a) ^ m) - m
10779           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10780           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10781                                                          MVT::i8));
10782           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10783           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10784           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10785           return Res;
10786         }
10787         llvm_unreachable("Unknown shift opcode.");
10788       }
10789     }
10790   }
10791
10792   // Lower SHL with variable shift amount.
10793   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10794     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10795                      DAG.getConstant(23, MVT::i32));
10796
10797     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10798     Constant *C = ConstantDataVector::get(*Context, CV);
10799     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10800     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10801                                  MachinePointerInfo::getConstantPool(),
10802                                  false, false, false, 16);
10803
10804     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10805     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10806     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10807     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10808   }
10809   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10810     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10811
10812     // a = a << 5;
10813     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10814                      DAG.getConstant(5, MVT::i32));
10815     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10816
10817     // Turn 'a' into a mask suitable for VSELECT
10818     SDValue VSelM = DAG.getConstant(0x80, VT);
10819     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10820     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10821
10822     SDValue CM1 = DAG.getConstant(0x0f, VT);
10823     SDValue CM2 = DAG.getConstant(0x3f, VT);
10824
10825     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10826     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10827     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10828                             DAG.getConstant(4, MVT::i32), DAG);
10829     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10830     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10831
10832     // a += a
10833     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10834     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10835     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10836
10837     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10838     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10839     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10840                             DAG.getConstant(2, MVT::i32), DAG);
10841     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10842     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10843
10844     // a += a
10845     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10846     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10847     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10848
10849     // return VSELECT(r, r+r, a);
10850     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10851                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10852     return R;
10853   }
10854
10855   // Decompose 256-bit shifts into smaller 128-bit shifts.
10856   if (VT.is256BitVector()) {
10857     unsigned NumElems = VT.getVectorNumElements();
10858     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10859     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10860
10861     // Extract the two vectors
10862     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10863     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10864
10865     // Recreate the shift amount vectors
10866     SDValue Amt1, Amt2;
10867     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10868       // Constant shift amount
10869       SmallVector<SDValue, 4> Amt1Csts;
10870       SmallVector<SDValue, 4> Amt2Csts;
10871       for (unsigned i = 0; i != NumElems/2; ++i)
10872         Amt1Csts.push_back(Amt->getOperand(i));
10873       for (unsigned i = NumElems/2; i != NumElems; ++i)
10874         Amt2Csts.push_back(Amt->getOperand(i));
10875
10876       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10877                                  &Amt1Csts[0], NumElems/2);
10878       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10879                                  &Amt2Csts[0], NumElems/2);
10880     } else {
10881       // Variable shift amount
10882       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10883       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10884     }
10885
10886     // Issue new vector shifts for the smaller types
10887     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10888     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10889
10890     // Concatenate the result back
10891     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10892   }
10893
10894   return SDValue();
10895 }
10896
10897 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10898   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10899   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10900   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10901   // has only one use.
10902   SDNode *N = Op.getNode();
10903   SDValue LHS = N->getOperand(0);
10904   SDValue RHS = N->getOperand(1);
10905   unsigned BaseOp = 0;
10906   unsigned Cond = 0;
10907   DebugLoc DL = Op.getDebugLoc();
10908   switch (Op.getOpcode()) {
10909   default: llvm_unreachable("Unknown ovf instruction!");
10910   case ISD::SADDO:
10911     // A subtract of one will be selected as a INC. Note that INC doesn't
10912     // set CF, so we can't do this for UADDO.
10913     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10914       if (C->isOne()) {
10915         BaseOp = X86ISD::INC;
10916         Cond = X86::COND_O;
10917         break;
10918       }
10919     BaseOp = X86ISD::ADD;
10920     Cond = X86::COND_O;
10921     break;
10922   case ISD::UADDO:
10923     BaseOp = X86ISD::ADD;
10924     Cond = X86::COND_B;
10925     break;
10926   case ISD::SSUBO:
10927     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10928     // set CF, so we can't do this for USUBO.
10929     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10930       if (C->isOne()) {
10931         BaseOp = X86ISD::DEC;
10932         Cond = X86::COND_O;
10933         break;
10934       }
10935     BaseOp = X86ISD::SUB;
10936     Cond = X86::COND_O;
10937     break;
10938   case ISD::USUBO:
10939     BaseOp = X86ISD::SUB;
10940     Cond = X86::COND_B;
10941     break;
10942   case ISD::SMULO:
10943     BaseOp = X86ISD::SMUL;
10944     Cond = X86::COND_O;
10945     break;
10946   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10947     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10948                                  MVT::i32);
10949     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10950
10951     SDValue SetCC =
10952       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10953                   DAG.getConstant(X86::COND_O, MVT::i32),
10954                   SDValue(Sum.getNode(), 2));
10955
10956     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10957   }
10958   }
10959
10960   // Also sets EFLAGS.
10961   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10962   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10963
10964   SDValue SetCC =
10965     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10966                 DAG.getConstant(Cond, MVT::i32),
10967                 SDValue(Sum.getNode(), 1));
10968
10969   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10970 }
10971
10972 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10973                                                   SelectionDAG &DAG) const {
10974   DebugLoc dl = Op.getDebugLoc();
10975   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10976   EVT VT = Op.getValueType();
10977
10978   if (!Subtarget->hasSSE2() || !VT.isVector())
10979     return SDValue();
10980
10981   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10982                       ExtraVT.getScalarType().getSizeInBits();
10983   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10984
10985   switch (VT.getSimpleVT().SimpleTy) {
10986     default: return SDValue();
10987     case MVT::v8i32:
10988     case MVT::v16i16:
10989       if (!Subtarget->hasAVX())
10990         return SDValue();
10991       if (!Subtarget->hasAVX2()) {
10992         // needs to be split
10993         unsigned NumElems = VT.getVectorNumElements();
10994
10995         // Extract the LHS vectors
10996         SDValue LHS = Op.getOperand(0);
10997         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10998         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10999
11000         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11001         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11002
11003         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11004         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11005         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11006                                    ExtraNumElems/2);
11007         SDValue Extra = DAG.getValueType(ExtraVT);
11008
11009         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11010         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11011
11012         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
11013       }
11014       // fall through
11015     case MVT::v4i32:
11016     case MVT::v8i16: {
11017       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11018                                          Op.getOperand(0), ShAmt, DAG);
11019       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11020     }
11021   }
11022 }
11023
11024
11025 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11026   DebugLoc dl = Op.getDebugLoc();
11027
11028   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11029   // There isn't any reason to disable it if the target processor supports it.
11030   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11031     SDValue Chain = Op.getOperand(0);
11032     SDValue Zero = DAG.getConstant(0, MVT::i32);
11033     SDValue Ops[] = {
11034       DAG.getRegister(X86::ESP, MVT::i32), // Base
11035       DAG.getTargetConstant(1, MVT::i8),   // Scale
11036       DAG.getRegister(0, MVT::i32),        // Index
11037       DAG.getTargetConstant(0, MVT::i32),  // Disp
11038       DAG.getRegister(0, MVT::i32),        // Segment.
11039       Zero,
11040       Chain
11041     };
11042     SDNode *Res =
11043       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11044                           array_lengthof(Ops));
11045     return SDValue(Res, 0);
11046   }
11047
11048   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11049   if (!isDev)
11050     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11051
11052   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11053   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11054   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11055   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11056
11057   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11058   if (!Op1 && !Op2 && !Op3 && Op4)
11059     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11060
11061   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11062   if (Op1 && !Op2 && !Op3 && !Op4)
11063     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11064
11065   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11066   //           (MFENCE)>;
11067   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11068 }
11069
11070 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11071                                              SelectionDAG &DAG) const {
11072   DebugLoc dl = Op.getDebugLoc();
11073   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11074     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11075   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11076     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11077
11078   // The only fence that needs an instruction is a sequentially-consistent
11079   // cross-thread fence.
11080   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11081     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11082     // no-sse2). There isn't any reason to disable it if the target processor
11083     // supports it.
11084     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11085       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11086
11087     SDValue Chain = Op.getOperand(0);
11088     SDValue Zero = DAG.getConstant(0, MVT::i32);
11089     SDValue Ops[] = {
11090       DAG.getRegister(X86::ESP, MVT::i32), // Base
11091       DAG.getTargetConstant(1, MVT::i8),   // Scale
11092       DAG.getRegister(0, MVT::i32),        // Index
11093       DAG.getTargetConstant(0, MVT::i32),  // Disp
11094       DAG.getRegister(0, MVT::i32),        // Segment.
11095       Zero,
11096       Chain
11097     };
11098     SDNode *Res =
11099       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11100                          array_lengthof(Ops));
11101     return SDValue(Res, 0);
11102   }
11103
11104   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11105   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11106 }
11107
11108
11109 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11110   EVT T = Op.getValueType();
11111   DebugLoc DL = Op.getDebugLoc();
11112   unsigned Reg = 0;
11113   unsigned size = 0;
11114   switch(T.getSimpleVT().SimpleTy) {
11115   default: llvm_unreachable("Invalid value type!");
11116   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11117   case MVT::i16: Reg = X86::AX;  size = 2; break;
11118   case MVT::i32: Reg = X86::EAX; size = 4; break;
11119   case MVT::i64:
11120     assert(Subtarget->is64Bit() && "Node not type legal!");
11121     Reg = X86::RAX; size = 8;
11122     break;
11123   }
11124   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11125                                     Op.getOperand(2), SDValue());
11126   SDValue Ops[] = { cpIn.getValue(0),
11127                     Op.getOperand(1),
11128                     Op.getOperand(3),
11129                     DAG.getTargetConstant(size, MVT::i8),
11130                     cpIn.getValue(1) };
11131   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11132   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11133   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11134                                            Ops, 5, T, MMO);
11135   SDValue cpOut =
11136     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11137   return cpOut;
11138 }
11139
11140 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11141                                                  SelectionDAG &DAG) const {
11142   assert(Subtarget->is64Bit() && "Result not type legalized?");
11143   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11144   SDValue TheChain = Op.getOperand(0);
11145   DebugLoc dl = Op.getDebugLoc();
11146   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11147   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11148   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11149                                    rax.getValue(2));
11150   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11151                             DAG.getConstant(32, MVT::i8));
11152   SDValue Ops[] = {
11153     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11154     rdx.getValue(1)
11155   };
11156   return DAG.getMergeValues(Ops, 2, dl);
11157 }
11158
11159 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11160                                             SelectionDAG &DAG) const {
11161   EVT SrcVT = Op.getOperand(0).getValueType();
11162   EVT DstVT = Op.getValueType();
11163   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11164          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11165   assert((DstVT == MVT::i64 ||
11166           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11167          "Unexpected custom BITCAST");
11168   // i64 <=> MMX conversions are Legal.
11169   if (SrcVT==MVT::i64 && DstVT.isVector())
11170     return Op;
11171   if (DstVT==MVT::i64 && SrcVT.isVector())
11172     return Op;
11173   // MMX <=> MMX conversions are Legal.
11174   if (SrcVT.isVector() && DstVT.isVector())
11175     return Op;
11176   // All other conversions need to be expanded.
11177   return SDValue();
11178 }
11179
11180 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11181   SDNode *Node = Op.getNode();
11182   DebugLoc dl = Node->getDebugLoc();
11183   EVT T = Node->getValueType(0);
11184   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11185                               DAG.getConstant(0, T), Node->getOperand(2));
11186   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11187                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11188                        Node->getOperand(0),
11189                        Node->getOperand(1), negOp,
11190                        cast<AtomicSDNode>(Node)->getSrcValue(),
11191                        cast<AtomicSDNode>(Node)->getAlignment(),
11192                        cast<AtomicSDNode>(Node)->getOrdering(),
11193                        cast<AtomicSDNode>(Node)->getSynchScope());
11194 }
11195
11196 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11197   SDNode *Node = Op.getNode();
11198   DebugLoc dl = Node->getDebugLoc();
11199   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11200
11201   // Convert seq_cst store -> xchg
11202   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11203   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11204   //        (The only way to get a 16-byte store is cmpxchg16b)
11205   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11206   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11207       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11208     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11209                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11210                                  Node->getOperand(0),
11211                                  Node->getOperand(1), Node->getOperand(2),
11212                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11213                                  cast<AtomicSDNode>(Node)->getOrdering(),
11214                                  cast<AtomicSDNode>(Node)->getSynchScope());
11215     return Swap.getValue(1);
11216   }
11217   // Other atomic stores have a simple pattern.
11218   return Op;
11219 }
11220
11221 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11222   EVT VT = Op.getNode()->getValueType(0);
11223
11224   // Let legalize expand this if it isn't a legal type yet.
11225   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11226     return SDValue();
11227
11228   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11229
11230   unsigned Opc;
11231   bool ExtraOp = false;
11232   switch (Op.getOpcode()) {
11233   default: llvm_unreachable("Invalid code");
11234   case ISD::ADDC: Opc = X86ISD::ADD; break;
11235   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11236   case ISD::SUBC: Opc = X86ISD::SUB; break;
11237   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11238   }
11239
11240   if (!ExtraOp)
11241     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11242                        Op.getOperand(1));
11243   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11244                      Op.getOperand(1), Op.getOperand(2));
11245 }
11246
11247 /// LowerOperation - Provide custom lowering hooks for some operations.
11248 ///
11249 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11250   switch (Op.getOpcode()) {
11251   default: llvm_unreachable("Should not custom lower this!");
11252   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11253   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11254   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11255   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11256   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11257   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11258   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11259   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11260   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11261   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11262   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11263   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11264   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11265   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11266   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11267   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11268   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11269   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11270   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11271   case ISD::SHL_PARTS:
11272   case ISD::SRA_PARTS:
11273   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11274   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11275   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11276   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11277   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11278   case ISD::FABS:               return LowerFABS(Op, DAG);
11279   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11280   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11281   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11282   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11283   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11284   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11285   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11286   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11287   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11288   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11289   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11290   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11291   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11292   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11293   case ISD::FRAME_TO_ARGS_OFFSET:
11294                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11295   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11296   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11297   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11298   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11299   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11300   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11301   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11302   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11303   case ISD::MUL:                return LowerMUL(Op, DAG);
11304   case ISD::SRA:
11305   case ISD::SRL:
11306   case ISD::SHL:                return LowerShift(Op, DAG);
11307   case ISD::SADDO:
11308   case ISD::UADDO:
11309   case ISD::SSUBO:
11310   case ISD::USUBO:
11311   case ISD::SMULO:
11312   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11313   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11314   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11315   case ISD::ADDC:
11316   case ISD::ADDE:
11317   case ISD::SUBC:
11318   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11319   case ISD::ADD:                return LowerADD(Op, DAG);
11320   case ISD::SUB:                return LowerSUB(Op, DAG);
11321   }
11322 }
11323
11324 static void ReplaceATOMIC_LOAD(SDNode *Node,
11325                                   SmallVectorImpl<SDValue> &Results,
11326                                   SelectionDAG &DAG) {
11327   DebugLoc dl = Node->getDebugLoc();
11328   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11329
11330   // Convert wide load -> cmpxchg8b/cmpxchg16b
11331   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11332   //        (The only way to get a 16-byte load is cmpxchg16b)
11333   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11334   SDValue Zero = DAG.getConstant(0, VT);
11335   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11336                                Node->getOperand(0),
11337                                Node->getOperand(1), Zero, Zero,
11338                                cast<AtomicSDNode>(Node)->getMemOperand(),
11339                                cast<AtomicSDNode>(Node)->getOrdering(),
11340                                cast<AtomicSDNode>(Node)->getSynchScope());
11341   Results.push_back(Swap.getValue(0));
11342   Results.push_back(Swap.getValue(1));
11343 }
11344
11345 static void
11346 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11347                         SelectionDAG &DAG, unsigned NewOp) {
11348   DebugLoc dl = Node->getDebugLoc();
11349   assert (Node->getValueType(0) == MVT::i64 &&
11350           "Only know how to expand i64 atomics");
11351
11352   SDValue Chain = Node->getOperand(0);
11353   SDValue In1 = Node->getOperand(1);
11354   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11355                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11356   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11357                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11358   SDValue Ops[] = { Chain, In1, In2L, In2H };
11359   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11360   SDValue Result =
11361     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11362                             cast<MemSDNode>(Node)->getMemOperand());
11363   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11364   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11365   Results.push_back(Result.getValue(2));
11366 }
11367
11368 /// ReplaceNodeResults - Replace a node with an illegal result type
11369 /// with a new node built out of custom code.
11370 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11371                                            SmallVectorImpl<SDValue>&Results,
11372                                            SelectionDAG &DAG) const {
11373   DebugLoc dl = N->getDebugLoc();
11374   switch (N->getOpcode()) {
11375   default:
11376     llvm_unreachable("Do not know how to custom type legalize this operation!");
11377   case ISD::SIGN_EXTEND_INREG:
11378   case ISD::ADDC:
11379   case ISD::ADDE:
11380   case ISD::SUBC:
11381   case ISD::SUBE:
11382     // We don't want to expand or promote these.
11383     return;
11384   case ISD::FP_TO_SINT:
11385   case ISD::FP_TO_UINT: {
11386     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11387
11388     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11389       return;
11390
11391     std::pair<SDValue,SDValue> Vals =
11392         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11393     SDValue FIST = Vals.first, StackSlot = Vals.second;
11394     if (FIST.getNode() != 0) {
11395       EVT VT = N->getValueType(0);
11396       // Return a load from the stack slot.
11397       if (StackSlot.getNode() != 0)
11398         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11399                                       MachinePointerInfo(),
11400                                       false, false, false, 0));
11401       else
11402         Results.push_back(FIST);
11403     }
11404     return;
11405   }
11406   case ISD::READCYCLECOUNTER: {
11407     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11408     SDValue TheChain = N->getOperand(0);
11409     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11410     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11411                                      rd.getValue(1));
11412     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11413                                      eax.getValue(2));
11414     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11415     SDValue Ops[] = { eax, edx };
11416     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11417     Results.push_back(edx.getValue(1));
11418     return;
11419   }
11420   case ISD::ATOMIC_CMP_SWAP: {
11421     EVT T = N->getValueType(0);
11422     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11423     bool Regs64bit = T == MVT::i128;
11424     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11425     SDValue cpInL, cpInH;
11426     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11427                         DAG.getConstant(0, HalfT));
11428     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11429                         DAG.getConstant(1, HalfT));
11430     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11431                              Regs64bit ? X86::RAX : X86::EAX,
11432                              cpInL, SDValue());
11433     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11434                              Regs64bit ? X86::RDX : X86::EDX,
11435                              cpInH, cpInL.getValue(1));
11436     SDValue swapInL, swapInH;
11437     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11438                           DAG.getConstant(0, HalfT));
11439     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11440                           DAG.getConstant(1, HalfT));
11441     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11442                                Regs64bit ? X86::RBX : X86::EBX,
11443                                swapInL, cpInH.getValue(1));
11444     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11445                                Regs64bit ? X86::RCX : X86::ECX,
11446                                swapInH, swapInL.getValue(1));
11447     SDValue Ops[] = { swapInH.getValue(0),
11448                       N->getOperand(1),
11449                       swapInH.getValue(1) };
11450     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11451     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11452     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11453                                   X86ISD::LCMPXCHG8_DAG;
11454     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11455                                              Ops, 3, T, MMO);
11456     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11457                                         Regs64bit ? X86::RAX : X86::EAX,
11458                                         HalfT, Result.getValue(1));
11459     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11460                                         Regs64bit ? X86::RDX : X86::EDX,
11461                                         HalfT, cpOutL.getValue(2));
11462     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11463     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11464     Results.push_back(cpOutH.getValue(1));
11465     return;
11466   }
11467   case ISD::ATOMIC_LOAD_ADD:
11468   case ISD::ATOMIC_LOAD_AND:
11469   case ISD::ATOMIC_LOAD_NAND:
11470   case ISD::ATOMIC_LOAD_OR:
11471   case ISD::ATOMIC_LOAD_SUB:
11472   case ISD::ATOMIC_LOAD_XOR:
11473   case ISD::ATOMIC_SWAP: {
11474     unsigned Opc;
11475     switch (N->getOpcode()) {
11476     default: llvm_unreachable("Unexpected opcode");
11477     case ISD::ATOMIC_LOAD_ADD:
11478       Opc = X86ISD::ATOMADD64_DAG;
11479       break;
11480     case ISD::ATOMIC_LOAD_AND:
11481       Opc = X86ISD::ATOMAND64_DAG;
11482       break;
11483     case ISD::ATOMIC_LOAD_NAND:
11484       Opc = X86ISD::ATOMNAND64_DAG;
11485       break;
11486     case ISD::ATOMIC_LOAD_OR:
11487       Opc = X86ISD::ATOMOR64_DAG;
11488       break;
11489     case ISD::ATOMIC_LOAD_SUB:
11490       Opc = X86ISD::ATOMSUB64_DAG;
11491       break;
11492     case ISD::ATOMIC_LOAD_XOR:
11493       Opc = X86ISD::ATOMXOR64_DAG;
11494       break;
11495     case ISD::ATOMIC_SWAP:
11496       Opc = X86ISD::ATOMSWAP64_DAG;
11497       break;
11498     }
11499     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11500     return;
11501   }
11502   case ISD::ATOMIC_LOAD:
11503     ReplaceATOMIC_LOAD(N, Results, DAG);
11504   }
11505 }
11506
11507 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11508   switch (Opcode) {
11509   default: return NULL;
11510   case X86ISD::BSF:                return "X86ISD::BSF";
11511   case X86ISD::BSR:                return "X86ISD::BSR";
11512   case X86ISD::SHLD:               return "X86ISD::SHLD";
11513   case X86ISD::SHRD:               return "X86ISD::SHRD";
11514   case X86ISD::FAND:               return "X86ISD::FAND";
11515   case X86ISD::FOR:                return "X86ISD::FOR";
11516   case X86ISD::FXOR:               return "X86ISD::FXOR";
11517   case X86ISD::FSRL:               return "X86ISD::FSRL";
11518   case X86ISD::FILD:               return "X86ISD::FILD";
11519   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11520   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11521   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11522   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11523   case X86ISD::FLD:                return "X86ISD::FLD";
11524   case X86ISD::FST:                return "X86ISD::FST";
11525   case X86ISD::CALL:               return "X86ISD::CALL";
11526   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11527   case X86ISD::BT:                 return "X86ISD::BT";
11528   case X86ISD::CMP:                return "X86ISD::CMP";
11529   case X86ISD::COMI:               return "X86ISD::COMI";
11530   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11531   case X86ISD::SETCC:              return "X86ISD::SETCC";
11532   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11533   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11534   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11535   case X86ISD::CMOV:               return "X86ISD::CMOV";
11536   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11537   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11538   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11539   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11540   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11541   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11542   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11543   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11544   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11545   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11546   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11547   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11548   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11549   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11550   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11551   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11552   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11553   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11554   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11555   case X86ISD::HADD:               return "X86ISD::HADD";
11556   case X86ISD::HSUB:               return "X86ISD::HSUB";
11557   case X86ISD::FHADD:              return "X86ISD::FHADD";
11558   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11559   case X86ISD::FMAX:               return "X86ISD::FMAX";
11560   case X86ISD::FMIN:               return "X86ISD::FMIN";
11561   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11562   case X86ISD::FMINC:              return "X86ISD::FMINC";
11563   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11564   case X86ISD::FRCP:               return "X86ISD::FRCP";
11565   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11566   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11567   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11568   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11569   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11570   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11571   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11572   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11573   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11574   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11575   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11576   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11577   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11578   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11579   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11580   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11581   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11582   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11583   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11584   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11585   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11586   case X86ISD::VSHL:               return "X86ISD::VSHL";
11587   case X86ISD::VSRL:               return "X86ISD::VSRL";
11588   case X86ISD::VSRA:               return "X86ISD::VSRA";
11589   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11590   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11591   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11592   case X86ISD::CMPP:               return "X86ISD::CMPP";
11593   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11594   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11595   case X86ISD::ADD:                return "X86ISD::ADD";
11596   case X86ISD::SUB:                return "X86ISD::SUB";
11597   case X86ISD::ADC:                return "X86ISD::ADC";
11598   case X86ISD::SBB:                return "X86ISD::SBB";
11599   case X86ISD::SMUL:               return "X86ISD::SMUL";
11600   case X86ISD::UMUL:               return "X86ISD::UMUL";
11601   case X86ISD::INC:                return "X86ISD::INC";
11602   case X86ISD::DEC:                return "X86ISD::DEC";
11603   case X86ISD::OR:                 return "X86ISD::OR";
11604   case X86ISD::XOR:                return "X86ISD::XOR";
11605   case X86ISD::AND:                return "X86ISD::AND";
11606   case X86ISD::ANDN:               return "X86ISD::ANDN";
11607   case X86ISD::BLSI:               return "X86ISD::BLSI";
11608   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11609   case X86ISD::BLSR:               return "X86ISD::BLSR";
11610   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11611   case X86ISD::PTEST:              return "X86ISD::PTEST";
11612   case X86ISD::TESTP:              return "X86ISD::TESTP";
11613   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11614   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11615   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11616   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11617   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11618   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11619   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11620   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11621   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11622   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11623   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11624   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11625   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11626   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11627   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11628   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11629   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11630   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11631   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11632   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11633   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11634   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11635   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11636   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11637   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11638   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11639   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11640   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11641   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11642   case X86ISD::SAHF:               return "X86ISD::SAHF";
11643   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11644   case X86ISD::FMADD:              return "X86ISD::FMADD";
11645   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11646   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11647   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11648   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11649   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11650   }
11651 }
11652
11653 // isLegalAddressingMode - Return true if the addressing mode represented
11654 // by AM is legal for this target, for a load/store of the specified type.
11655 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11656                                               Type *Ty) const {
11657   // X86 supports extremely general addressing modes.
11658   CodeModel::Model M = getTargetMachine().getCodeModel();
11659   Reloc::Model R = getTargetMachine().getRelocationModel();
11660
11661   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11662   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11663     return false;
11664
11665   if (AM.BaseGV) {
11666     unsigned GVFlags =
11667       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11668
11669     // If a reference to this global requires an extra load, we can't fold it.
11670     if (isGlobalStubReference(GVFlags))
11671       return false;
11672
11673     // If BaseGV requires a register for the PIC base, we cannot also have a
11674     // BaseReg specified.
11675     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11676       return false;
11677
11678     // If lower 4G is not available, then we must use rip-relative addressing.
11679     if ((M != CodeModel::Small || R != Reloc::Static) &&
11680         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11681       return false;
11682   }
11683
11684   switch (AM.Scale) {
11685   case 0:
11686   case 1:
11687   case 2:
11688   case 4:
11689   case 8:
11690     // These scales always work.
11691     break;
11692   case 3:
11693   case 5:
11694   case 9:
11695     // These scales are formed with basereg+scalereg.  Only accept if there is
11696     // no basereg yet.
11697     if (AM.HasBaseReg)
11698       return false;
11699     break;
11700   default:  // Other stuff never works.
11701     return false;
11702   }
11703
11704   return true;
11705 }
11706
11707
11708 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11709   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11710     return false;
11711   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11712   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11713   if (NumBits1 <= NumBits2)
11714     return false;
11715   return true;
11716 }
11717
11718 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11719   return Imm == (int32_t)Imm;
11720 }
11721
11722 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11723   // Can also use sub to handle negated immediates.
11724   return Imm == (int32_t)Imm;
11725 }
11726
11727 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11728   if (!VT1.isInteger() || !VT2.isInteger())
11729     return false;
11730   unsigned NumBits1 = VT1.getSizeInBits();
11731   unsigned NumBits2 = VT2.getSizeInBits();
11732   if (NumBits1 <= NumBits2)
11733     return false;
11734   return true;
11735 }
11736
11737 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11738   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11739   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11740 }
11741
11742 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11743   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11744   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11745 }
11746
11747 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11748   // i16 instructions are longer (0x66 prefix) and potentially slower.
11749   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11750 }
11751
11752 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11753 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11754 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11755 /// are assumed to be legal.
11756 bool
11757 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11758                                       EVT VT) const {
11759   // Very little shuffling can be done for 64-bit vectors right now.
11760   if (VT.getSizeInBits() == 64)
11761     return false;
11762
11763   // FIXME: pshufb, blends, shifts.
11764   return (VT.getVectorNumElements() == 2 ||
11765           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11766           isMOVLMask(M, VT) ||
11767           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11768           isPSHUFDMask(M, VT) ||
11769           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11770           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11771           isPALIGNRMask(M, VT, Subtarget) ||
11772           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11773           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11774           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11775           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11776 }
11777
11778 bool
11779 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11780                                           EVT VT) const {
11781   unsigned NumElts = VT.getVectorNumElements();
11782   // FIXME: This collection of masks seems suspect.
11783   if (NumElts == 2)
11784     return true;
11785   if (NumElts == 4 && VT.is128BitVector()) {
11786     return (isMOVLMask(Mask, VT)  ||
11787             isCommutedMOVLMask(Mask, VT, true) ||
11788             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11789             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11790   }
11791   return false;
11792 }
11793
11794 //===----------------------------------------------------------------------===//
11795 //                           X86 Scheduler Hooks
11796 //===----------------------------------------------------------------------===//
11797
11798 // private utility function
11799 MachineBasicBlock *
11800 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11801                                                        MachineBasicBlock *MBB,
11802                                                        unsigned regOpc,
11803                                                        unsigned immOpc,
11804                                                        unsigned LoadOpc,
11805                                                        unsigned CXchgOpc,
11806                                                        unsigned notOpc,
11807                                                        unsigned EAXreg,
11808                                                  const TargetRegisterClass *RC,
11809                                                        bool Invert) const {
11810   // For the atomic bitwise operator, we generate
11811   //   thisMBB:
11812   //   newMBB:
11813   //     ld  t1 = [bitinstr.addr]
11814   //     op  t2 = t1, [bitinstr.val]
11815   //     not t3 = t2  (if Invert)
11816   //     mov EAX = t1
11817   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11818   //     bz  newMBB
11819   //     fallthrough -->nextMBB
11820   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11821   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11822   MachineFunction::iterator MBBIter = MBB;
11823   ++MBBIter;
11824
11825   /// First build the CFG
11826   MachineFunction *F = MBB->getParent();
11827   MachineBasicBlock *thisMBB = MBB;
11828   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11829   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11830   F->insert(MBBIter, newMBB);
11831   F->insert(MBBIter, nextMBB);
11832
11833   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11834   nextMBB->splice(nextMBB->begin(), thisMBB,
11835                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11836                   thisMBB->end());
11837   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11838
11839   // Update thisMBB to fall through to newMBB
11840   thisMBB->addSuccessor(newMBB);
11841
11842   // newMBB jumps to itself and fall through to nextMBB
11843   newMBB->addSuccessor(nextMBB);
11844   newMBB->addSuccessor(newMBB);
11845
11846   // Insert instructions into newMBB based on incoming instruction
11847   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11848          "unexpected number of operands");
11849   DebugLoc dl = bInstr->getDebugLoc();
11850   MachineOperand& destOper = bInstr->getOperand(0);
11851   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11852   int numArgs = bInstr->getNumOperands() - 1;
11853   for (int i=0; i < numArgs; ++i)
11854     argOpers[i] = &bInstr->getOperand(i+1);
11855
11856   // x86 address has 4 operands: base, index, scale, and displacement
11857   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11858   int valArgIndx = lastAddrIndx + 1;
11859
11860   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11861   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11862   for (int i=0; i <= lastAddrIndx; ++i)
11863     (*MIB).addOperand(*argOpers[i]);
11864
11865   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11866   assert((argOpers[valArgIndx]->isReg() ||
11867           argOpers[valArgIndx]->isImm()) &&
11868          "invalid operand");
11869   if (argOpers[valArgIndx]->isReg())
11870     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11871   else
11872     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11873   MIB.addReg(t1);
11874   (*MIB).addOperand(*argOpers[valArgIndx]);
11875
11876   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11877   if (Invert) {
11878     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11879   }
11880   else
11881     t3 = t2;
11882
11883   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11884   MIB.addReg(t1);
11885
11886   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11887   for (int i=0; i <= lastAddrIndx; ++i)
11888     (*MIB).addOperand(*argOpers[i]);
11889   MIB.addReg(t3);
11890   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11891   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11892                     bInstr->memoperands_end());
11893
11894   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11895   MIB.addReg(EAXreg);
11896
11897   // insert branch
11898   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11899
11900   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11901   return nextMBB;
11902 }
11903
11904 // private utility function:  64 bit atomics on 32 bit host.
11905 MachineBasicBlock *
11906 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11907                                                        MachineBasicBlock *MBB,
11908                                                        unsigned regOpcL,
11909                                                        unsigned regOpcH,
11910                                                        unsigned immOpcL,
11911                                                        unsigned immOpcH,
11912                                                        bool Invert) const {
11913   // For the atomic bitwise operator, we generate
11914   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11915   //     ld t1,t2 = [bitinstr.addr]
11916   //   newMBB:
11917   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11918   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11919   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11920   //     neg t7, t8 < t5, t6  (if Invert)
11921   //     mov ECX, EBX <- t5, t6
11922   //     mov EAX, EDX <- t1, t2
11923   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11924   //     mov t3, t4 <- EAX, EDX
11925   //     bz  newMBB
11926   //     result in out1, out2
11927   //     fallthrough -->nextMBB
11928
11929   const TargetRegisterClass *RC = &X86::GR32RegClass;
11930   const unsigned LoadOpc = X86::MOV32rm;
11931   const unsigned NotOpc = X86::NOT32r;
11932   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11933   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11934   MachineFunction::iterator MBBIter = MBB;
11935   ++MBBIter;
11936
11937   /// First build the CFG
11938   MachineFunction *F = MBB->getParent();
11939   MachineBasicBlock *thisMBB = MBB;
11940   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11941   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11942   F->insert(MBBIter, newMBB);
11943   F->insert(MBBIter, nextMBB);
11944
11945   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11946   nextMBB->splice(nextMBB->begin(), thisMBB,
11947                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11948                   thisMBB->end());
11949   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11950
11951   // Update thisMBB to fall through to newMBB
11952   thisMBB->addSuccessor(newMBB);
11953
11954   // newMBB jumps to itself and fall through to nextMBB
11955   newMBB->addSuccessor(nextMBB);
11956   newMBB->addSuccessor(newMBB);
11957
11958   DebugLoc dl = bInstr->getDebugLoc();
11959   // Insert instructions into newMBB based on incoming instruction
11960   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11961   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11962          "unexpected number of operands");
11963   MachineOperand& dest1Oper = bInstr->getOperand(0);
11964   MachineOperand& dest2Oper = bInstr->getOperand(1);
11965   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11966   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11967     argOpers[i] = &bInstr->getOperand(i+2);
11968
11969     // We use some of the operands multiple times, so conservatively just
11970     // clear any kill flags that might be present.
11971     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11972       argOpers[i]->setIsKill(false);
11973   }
11974
11975   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11976   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11977
11978   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11979   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11980   for (int i=0; i <= lastAddrIndx; ++i)
11981     (*MIB).addOperand(*argOpers[i]);
11982   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11983   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11984   // add 4 to displacement.
11985   for (int i=0; i <= lastAddrIndx-2; ++i)
11986     (*MIB).addOperand(*argOpers[i]);
11987   MachineOperand newOp3 = *(argOpers[3]);
11988   if (newOp3.isImm())
11989     newOp3.setImm(newOp3.getImm()+4);
11990   else
11991     newOp3.setOffset(newOp3.getOffset()+4);
11992   (*MIB).addOperand(newOp3);
11993   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11994
11995   // t3/4 are defined later, at the bottom of the loop
11996   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11997   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11998   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11999     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12000   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12001     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12002
12003   // The subsequent operations should be using the destination registers of
12004   // the PHI instructions.
12005   t1 = dest1Oper.getReg();
12006   t2 = dest2Oper.getReg();
12007
12008   int valArgIndx = lastAddrIndx + 1;
12009   assert((argOpers[valArgIndx]->isReg() ||
12010           argOpers[valArgIndx]->isImm()) &&
12011          "invalid operand");
12012   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12013   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12014   if (argOpers[valArgIndx]->isReg())
12015     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12016   else
12017     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12018   if (regOpcL != X86::MOV32rr)
12019     MIB.addReg(t1);
12020   (*MIB).addOperand(*argOpers[valArgIndx]);
12021   assert(argOpers[valArgIndx + 1]->isReg() ==
12022          argOpers[valArgIndx]->isReg());
12023   assert(argOpers[valArgIndx + 1]->isImm() ==
12024          argOpers[valArgIndx]->isImm());
12025   if (argOpers[valArgIndx + 1]->isReg())
12026     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12027   else
12028     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12029   if (regOpcH != X86::MOV32rr)
12030     MIB.addReg(t2);
12031   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12032
12033   unsigned t7, t8;
12034   if (Invert) {
12035     t7 = F->getRegInfo().createVirtualRegister(RC);
12036     t8 = F->getRegInfo().createVirtualRegister(RC);
12037     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12038     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12039   } else {
12040     t7 = t5;
12041     t8 = t6;
12042   }
12043
12044   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12045   MIB.addReg(t1);
12046   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12047   MIB.addReg(t2);
12048
12049   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12050   MIB.addReg(t7);
12051   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12052   MIB.addReg(t8);
12053
12054   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12055   for (int i=0; i <= lastAddrIndx; ++i)
12056     (*MIB).addOperand(*argOpers[i]);
12057
12058   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12059   (*MIB).setMemRefs(bInstr->memoperands_begin(),
12060                     bInstr->memoperands_end());
12061
12062   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12063   MIB.addReg(X86::EAX);
12064   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12065   MIB.addReg(X86::EDX);
12066
12067   // insert branch
12068   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12069
12070   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12071   return nextMBB;
12072 }
12073
12074 // private utility function
12075 MachineBasicBlock *
12076 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12077                                                       MachineBasicBlock *MBB,
12078                                                       unsigned cmovOpc) const {
12079   // For the atomic min/max operator, we generate
12080   //   thisMBB:
12081   //   newMBB:
12082   //     ld t1 = [min/max.addr]
12083   //     mov t2 = [min/max.val]
12084   //     cmp  t1, t2
12085   //     cmov[cond] t2 = t1
12086   //     mov EAX = t1
12087   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12088   //     bz   newMBB
12089   //     fallthrough -->nextMBB
12090   //
12091   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12092   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12093   MachineFunction::iterator MBBIter = MBB;
12094   ++MBBIter;
12095
12096   /// First build the CFG
12097   MachineFunction *F = MBB->getParent();
12098   MachineBasicBlock *thisMBB = MBB;
12099   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12100   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12101   F->insert(MBBIter, newMBB);
12102   F->insert(MBBIter, nextMBB);
12103
12104   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12105   nextMBB->splice(nextMBB->begin(), thisMBB,
12106                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12107                   thisMBB->end());
12108   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12109
12110   // Update thisMBB to fall through to newMBB
12111   thisMBB->addSuccessor(newMBB);
12112
12113   // newMBB jumps to newMBB and fall through to nextMBB
12114   newMBB->addSuccessor(nextMBB);
12115   newMBB->addSuccessor(newMBB);
12116
12117   DebugLoc dl = mInstr->getDebugLoc();
12118   // Insert instructions into newMBB based on incoming instruction
12119   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12120          "unexpected number of operands");
12121   MachineOperand& destOper = mInstr->getOperand(0);
12122   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12123   int numArgs = mInstr->getNumOperands() - 1;
12124   for (int i=0; i < numArgs; ++i)
12125     argOpers[i] = &mInstr->getOperand(i+1);
12126
12127   // x86 address has 4 operands: base, index, scale, and displacement
12128   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12129   int valArgIndx = lastAddrIndx + 1;
12130
12131   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12132   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12133   for (int i=0; i <= lastAddrIndx; ++i)
12134     (*MIB).addOperand(*argOpers[i]);
12135
12136   // We only support register and immediate values
12137   assert((argOpers[valArgIndx]->isReg() ||
12138           argOpers[valArgIndx]->isImm()) &&
12139          "invalid operand");
12140
12141   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12142   if (argOpers[valArgIndx]->isReg())
12143     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12144   else
12145     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12146   (*MIB).addOperand(*argOpers[valArgIndx]);
12147
12148   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12149   MIB.addReg(t1);
12150
12151   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12152   MIB.addReg(t1);
12153   MIB.addReg(t2);
12154
12155   // Generate movc
12156   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12157   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12158   MIB.addReg(t2);
12159   MIB.addReg(t1);
12160
12161   // Cmp and exchange if none has modified the memory location
12162   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12163   for (int i=0; i <= lastAddrIndx; ++i)
12164     (*MIB).addOperand(*argOpers[i]);
12165   MIB.addReg(t3);
12166   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12167   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12168                     mInstr->memoperands_end());
12169
12170   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12171   MIB.addReg(X86::EAX);
12172
12173   // insert branch
12174   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12175
12176   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12177   return nextMBB;
12178 }
12179
12180 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12181 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12182 // in the .td file.
12183 MachineBasicBlock *
12184 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12185                             unsigned numArgs, bool memArg) const {
12186   assert(Subtarget->hasSSE42() &&
12187          "Target must have SSE4.2 or AVX features enabled");
12188
12189   DebugLoc dl = MI->getDebugLoc();
12190   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12191   unsigned Opc;
12192   if (!Subtarget->hasAVX()) {
12193     if (memArg)
12194       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12195     else
12196       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12197   } else {
12198     if (memArg)
12199       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12200     else
12201       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12202   }
12203
12204   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12205   for (unsigned i = 0; i < numArgs; ++i) {
12206     MachineOperand &Op = MI->getOperand(i+1);
12207     if (!(Op.isReg() && Op.isImplicit()))
12208       MIB.addOperand(Op);
12209   }
12210   BuildMI(*BB, MI, dl,
12211     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12212     .addReg(X86::XMM0);
12213
12214   MI->eraseFromParent();
12215   return BB;
12216 }
12217
12218 MachineBasicBlock *
12219 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12220   DebugLoc dl = MI->getDebugLoc();
12221   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12222
12223   // Address into RAX/EAX, other two args into ECX, EDX.
12224   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12225   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12226   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12227   for (int i = 0; i < X86::AddrNumOperands; ++i)
12228     MIB.addOperand(MI->getOperand(i));
12229
12230   unsigned ValOps = X86::AddrNumOperands;
12231   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12232     .addReg(MI->getOperand(ValOps).getReg());
12233   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12234     .addReg(MI->getOperand(ValOps+1).getReg());
12235
12236   // The instruction doesn't actually take any operands though.
12237   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12238
12239   MI->eraseFromParent(); // The pseudo is gone now.
12240   return BB;
12241 }
12242
12243 MachineBasicBlock *
12244 X86TargetLowering::EmitVAARG64WithCustomInserter(
12245                    MachineInstr *MI,
12246                    MachineBasicBlock *MBB) const {
12247   // Emit va_arg instruction on X86-64.
12248
12249   // Operands to this pseudo-instruction:
12250   // 0  ) Output        : destination address (reg)
12251   // 1-5) Input         : va_list address (addr, i64mem)
12252   // 6  ) ArgSize       : Size (in bytes) of vararg type
12253   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12254   // 8  ) Align         : Alignment of type
12255   // 9  ) EFLAGS (implicit-def)
12256
12257   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12258   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12259
12260   unsigned DestReg = MI->getOperand(0).getReg();
12261   MachineOperand &Base = MI->getOperand(1);
12262   MachineOperand &Scale = MI->getOperand(2);
12263   MachineOperand &Index = MI->getOperand(3);
12264   MachineOperand &Disp = MI->getOperand(4);
12265   MachineOperand &Segment = MI->getOperand(5);
12266   unsigned ArgSize = MI->getOperand(6).getImm();
12267   unsigned ArgMode = MI->getOperand(7).getImm();
12268   unsigned Align = MI->getOperand(8).getImm();
12269
12270   // Memory Reference
12271   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12272   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12273   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12274
12275   // Machine Information
12276   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12277   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12278   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12279   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12280   DebugLoc DL = MI->getDebugLoc();
12281
12282   // struct va_list {
12283   //   i32   gp_offset
12284   //   i32   fp_offset
12285   //   i64   overflow_area (address)
12286   //   i64   reg_save_area (address)
12287   // }
12288   // sizeof(va_list) = 24
12289   // alignment(va_list) = 8
12290
12291   unsigned TotalNumIntRegs = 6;
12292   unsigned TotalNumXMMRegs = 8;
12293   bool UseGPOffset = (ArgMode == 1);
12294   bool UseFPOffset = (ArgMode == 2);
12295   unsigned MaxOffset = TotalNumIntRegs * 8 +
12296                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12297
12298   /* Align ArgSize to a multiple of 8 */
12299   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12300   bool NeedsAlign = (Align > 8);
12301
12302   MachineBasicBlock *thisMBB = MBB;
12303   MachineBasicBlock *overflowMBB;
12304   MachineBasicBlock *offsetMBB;
12305   MachineBasicBlock *endMBB;
12306
12307   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12308   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12309   unsigned OffsetReg = 0;
12310
12311   if (!UseGPOffset && !UseFPOffset) {
12312     // If we only pull from the overflow region, we don't create a branch.
12313     // We don't need to alter control flow.
12314     OffsetDestReg = 0; // unused
12315     OverflowDestReg = DestReg;
12316
12317     offsetMBB = NULL;
12318     overflowMBB = thisMBB;
12319     endMBB = thisMBB;
12320   } else {
12321     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12322     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12323     // If not, pull from overflow_area. (branch to overflowMBB)
12324     //
12325     //       thisMBB
12326     //         |     .
12327     //         |        .
12328     //     offsetMBB   overflowMBB
12329     //         |        .
12330     //         |     .
12331     //        endMBB
12332
12333     // Registers for the PHI in endMBB
12334     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12335     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12336
12337     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12338     MachineFunction *MF = MBB->getParent();
12339     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12340     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12341     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12342
12343     MachineFunction::iterator MBBIter = MBB;
12344     ++MBBIter;
12345
12346     // Insert the new basic blocks
12347     MF->insert(MBBIter, offsetMBB);
12348     MF->insert(MBBIter, overflowMBB);
12349     MF->insert(MBBIter, endMBB);
12350
12351     // Transfer the remainder of MBB and its successor edges to endMBB.
12352     endMBB->splice(endMBB->begin(), thisMBB,
12353                     llvm::next(MachineBasicBlock::iterator(MI)),
12354                     thisMBB->end());
12355     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12356
12357     // Make offsetMBB and overflowMBB successors of thisMBB
12358     thisMBB->addSuccessor(offsetMBB);
12359     thisMBB->addSuccessor(overflowMBB);
12360
12361     // endMBB is a successor of both offsetMBB and overflowMBB
12362     offsetMBB->addSuccessor(endMBB);
12363     overflowMBB->addSuccessor(endMBB);
12364
12365     // Load the offset value into a register
12366     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12367     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12368       .addOperand(Base)
12369       .addOperand(Scale)
12370       .addOperand(Index)
12371       .addDisp(Disp, UseFPOffset ? 4 : 0)
12372       .addOperand(Segment)
12373       .setMemRefs(MMOBegin, MMOEnd);
12374
12375     // Check if there is enough room left to pull this argument.
12376     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12377       .addReg(OffsetReg)
12378       .addImm(MaxOffset + 8 - ArgSizeA8);
12379
12380     // Branch to "overflowMBB" if offset >= max
12381     // Fall through to "offsetMBB" otherwise
12382     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12383       .addMBB(overflowMBB);
12384   }
12385
12386   // In offsetMBB, emit code to use the reg_save_area.
12387   if (offsetMBB) {
12388     assert(OffsetReg != 0);
12389
12390     // Read the reg_save_area address.
12391     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12392     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12393       .addOperand(Base)
12394       .addOperand(Scale)
12395       .addOperand(Index)
12396       .addDisp(Disp, 16)
12397       .addOperand(Segment)
12398       .setMemRefs(MMOBegin, MMOEnd);
12399
12400     // Zero-extend the offset
12401     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12402       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12403         .addImm(0)
12404         .addReg(OffsetReg)
12405         .addImm(X86::sub_32bit);
12406
12407     // Add the offset to the reg_save_area to get the final address.
12408     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12409       .addReg(OffsetReg64)
12410       .addReg(RegSaveReg);
12411
12412     // Compute the offset for the next argument
12413     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12414     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12415       .addReg(OffsetReg)
12416       .addImm(UseFPOffset ? 16 : 8);
12417
12418     // Store it back into the va_list.
12419     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12420       .addOperand(Base)
12421       .addOperand(Scale)
12422       .addOperand(Index)
12423       .addDisp(Disp, UseFPOffset ? 4 : 0)
12424       .addOperand(Segment)
12425       .addReg(NextOffsetReg)
12426       .setMemRefs(MMOBegin, MMOEnd);
12427
12428     // Jump to endMBB
12429     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12430       .addMBB(endMBB);
12431   }
12432
12433   //
12434   // Emit code to use overflow area
12435   //
12436
12437   // Load the overflow_area address into a register.
12438   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12439   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12440     .addOperand(Base)
12441     .addOperand(Scale)
12442     .addOperand(Index)
12443     .addDisp(Disp, 8)
12444     .addOperand(Segment)
12445     .setMemRefs(MMOBegin, MMOEnd);
12446
12447   // If we need to align it, do so. Otherwise, just copy the address
12448   // to OverflowDestReg.
12449   if (NeedsAlign) {
12450     // Align the overflow address
12451     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12452     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12453
12454     // aligned_addr = (addr + (align-1)) & ~(align-1)
12455     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12456       .addReg(OverflowAddrReg)
12457       .addImm(Align-1);
12458
12459     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12460       .addReg(TmpReg)
12461       .addImm(~(uint64_t)(Align-1));
12462   } else {
12463     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12464       .addReg(OverflowAddrReg);
12465   }
12466
12467   // Compute the next overflow address after this argument.
12468   // (the overflow address should be kept 8-byte aligned)
12469   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12470   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12471     .addReg(OverflowDestReg)
12472     .addImm(ArgSizeA8);
12473
12474   // Store the new overflow address.
12475   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12476     .addOperand(Base)
12477     .addOperand(Scale)
12478     .addOperand(Index)
12479     .addDisp(Disp, 8)
12480     .addOperand(Segment)
12481     .addReg(NextAddrReg)
12482     .setMemRefs(MMOBegin, MMOEnd);
12483
12484   // If we branched, emit the PHI to the front of endMBB.
12485   if (offsetMBB) {
12486     BuildMI(*endMBB, endMBB->begin(), DL,
12487             TII->get(X86::PHI), DestReg)
12488       .addReg(OffsetDestReg).addMBB(offsetMBB)
12489       .addReg(OverflowDestReg).addMBB(overflowMBB);
12490   }
12491
12492   // Erase the pseudo instruction
12493   MI->eraseFromParent();
12494
12495   return endMBB;
12496 }
12497
12498 MachineBasicBlock *
12499 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12500                                                  MachineInstr *MI,
12501                                                  MachineBasicBlock *MBB) const {
12502   // Emit code to save XMM registers to the stack. The ABI says that the
12503   // number of registers to save is given in %al, so it's theoretically
12504   // possible to do an indirect jump trick to avoid saving all of them,
12505   // however this code takes a simpler approach and just executes all
12506   // of the stores if %al is non-zero. It's less code, and it's probably
12507   // easier on the hardware branch predictor, and stores aren't all that
12508   // expensive anyway.
12509
12510   // Create the new basic blocks. One block contains all the XMM stores,
12511   // and one block is the final destination regardless of whether any
12512   // stores were performed.
12513   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12514   MachineFunction *F = MBB->getParent();
12515   MachineFunction::iterator MBBIter = MBB;
12516   ++MBBIter;
12517   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12518   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12519   F->insert(MBBIter, XMMSaveMBB);
12520   F->insert(MBBIter, EndMBB);
12521
12522   // Transfer the remainder of MBB and its successor edges to EndMBB.
12523   EndMBB->splice(EndMBB->begin(), MBB,
12524                  llvm::next(MachineBasicBlock::iterator(MI)),
12525                  MBB->end());
12526   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12527
12528   // The original block will now fall through to the XMM save block.
12529   MBB->addSuccessor(XMMSaveMBB);
12530   // The XMMSaveMBB will fall through to the end block.
12531   XMMSaveMBB->addSuccessor(EndMBB);
12532
12533   // Now add the instructions.
12534   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12535   DebugLoc DL = MI->getDebugLoc();
12536
12537   unsigned CountReg = MI->getOperand(0).getReg();
12538   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12539   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12540
12541   if (!Subtarget->isTargetWin64()) {
12542     // If %al is 0, branch around the XMM save block.
12543     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12544     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12545     MBB->addSuccessor(EndMBB);
12546   }
12547
12548   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12549   // In the XMM save block, save all the XMM argument registers.
12550   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12551     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12552     MachineMemOperand *MMO =
12553       F->getMachineMemOperand(
12554           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12555         MachineMemOperand::MOStore,
12556         /*Size=*/16, /*Align=*/16);
12557     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12558       .addFrameIndex(RegSaveFrameIndex)
12559       .addImm(/*Scale=*/1)
12560       .addReg(/*IndexReg=*/0)
12561       .addImm(/*Disp=*/Offset)
12562       .addReg(/*Segment=*/0)
12563       .addReg(MI->getOperand(i).getReg())
12564       .addMemOperand(MMO);
12565   }
12566
12567   MI->eraseFromParent();   // The pseudo instruction is gone now.
12568
12569   return EndMBB;
12570 }
12571
12572 // The EFLAGS operand of SelectItr might be missing a kill marker
12573 // because there were multiple uses of EFLAGS, and ISel didn't know
12574 // which to mark. Figure out whether SelectItr should have had a
12575 // kill marker, and set it if it should. Returns the correct kill
12576 // marker value.
12577 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12578                                      MachineBasicBlock* BB,
12579                                      const TargetRegisterInfo* TRI) {
12580   // Scan forward through BB for a use/def of EFLAGS.
12581   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12582   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12583     const MachineInstr& mi = *miI;
12584     if (mi.readsRegister(X86::EFLAGS))
12585       return false;
12586     if (mi.definesRegister(X86::EFLAGS))
12587       break; // Should have kill-flag - update below.
12588   }
12589
12590   // If we hit the end of the block, check whether EFLAGS is live into a
12591   // successor.
12592   if (miI == BB->end()) {
12593     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12594                                           sEnd = BB->succ_end();
12595          sItr != sEnd; ++sItr) {
12596       MachineBasicBlock* succ = *sItr;
12597       if (succ->isLiveIn(X86::EFLAGS))
12598         return false;
12599     }
12600   }
12601
12602   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12603   // out. SelectMI should have a kill flag on EFLAGS.
12604   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12605   return true;
12606 }
12607
12608 MachineBasicBlock *
12609 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12610                                      MachineBasicBlock *BB) const {
12611   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12612   DebugLoc DL = MI->getDebugLoc();
12613
12614   // To "insert" a SELECT_CC instruction, we actually have to insert the
12615   // diamond control-flow pattern.  The incoming instruction knows the
12616   // destination vreg to set, the condition code register to branch on, the
12617   // true/false values to select between, and a branch opcode to use.
12618   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12619   MachineFunction::iterator It = BB;
12620   ++It;
12621
12622   //  thisMBB:
12623   //  ...
12624   //   TrueVal = ...
12625   //   cmpTY ccX, r1, r2
12626   //   bCC copy1MBB
12627   //   fallthrough --> copy0MBB
12628   MachineBasicBlock *thisMBB = BB;
12629   MachineFunction *F = BB->getParent();
12630   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12631   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12632   F->insert(It, copy0MBB);
12633   F->insert(It, sinkMBB);
12634
12635   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12636   // live into the sink and copy blocks.
12637   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12638   if (!MI->killsRegister(X86::EFLAGS) &&
12639       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12640     copy0MBB->addLiveIn(X86::EFLAGS);
12641     sinkMBB->addLiveIn(X86::EFLAGS);
12642   }
12643
12644   // Transfer the remainder of BB and its successor edges to sinkMBB.
12645   sinkMBB->splice(sinkMBB->begin(), BB,
12646                   llvm::next(MachineBasicBlock::iterator(MI)),
12647                   BB->end());
12648   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12649
12650   // Add the true and fallthrough blocks as its successors.
12651   BB->addSuccessor(copy0MBB);
12652   BB->addSuccessor(sinkMBB);
12653
12654   // Create the conditional branch instruction.
12655   unsigned Opc =
12656     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12657   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12658
12659   //  copy0MBB:
12660   //   %FalseValue = ...
12661   //   # fallthrough to sinkMBB
12662   copy0MBB->addSuccessor(sinkMBB);
12663
12664   //  sinkMBB:
12665   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12666   //  ...
12667   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12668           TII->get(X86::PHI), MI->getOperand(0).getReg())
12669     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12670     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12671
12672   MI->eraseFromParent();   // The pseudo instruction is gone now.
12673   return sinkMBB;
12674 }
12675
12676 MachineBasicBlock *
12677 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12678                                         bool Is64Bit) const {
12679   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12680   DebugLoc DL = MI->getDebugLoc();
12681   MachineFunction *MF = BB->getParent();
12682   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12683
12684   assert(getTargetMachine().Options.EnableSegmentedStacks);
12685
12686   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12687   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12688
12689   // BB:
12690   //  ... [Till the alloca]
12691   // If stacklet is not large enough, jump to mallocMBB
12692   //
12693   // bumpMBB:
12694   //  Allocate by subtracting from RSP
12695   //  Jump to continueMBB
12696   //
12697   // mallocMBB:
12698   //  Allocate by call to runtime
12699   //
12700   // continueMBB:
12701   //  ...
12702   //  [rest of original BB]
12703   //
12704
12705   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12706   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12707   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12708
12709   MachineRegisterInfo &MRI = MF->getRegInfo();
12710   const TargetRegisterClass *AddrRegClass =
12711     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12712
12713   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12714     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12715     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12716     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12717     sizeVReg = MI->getOperand(1).getReg(),
12718     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12719
12720   MachineFunction::iterator MBBIter = BB;
12721   ++MBBIter;
12722
12723   MF->insert(MBBIter, bumpMBB);
12724   MF->insert(MBBIter, mallocMBB);
12725   MF->insert(MBBIter, continueMBB);
12726
12727   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12728                       (MachineBasicBlock::iterator(MI)), BB->end());
12729   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12730
12731   // Add code to the main basic block to check if the stack limit has been hit,
12732   // and if so, jump to mallocMBB otherwise to bumpMBB.
12733   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12734   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12735     .addReg(tmpSPVReg).addReg(sizeVReg);
12736   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12737     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12738     .addReg(SPLimitVReg);
12739   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12740
12741   // bumpMBB simply decreases the stack pointer, since we know the current
12742   // stacklet has enough space.
12743   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12744     .addReg(SPLimitVReg);
12745   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12746     .addReg(SPLimitVReg);
12747   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12748
12749   // Calls into a routine in libgcc to allocate more space from the heap.
12750   const uint32_t *RegMask =
12751     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12752   if (Is64Bit) {
12753     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12754       .addReg(sizeVReg);
12755     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12756       .addExternalSymbol("__morestack_allocate_stack_space")
12757       .addRegMask(RegMask)
12758       .addReg(X86::RDI, RegState::Implicit)
12759       .addReg(X86::RAX, RegState::ImplicitDefine);
12760   } else {
12761     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12762       .addImm(12);
12763     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12764     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12765       .addExternalSymbol("__morestack_allocate_stack_space")
12766       .addRegMask(RegMask)
12767       .addReg(X86::EAX, RegState::ImplicitDefine);
12768   }
12769
12770   if (!Is64Bit)
12771     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12772       .addImm(16);
12773
12774   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12775     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12776   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12777
12778   // Set up the CFG correctly.
12779   BB->addSuccessor(bumpMBB);
12780   BB->addSuccessor(mallocMBB);
12781   mallocMBB->addSuccessor(continueMBB);
12782   bumpMBB->addSuccessor(continueMBB);
12783
12784   // Take care of the PHI nodes.
12785   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12786           MI->getOperand(0).getReg())
12787     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12788     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12789
12790   // Delete the original pseudo instruction.
12791   MI->eraseFromParent();
12792
12793   // And we're done.
12794   return continueMBB;
12795 }
12796
12797 MachineBasicBlock *
12798 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12799                                           MachineBasicBlock *BB) const {
12800   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12801   DebugLoc DL = MI->getDebugLoc();
12802
12803   assert(!Subtarget->isTargetEnvMacho());
12804
12805   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12806   // non-trivial part is impdef of ESP.
12807
12808   if (Subtarget->isTargetWin64()) {
12809     if (Subtarget->isTargetCygMing()) {
12810       // ___chkstk(Mingw64):
12811       // Clobbers R10, R11, RAX and EFLAGS.
12812       // Updates RSP.
12813       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12814         .addExternalSymbol("___chkstk")
12815         .addReg(X86::RAX, RegState::Implicit)
12816         .addReg(X86::RSP, RegState::Implicit)
12817         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12818         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12819         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12820     } else {
12821       // __chkstk(MSVCRT): does not update stack pointer.
12822       // Clobbers R10, R11 and EFLAGS.
12823       // FIXME: RAX(allocated size) might be reused and not killed.
12824       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12825         .addExternalSymbol("__chkstk")
12826         .addReg(X86::RAX, RegState::Implicit)
12827         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12828       // RAX has the offset to subtracted from RSP.
12829       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12830         .addReg(X86::RSP)
12831         .addReg(X86::RAX);
12832     }
12833   } else {
12834     const char *StackProbeSymbol =
12835       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12836
12837     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12838       .addExternalSymbol(StackProbeSymbol)
12839       .addReg(X86::EAX, RegState::Implicit)
12840       .addReg(X86::ESP, RegState::Implicit)
12841       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12842       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12843       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12844   }
12845
12846   MI->eraseFromParent();   // The pseudo instruction is gone now.
12847   return BB;
12848 }
12849
12850 MachineBasicBlock *
12851 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12852                                       MachineBasicBlock *BB) const {
12853   // This is pretty easy.  We're taking the value that we received from
12854   // our load from the relocation, sticking it in either RDI (x86-64)
12855   // or EAX and doing an indirect call.  The return value will then
12856   // be in the normal return register.
12857   const X86InstrInfo *TII
12858     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12859   DebugLoc DL = MI->getDebugLoc();
12860   MachineFunction *F = BB->getParent();
12861
12862   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12863   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12864
12865   // Get a register mask for the lowered call.
12866   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12867   // proper register mask.
12868   const uint32_t *RegMask =
12869     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12870   if (Subtarget->is64Bit()) {
12871     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12872                                       TII->get(X86::MOV64rm), X86::RDI)
12873     .addReg(X86::RIP)
12874     .addImm(0).addReg(0)
12875     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12876                       MI->getOperand(3).getTargetFlags())
12877     .addReg(0);
12878     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12879     addDirectMem(MIB, X86::RDI);
12880     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12881   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12882     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12883                                       TII->get(X86::MOV32rm), X86::EAX)
12884     .addReg(0)
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::CALL32m));
12890     addDirectMem(MIB, X86::EAX);
12891     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12892   } else {
12893     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12894                                       TII->get(X86::MOV32rm), X86::EAX)
12895     .addReg(TII->getGlobalBaseReg(F))
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   }
12904
12905   MI->eraseFromParent(); // The pseudo instruction is gone now.
12906   return BB;
12907 }
12908
12909 MachineBasicBlock *
12910 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12911                                                MachineBasicBlock *BB) const {
12912   switch (MI->getOpcode()) {
12913   default: llvm_unreachable("Unexpected instr type to insert");
12914   case X86::TAILJMPd64:
12915   case X86::TAILJMPr64:
12916   case X86::TAILJMPm64:
12917     llvm_unreachable("TAILJMP64 would not be touched here.");
12918   case X86::TCRETURNdi64:
12919   case X86::TCRETURNri64:
12920   case X86::TCRETURNmi64:
12921     return BB;
12922   case X86::WIN_ALLOCA:
12923     return EmitLoweredWinAlloca(MI, BB);
12924   case X86::SEG_ALLOCA_32:
12925     return EmitLoweredSegAlloca(MI, BB, false);
12926   case X86::SEG_ALLOCA_64:
12927     return EmitLoweredSegAlloca(MI, BB, true);
12928   case X86::TLSCall_32:
12929   case X86::TLSCall_64:
12930     return EmitLoweredTLSCall(MI, BB);
12931   case X86::CMOV_GR8:
12932   case X86::CMOV_FR32:
12933   case X86::CMOV_FR64:
12934   case X86::CMOV_V4F32:
12935   case X86::CMOV_V2F64:
12936   case X86::CMOV_V2I64:
12937   case X86::CMOV_V8F32:
12938   case X86::CMOV_V4F64:
12939   case X86::CMOV_V4I64:
12940   case X86::CMOV_GR16:
12941   case X86::CMOV_GR32:
12942   case X86::CMOV_RFP32:
12943   case X86::CMOV_RFP64:
12944   case X86::CMOV_RFP80:
12945     return EmitLoweredSelect(MI, BB);
12946
12947   case X86::FP32_TO_INT16_IN_MEM:
12948   case X86::FP32_TO_INT32_IN_MEM:
12949   case X86::FP32_TO_INT64_IN_MEM:
12950   case X86::FP64_TO_INT16_IN_MEM:
12951   case X86::FP64_TO_INT32_IN_MEM:
12952   case X86::FP64_TO_INT64_IN_MEM:
12953   case X86::FP80_TO_INT16_IN_MEM:
12954   case X86::FP80_TO_INT32_IN_MEM:
12955   case X86::FP80_TO_INT64_IN_MEM: {
12956     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12957     DebugLoc DL = MI->getDebugLoc();
12958
12959     // Change the floating point control register to use "round towards zero"
12960     // mode when truncating to an integer value.
12961     MachineFunction *F = BB->getParent();
12962     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12963     addFrameReference(BuildMI(*BB, MI, DL,
12964                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12965
12966     // Load the old value of the high byte of the control word...
12967     unsigned OldCW =
12968       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12969     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12970                       CWFrameIdx);
12971
12972     // Set the high part to be round to zero...
12973     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12974       .addImm(0xC7F);
12975
12976     // Reload the modified control word now...
12977     addFrameReference(BuildMI(*BB, MI, DL,
12978                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12979
12980     // Restore the memory image of control word to original value
12981     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12982       .addReg(OldCW);
12983
12984     // Get the X86 opcode to use.
12985     unsigned Opc;
12986     switch (MI->getOpcode()) {
12987     default: llvm_unreachable("illegal opcode!");
12988     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12989     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12990     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12991     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12992     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12993     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12994     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12995     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12996     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12997     }
12998
12999     X86AddressMode AM;
13000     MachineOperand &Op = MI->getOperand(0);
13001     if (Op.isReg()) {
13002       AM.BaseType = X86AddressMode::RegBase;
13003       AM.Base.Reg = Op.getReg();
13004     } else {
13005       AM.BaseType = X86AddressMode::FrameIndexBase;
13006       AM.Base.FrameIndex = Op.getIndex();
13007     }
13008     Op = MI->getOperand(1);
13009     if (Op.isImm())
13010       AM.Scale = Op.getImm();
13011     Op = MI->getOperand(2);
13012     if (Op.isImm())
13013       AM.IndexReg = Op.getImm();
13014     Op = MI->getOperand(3);
13015     if (Op.isGlobal()) {
13016       AM.GV = Op.getGlobal();
13017     } else {
13018       AM.Disp = Op.getImm();
13019     }
13020     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13021                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13022
13023     // Reload the original control word now.
13024     addFrameReference(BuildMI(*BB, MI, DL,
13025                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13026
13027     MI->eraseFromParent();   // The pseudo instruction is gone now.
13028     return BB;
13029   }
13030     // String/text processing lowering.
13031   case X86::PCMPISTRM128REG:
13032   case X86::VPCMPISTRM128REG:
13033   case X86::PCMPISTRM128MEM:
13034   case X86::VPCMPISTRM128MEM:
13035   case X86::PCMPESTRM128REG:
13036   case X86::VPCMPESTRM128REG:
13037   case X86::PCMPESTRM128MEM:
13038   case X86::VPCMPESTRM128MEM: {
13039     unsigned NumArgs;
13040     bool MemArg;
13041     switch (MI->getOpcode()) {
13042     default: llvm_unreachable("illegal opcode!");
13043     case X86::PCMPISTRM128REG:
13044     case X86::VPCMPISTRM128REG:
13045       NumArgs = 3; MemArg = false; break;
13046     case X86::PCMPISTRM128MEM:
13047     case X86::VPCMPISTRM128MEM:
13048       NumArgs = 3; MemArg = true; break;
13049     case X86::PCMPESTRM128REG:
13050     case X86::VPCMPESTRM128REG:
13051       NumArgs = 5; MemArg = false; break;
13052     case X86::PCMPESTRM128MEM:
13053     case X86::VPCMPESTRM128MEM:
13054       NumArgs = 5; MemArg = true; break;
13055     }
13056     return EmitPCMP(MI, BB, NumArgs, MemArg);
13057   }
13058
13059     // Thread synchronization.
13060   case X86::MONITOR:
13061     return EmitMonitor(MI, BB);
13062
13063     // Atomic Lowering.
13064   case X86::ATOMMIN32:
13065   case X86::ATOMMAX32:
13066   case X86::ATOMUMIN32:
13067   case X86::ATOMUMAX32:
13068   case X86::ATOMMIN16:
13069   case X86::ATOMMAX16:
13070   case X86::ATOMUMIN16:
13071   case X86::ATOMUMAX16:
13072   case X86::ATOMMIN64:
13073   case X86::ATOMMAX64:
13074   case X86::ATOMUMIN64:
13075   case X86::ATOMUMAX64: {
13076     unsigned Opc;
13077     switch (MI->getOpcode()) {
13078     default: llvm_unreachable("illegal opcode!");
13079     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13080     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13081     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13082     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13083     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13084     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13085     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13086     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13087     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13088     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13089     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13090     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13091     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13092     }
13093     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13094   }
13095
13096   case X86::ATOMAND32:
13097   case X86::ATOMOR32:
13098   case X86::ATOMXOR32:
13099   case X86::ATOMNAND32: {
13100     bool Invert = false;
13101     unsigned RegOpc, ImmOpc;
13102     switch (MI->getOpcode()) {
13103     default: llvm_unreachable("illegal opcode!");
13104     case X86::ATOMAND32:
13105       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13106     case X86::ATOMOR32:
13107       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13108     case X86::ATOMXOR32:
13109       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13110     case X86::ATOMNAND32:
13111       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13112     }
13113     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13114                                                X86::MOV32rm, X86::LCMPXCHG32,
13115                                                X86::NOT32r, X86::EAX,
13116                                                &X86::GR32RegClass, Invert);
13117   }
13118
13119   case X86::ATOMAND16:
13120   case X86::ATOMOR16:
13121   case X86::ATOMXOR16:
13122   case X86::ATOMNAND16: {
13123     bool Invert = false;
13124     unsigned RegOpc, ImmOpc;
13125     switch (MI->getOpcode()) {
13126     default: llvm_unreachable("illegal opcode!");
13127     case X86::ATOMAND16:
13128       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13129     case X86::ATOMOR16:
13130       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13131     case X86::ATOMXOR16:
13132       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13133     case X86::ATOMNAND16:
13134       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13135     }
13136     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13137                                                X86::MOV16rm, X86::LCMPXCHG16,
13138                                                X86::NOT16r, X86::AX,
13139                                                &X86::GR16RegClass, Invert);
13140   }
13141
13142   case X86::ATOMAND8:
13143   case X86::ATOMOR8:
13144   case X86::ATOMXOR8:
13145   case X86::ATOMNAND8: {
13146     bool Invert = false;
13147     unsigned RegOpc, ImmOpc;
13148     switch (MI->getOpcode()) {
13149     default: llvm_unreachable("illegal opcode!");
13150     case X86::ATOMAND8:
13151       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13152     case X86::ATOMOR8:
13153       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13154     case X86::ATOMXOR8:
13155       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13156     case X86::ATOMNAND8:
13157       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13158     }
13159     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13160                                                X86::MOV8rm, X86::LCMPXCHG8,
13161                                                X86::NOT8r, X86::AL,
13162                                                &X86::GR8RegClass, Invert);
13163   }
13164
13165   // This group is for 64-bit host.
13166   case X86::ATOMAND64:
13167   case X86::ATOMOR64:
13168   case X86::ATOMXOR64:
13169   case X86::ATOMNAND64: {
13170     bool Invert = false;
13171     unsigned RegOpc, ImmOpc;
13172     switch (MI->getOpcode()) {
13173     default: llvm_unreachable("illegal opcode!");
13174     case X86::ATOMAND64:
13175       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13176     case X86::ATOMOR64:
13177       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13178     case X86::ATOMXOR64:
13179       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13180     case X86::ATOMNAND64:
13181       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13182     }
13183     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13184                                                X86::MOV64rm, X86::LCMPXCHG64,
13185                                                X86::NOT64r, X86::RAX,
13186                                                &X86::GR64RegClass, Invert);
13187   }
13188
13189   // This group does 64-bit operations on a 32-bit host.
13190   case X86::ATOMAND6432:
13191   case X86::ATOMOR6432:
13192   case X86::ATOMXOR6432:
13193   case X86::ATOMNAND6432:
13194   case X86::ATOMADD6432:
13195   case X86::ATOMSUB6432:
13196   case X86::ATOMSWAP6432: {
13197     bool Invert = false;
13198     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13199     switch (MI->getOpcode()) {
13200     default: llvm_unreachable("illegal opcode!");
13201     case X86::ATOMAND6432:
13202       RegOpcL = RegOpcH = X86::AND32rr;
13203       ImmOpcL = ImmOpcH = X86::AND32ri;
13204       break;
13205     case X86::ATOMOR6432:
13206       RegOpcL = RegOpcH = X86::OR32rr;
13207       ImmOpcL = ImmOpcH = X86::OR32ri;
13208       break;
13209     case X86::ATOMXOR6432:
13210       RegOpcL = RegOpcH = X86::XOR32rr;
13211       ImmOpcL = ImmOpcH = X86::XOR32ri;
13212       break;
13213     case X86::ATOMNAND6432:
13214       RegOpcL = RegOpcH = X86::AND32rr;
13215       ImmOpcL = ImmOpcH = X86::AND32ri;
13216       Invert = true;
13217       break;
13218     case X86::ATOMADD6432:
13219       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13220       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13221       break;
13222     case X86::ATOMSUB6432:
13223       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13224       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13225       break;
13226     case X86::ATOMSWAP6432:
13227       RegOpcL = RegOpcH = X86::MOV32rr;
13228       ImmOpcL = ImmOpcH = X86::MOV32ri;
13229       break;
13230     }
13231     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13232                                                ImmOpcL, ImmOpcH, Invert);
13233   }
13234
13235   case X86::VASTART_SAVE_XMM_REGS:
13236     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13237
13238   case X86::VAARG_64:
13239     return EmitVAARG64WithCustomInserter(MI, BB);
13240   }
13241 }
13242
13243 //===----------------------------------------------------------------------===//
13244 //                           X86 Optimization Hooks
13245 //===----------------------------------------------------------------------===//
13246
13247 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13248                                                        APInt &KnownZero,
13249                                                        APInt &KnownOne,
13250                                                        const SelectionDAG &DAG,
13251                                                        unsigned Depth) const {
13252   unsigned BitWidth = KnownZero.getBitWidth();
13253   unsigned Opc = Op.getOpcode();
13254   assert((Opc >= ISD::BUILTIN_OP_END ||
13255           Opc == ISD::INTRINSIC_WO_CHAIN ||
13256           Opc == ISD::INTRINSIC_W_CHAIN ||
13257           Opc == ISD::INTRINSIC_VOID) &&
13258          "Should use MaskedValueIsZero if you don't know whether Op"
13259          " is a target node!");
13260
13261   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13262   switch (Opc) {
13263   default: break;
13264   case X86ISD::ADD:
13265   case X86ISD::SUB:
13266   case X86ISD::ADC:
13267   case X86ISD::SBB:
13268   case X86ISD::SMUL:
13269   case X86ISD::UMUL:
13270   case X86ISD::INC:
13271   case X86ISD::DEC:
13272   case X86ISD::OR:
13273   case X86ISD::XOR:
13274   case X86ISD::AND:
13275     // These nodes' second result is a boolean.
13276     if (Op.getResNo() == 0)
13277       break;
13278     // Fallthrough
13279   case X86ISD::SETCC:
13280     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13281     break;
13282   case ISD::INTRINSIC_WO_CHAIN: {
13283     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13284     unsigned NumLoBits = 0;
13285     switch (IntId) {
13286     default: break;
13287     case Intrinsic::x86_sse_movmsk_ps:
13288     case Intrinsic::x86_avx_movmsk_ps_256:
13289     case Intrinsic::x86_sse2_movmsk_pd:
13290     case Intrinsic::x86_avx_movmsk_pd_256:
13291     case Intrinsic::x86_mmx_pmovmskb:
13292     case Intrinsic::x86_sse2_pmovmskb_128:
13293     case Intrinsic::x86_avx2_pmovmskb: {
13294       // High bits of movmskp{s|d}, pmovmskb are known zero.
13295       switch (IntId) {
13296         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13297         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13298         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13299         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13300         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13301         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13302         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13303         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13304       }
13305       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13306       break;
13307     }
13308     }
13309     break;
13310   }
13311   }
13312 }
13313
13314 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13315                                                          unsigned Depth) const {
13316   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13317   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13318     return Op.getValueType().getScalarType().getSizeInBits();
13319
13320   // Fallback case.
13321   return 1;
13322 }
13323
13324 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13325 /// node is a GlobalAddress + offset.
13326 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13327                                        const GlobalValue* &GA,
13328                                        int64_t &Offset) const {
13329   if (N->getOpcode() == X86ISD::Wrapper) {
13330     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13331       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13332       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13333       return true;
13334     }
13335   }
13336   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13337 }
13338
13339 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13340 /// same as extracting the high 128-bit part of 256-bit vector and then
13341 /// inserting the result into the low part of a new 256-bit vector
13342 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13343   EVT VT = SVOp->getValueType(0);
13344   unsigned NumElems = VT.getVectorNumElements();
13345
13346   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13347   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13348     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13349         SVOp->getMaskElt(j) >= 0)
13350       return false;
13351
13352   return true;
13353 }
13354
13355 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13356 /// same as extracting the low 128-bit part of 256-bit vector and then
13357 /// inserting the result into the high part of a new 256-bit vector
13358 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13359   EVT VT = SVOp->getValueType(0);
13360   unsigned NumElems = VT.getVectorNumElements();
13361
13362   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13363   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13364     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13365         SVOp->getMaskElt(j) >= 0)
13366       return false;
13367
13368   return true;
13369 }
13370
13371 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13372 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13373                                         TargetLowering::DAGCombinerInfo &DCI,
13374                                         const X86Subtarget* Subtarget) {
13375   DebugLoc dl = N->getDebugLoc();
13376   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13377   SDValue V1 = SVOp->getOperand(0);
13378   SDValue V2 = SVOp->getOperand(1);
13379   EVT VT = SVOp->getValueType(0);
13380   unsigned NumElems = VT.getVectorNumElements();
13381
13382   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13383       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13384     //
13385     //                   0,0,0,...
13386     //                      |
13387     //    V      UNDEF    BUILD_VECTOR    UNDEF
13388     //     \      /           \           /
13389     //  CONCAT_VECTOR         CONCAT_VECTOR
13390     //         \                  /
13391     //          \                /
13392     //          RESULT: V + zero extended
13393     //
13394     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13395         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13396         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13397       return SDValue();
13398
13399     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13400       return SDValue();
13401
13402     // To match the shuffle mask, the first half of the mask should
13403     // be exactly the first vector, and all the rest a splat with the
13404     // first element of the second one.
13405     for (unsigned i = 0; i != NumElems/2; ++i)
13406       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13407           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13408         return SDValue();
13409
13410     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13411     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13412       if (Ld->hasNUsesOfValue(1, 0)) {
13413         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13414         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13415         SDValue ResNode =
13416           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13417                                   Ld->getMemoryVT(),
13418                                   Ld->getPointerInfo(),
13419                                   Ld->getAlignment(),
13420                                   false/*isVolatile*/, true/*ReadMem*/,
13421                                   false/*WriteMem*/);
13422         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13423       }
13424     }
13425
13426     // Emit a zeroed vector and insert the desired subvector on its
13427     // first half.
13428     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13429     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13430     return DCI.CombineTo(N, InsV);
13431   }
13432
13433   //===--------------------------------------------------------------------===//
13434   // Combine some shuffles into subvector extracts and inserts:
13435   //
13436
13437   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13438   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13439     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13440     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13441     return DCI.CombineTo(N, InsV);
13442   }
13443
13444   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13445   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13446     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13447     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13448     return DCI.CombineTo(N, InsV);
13449   }
13450
13451   return SDValue();
13452 }
13453
13454 /// PerformShuffleCombine - Performs several different shuffle combines.
13455 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13456                                      TargetLowering::DAGCombinerInfo &DCI,
13457                                      const X86Subtarget *Subtarget) {
13458   DebugLoc dl = N->getDebugLoc();
13459   EVT VT = N->getValueType(0);
13460
13461   // Don't create instructions with illegal types after legalize types has run.
13462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13463   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13464     return SDValue();
13465
13466   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13467   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13468       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13469     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13470
13471   // Only handle 128 wide vector from here on.
13472   if (!VT.is128BitVector())
13473     return SDValue();
13474
13475   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13476   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13477   // consecutive, non-overlapping, and in the right order.
13478   SmallVector<SDValue, 16> Elts;
13479   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13480     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13481
13482   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13483 }
13484
13485
13486 /// DCI, PerformTruncateCombine - Converts truncate operation to
13487 /// a sequence of vector shuffle operations.
13488 /// It is possible when we truncate 256-bit vector to 128-bit vector
13489
13490 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13491                                                   DAGCombinerInfo &DCI) const {
13492   if (!DCI.isBeforeLegalizeOps())
13493     return SDValue();
13494
13495   if (!Subtarget->hasAVX())
13496     return SDValue();
13497
13498   EVT VT = N->getValueType(0);
13499   SDValue Op = N->getOperand(0);
13500   EVT OpVT = Op.getValueType();
13501   DebugLoc dl = N->getDebugLoc();
13502
13503   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13504
13505     if (Subtarget->hasAVX2()) {
13506       // AVX2: v4i64 -> v4i32
13507
13508       // VPERMD
13509       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13510
13511       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13512       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13513                                 ShufMask);
13514
13515       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13516                          DAG.getIntPtrConstant(0));
13517     }
13518
13519     // AVX: v4i64 -> v4i32
13520     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13521                                DAG.getIntPtrConstant(0));
13522
13523     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13524                                DAG.getIntPtrConstant(2));
13525
13526     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13527     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13528
13529     // PSHUFD
13530     static const int ShufMask1[] = {0, 2, 0, 0};
13531
13532     SDValue Undef = DAG.getUNDEF(VT);
13533     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13534     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13535
13536     // MOVLHPS
13537     static const int ShufMask2[] = {0, 1, 4, 5};
13538
13539     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13540   }
13541
13542   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13543
13544     if (Subtarget->hasAVX2()) {
13545       // AVX2: v8i32 -> v8i16
13546
13547       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13548
13549       // PSHUFB
13550       SmallVector<SDValue,32> pshufbMask;
13551       for (unsigned i = 0; i < 2; ++i) {
13552         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13553         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13554         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13555         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13556         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13557         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13558         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13559         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13560         for (unsigned j = 0; j < 8; ++j)
13561           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13562       }
13563       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13564                                &pshufbMask[0], 32);
13565       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13566
13567       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13568
13569       static const int ShufMask[] = {0,  2,  -1,  -1};
13570       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13571                                 &ShufMask[0]);
13572
13573       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13574                        DAG.getIntPtrConstant(0));
13575
13576       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13577     }
13578
13579     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13580                                DAG.getIntPtrConstant(0));
13581
13582     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13583                                DAG.getIntPtrConstant(4));
13584
13585     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13586     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13587
13588     // PSHUFB
13589     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13590                                    -1, -1, -1, -1, -1, -1, -1, -1};
13591
13592     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13593     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13594     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13595
13596     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13597     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13598
13599     // MOVLHPS
13600     static const int ShufMask2[] = {0, 1, 4, 5};
13601
13602     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13603     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13604   }
13605
13606   return SDValue();
13607 }
13608
13609 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13610 /// specific shuffle of a load can be folded into a single element load.
13611 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13612 /// shuffles have been customed lowered so we need to handle those here.
13613 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13614                                          TargetLowering::DAGCombinerInfo &DCI) {
13615   if (DCI.isBeforeLegalizeOps())
13616     return SDValue();
13617
13618   SDValue InVec = N->getOperand(0);
13619   SDValue EltNo = N->getOperand(1);
13620
13621   if (!isa<ConstantSDNode>(EltNo))
13622     return SDValue();
13623
13624   EVT VT = InVec.getValueType();
13625
13626   bool HasShuffleIntoBitcast = false;
13627   if (InVec.getOpcode() == ISD::BITCAST) {
13628     // Don't duplicate a load with other uses.
13629     if (!InVec.hasOneUse())
13630       return SDValue();
13631     EVT BCVT = InVec.getOperand(0).getValueType();
13632     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13633       return SDValue();
13634     InVec = InVec.getOperand(0);
13635     HasShuffleIntoBitcast = true;
13636   }
13637
13638   if (!isTargetShuffle(InVec.getOpcode()))
13639     return SDValue();
13640
13641   // Don't duplicate a load with other uses.
13642   if (!InVec.hasOneUse())
13643     return SDValue();
13644
13645   SmallVector<int, 16> ShuffleMask;
13646   bool UnaryShuffle;
13647   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13648                             UnaryShuffle))
13649     return SDValue();
13650
13651   // Select the input vector, guarding against out of range extract vector.
13652   unsigned NumElems = VT.getVectorNumElements();
13653   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13654   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13655   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13656                                          : InVec.getOperand(1);
13657
13658   // If inputs to shuffle are the same for both ops, then allow 2 uses
13659   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13660
13661   if (LdNode.getOpcode() == ISD::BITCAST) {
13662     // Don't duplicate a load with other uses.
13663     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13664       return SDValue();
13665
13666     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13667     LdNode = LdNode.getOperand(0);
13668   }
13669
13670   if (!ISD::isNormalLoad(LdNode.getNode()))
13671     return SDValue();
13672
13673   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13674
13675   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13676     return SDValue();
13677
13678   if (HasShuffleIntoBitcast) {
13679     // If there's a bitcast before the shuffle, check if the load type and
13680     // alignment is valid.
13681     unsigned Align = LN0->getAlignment();
13682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13683     unsigned NewAlign = TLI.getTargetData()->
13684       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13685
13686     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13687       return SDValue();
13688   }
13689
13690   // All checks match so transform back to vector_shuffle so that DAG combiner
13691   // can finish the job
13692   DebugLoc dl = N->getDebugLoc();
13693
13694   // Create shuffle node taking into account the case that its a unary shuffle
13695   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13696   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13697                                  InVec.getOperand(0), Shuffle,
13698                                  &ShuffleMask[0]);
13699   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13700   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13701                      EltNo);
13702 }
13703
13704 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13705 /// generation and convert it from being a bunch of shuffles and extracts
13706 /// to a simple store and scalar loads to extract the elements.
13707 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13708                                          TargetLowering::DAGCombinerInfo &DCI) {
13709   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13710   if (NewOp.getNode())
13711     return NewOp;
13712
13713   SDValue InputVector = N->getOperand(0);
13714
13715   // Only operate on vectors of 4 elements, where the alternative shuffling
13716   // gets to be more expensive.
13717   if (InputVector.getValueType() != MVT::v4i32)
13718     return SDValue();
13719
13720   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13721   // single use which is a sign-extend or zero-extend, and all elements are
13722   // used.
13723   SmallVector<SDNode *, 4> Uses;
13724   unsigned ExtractedElements = 0;
13725   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13726        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13727     if (UI.getUse().getResNo() != InputVector.getResNo())
13728       return SDValue();
13729
13730     SDNode *Extract = *UI;
13731     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13732       return SDValue();
13733
13734     if (Extract->getValueType(0) != MVT::i32)
13735       return SDValue();
13736     if (!Extract->hasOneUse())
13737       return SDValue();
13738     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13739         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13740       return SDValue();
13741     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13742       return SDValue();
13743
13744     // Record which element was extracted.
13745     ExtractedElements |=
13746       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13747
13748     Uses.push_back(Extract);
13749   }
13750
13751   // If not all the elements were used, this may not be worthwhile.
13752   if (ExtractedElements != 15)
13753     return SDValue();
13754
13755   // Ok, we've now decided to do the transformation.
13756   DebugLoc dl = InputVector.getDebugLoc();
13757
13758   // Store the value to a temporary stack slot.
13759   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13760   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13761                             MachinePointerInfo(), false, false, 0);
13762
13763   // Replace each use (extract) with a load of the appropriate element.
13764   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13765        UE = Uses.end(); UI != UE; ++UI) {
13766     SDNode *Extract = *UI;
13767
13768     // cOMpute the element's address.
13769     SDValue Idx = Extract->getOperand(1);
13770     unsigned EltSize =
13771         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13772     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13773     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13774     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13775
13776     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13777                                      StackPtr, OffsetVal);
13778
13779     // Load the scalar.
13780     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13781                                      ScalarAddr, MachinePointerInfo(),
13782                                      false, false, false, 0);
13783
13784     // Replace the exact with the load.
13785     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13786   }
13787
13788   // The replacement was made in place; don't return anything.
13789   return SDValue();
13790 }
13791
13792 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13793 /// nodes.
13794 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13795                                     TargetLowering::DAGCombinerInfo &DCI,
13796                                     const X86Subtarget *Subtarget) {
13797   DebugLoc DL = N->getDebugLoc();
13798   SDValue Cond = N->getOperand(0);
13799   // Get the LHS/RHS of the select.
13800   SDValue LHS = N->getOperand(1);
13801   SDValue RHS = N->getOperand(2);
13802   EVT VT = LHS.getValueType();
13803
13804   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13805   // instructions match the semantics of the common C idiom x<y?x:y but not
13806   // x<=y?x:y, because of how they handle negative zero (which can be
13807   // ignored in unsafe-math mode).
13808   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13809       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13810       (Subtarget->hasSSE2() ||
13811        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13812     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13813
13814     unsigned Opcode = 0;
13815     // Check for x CC y ? x : y.
13816     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13817         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13818       switch (CC) {
13819       default: break;
13820       case ISD::SETULT:
13821         // Converting this to a min would handle NaNs incorrectly, and swapping
13822         // the operands would cause it to handle comparisons between positive
13823         // and negative zero incorrectly.
13824         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13825           if (!DAG.getTarget().Options.UnsafeFPMath &&
13826               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13827             break;
13828           std::swap(LHS, RHS);
13829         }
13830         Opcode = X86ISD::FMIN;
13831         break;
13832       case ISD::SETOLE:
13833         // Converting this to a min would handle comparisons between positive
13834         // and negative zero incorrectly.
13835         if (!DAG.getTarget().Options.UnsafeFPMath &&
13836             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13837           break;
13838         Opcode = X86ISD::FMIN;
13839         break;
13840       case ISD::SETULE:
13841         // Converting this to a min would handle both negative zeros and NaNs
13842         // incorrectly, but we can swap the operands to fix both.
13843         std::swap(LHS, RHS);
13844       case ISD::SETOLT:
13845       case ISD::SETLT:
13846       case ISD::SETLE:
13847         Opcode = X86ISD::FMIN;
13848         break;
13849
13850       case ISD::SETOGE:
13851         // Converting this to a max would handle comparisons between positive
13852         // and negative zero incorrectly.
13853         if (!DAG.getTarget().Options.UnsafeFPMath &&
13854             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13855           break;
13856         Opcode = X86ISD::FMAX;
13857         break;
13858       case ISD::SETUGT:
13859         // Converting this to a max would handle NaNs incorrectly, and swapping
13860         // the operands would cause it to handle comparisons between positive
13861         // and negative zero incorrectly.
13862         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13863           if (!DAG.getTarget().Options.UnsafeFPMath &&
13864               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13865             break;
13866           std::swap(LHS, RHS);
13867         }
13868         Opcode = X86ISD::FMAX;
13869         break;
13870       case ISD::SETUGE:
13871         // Converting this to a max would handle both negative zeros and NaNs
13872         // incorrectly, but we can swap the operands to fix both.
13873         std::swap(LHS, RHS);
13874       case ISD::SETOGT:
13875       case ISD::SETGT:
13876       case ISD::SETGE:
13877         Opcode = X86ISD::FMAX;
13878         break;
13879       }
13880     // Check for x CC y ? y : x -- a min/max with reversed arms.
13881     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13882                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13883       switch (CC) {
13884       default: break;
13885       case ISD::SETOGE:
13886         // Converting this to a min would handle comparisons between positive
13887         // and negative zero incorrectly, and swapping the operands would
13888         // cause it to handle NaNs incorrectly.
13889         if (!DAG.getTarget().Options.UnsafeFPMath &&
13890             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13891           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13892             break;
13893           std::swap(LHS, RHS);
13894         }
13895         Opcode = X86ISD::FMIN;
13896         break;
13897       case ISD::SETUGT:
13898         // Converting this to a min would handle NaNs incorrectly.
13899         if (!DAG.getTarget().Options.UnsafeFPMath &&
13900             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13901           break;
13902         Opcode = X86ISD::FMIN;
13903         break;
13904       case ISD::SETUGE:
13905         // Converting this to a min would handle both negative zeros and NaNs
13906         // incorrectly, but we can swap the operands to fix both.
13907         std::swap(LHS, RHS);
13908       case ISD::SETOGT:
13909       case ISD::SETGT:
13910       case ISD::SETGE:
13911         Opcode = X86ISD::FMIN;
13912         break;
13913
13914       case ISD::SETULT:
13915         // Converting this to a max would handle NaNs incorrectly.
13916         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13917           break;
13918         Opcode = X86ISD::FMAX;
13919         break;
13920       case ISD::SETOLE:
13921         // Converting this to a max would handle comparisons between positive
13922         // and negative zero incorrectly, and swapping the operands would
13923         // cause it to handle NaNs incorrectly.
13924         if (!DAG.getTarget().Options.UnsafeFPMath &&
13925             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13926           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13927             break;
13928           std::swap(LHS, RHS);
13929         }
13930         Opcode = X86ISD::FMAX;
13931         break;
13932       case ISD::SETULE:
13933         // Converting this to a max would handle both negative zeros and NaNs
13934         // incorrectly, but we can swap the operands to fix both.
13935         std::swap(LHS, RHS);
13936       case ISD::SETOLT:
13937       case ISD::SETLT:
13938       case ISD::SETLE:
13939         Opcode = X86ISD::FMAX;
13940         break;
13941       }
13942     }
13943
13944     if (Opcode)
13945       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13946   }
13947
13948   // If this is a select between two integer constants, try to do some
13949   // optimizations.
13950   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13951     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13952       // Don't do this for crazy integer types.
13953       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13954         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13955         // so that TrueC (the true value) is larger than FalseC.
13956         bool NeedsCondInvert = false;
13957
13958         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13959             // Efficiently invertible.
13960             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13961              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13962               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13963           NeedsCondInvert = true;
13964           std::swap(TrueC, FalseC);
13965         }
13966
13967         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13968         if (FalseC->getAPIntValue() == 0 &&
13969             TrueC->getAPIntValue().isPowerOf2()) {
13970           if (NeedsCondInvert) // Invert the condition if needed.
13971             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13972                                DAG.getConstant(1, Cond.getValueType()));
13973
13974           // Zero extend the condition if needed.
13975           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13976
13977           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13978           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13979                              DAG.getConstant(ShAmt, MVT::i8));
13980         }
13981
13982         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13983         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13984           if (NeedsCondInvert) // Invert the condition if needed.
13985             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13986                                DAG.getConstant(1, Cond.getValueType()));
13987
13988           // Zero extend the condition if needed.
13989           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13990                              FalseC->getValueType(0), Cond);
13991           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13992                              SDValue(FalseC, 0));
13993         }
13994
13995         // Optimize cases that will turn into an LEA instruction.  This requires
13996         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13997         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13998           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13999           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14000
14001           bool isFastMultiplier = false;
14002           if (Diff < 10) {
14003             switch ((unsigned char)Diff) {
14004               default: break;
14005               case 1:  // result = add base, cond
14006               case 2:  // result = lea base(    , cond*2)
14007               case 3:  // result = lea base(cond, cond*2)
14008               case 4:  // result = lea base(    , cond*4)
14009               case 5:  // result = lea base(cond, cond*4)
14010               case 8:  // result = lea base(    , cond*8)
14011               case 9:  // result = lea base(cond, cond*8)
14012                 isFastMultiplier = true;
14013                 break;
14014             }
14015           }
14016
14017           if (isFastMultiplier) {
14018             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14019             if (NeedsCondInvert) // Invert the condition if needed.
14020               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14021                                  DAG.getConstant(1, Cond.getValueType()));
14022
14023             // Zero extend the condition if needed.
14024             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14025                                Cond);
14026             // Scale the condition by the difference.
14027             if (Diff != 1)
14028               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14029                                  DAG.getConstant(Diff, Cond.getValueType()));
14030
14031             // Add the base if non-zero.
14032             if (FalseC->getAPIntValue() != 0)
14033               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14034                                  SDValue(FalseC, 0));
14035             return Cond;
14036           }
14037         }
14038       }
14039   }
14040
14041   // Canonicalize max and min:
14042   // (x > y) ? x : y -> (x >= y) ? x : y
14043   // (x < y) ? x : y -> (x <= y) ? x : y
14044   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14045   // the need for an extra compare
14046   // against zero. e.g.
14047   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14048   // subl   %esi, %edi
14049   // testl  %edi, %edi
14050   // movl   $0, %eax
14051   // cmovgl %edi, %eax
14052   // =>
14053   // xorl   %eax, %eax
14054   // subl   %esi, $edi
14055   // cmovsl %eax, %edi
14056   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14057       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14058       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14059     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14060     switch (CC) {
14061     default: break;
14062     case ISD::SETLT:
14063     case ISD::SETGT: {
14064       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14065       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14066                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14067       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14068     }
14069     }
14070   }
14071
14072   // If we know that this node is legal then we know that it is going to be
14073   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14074   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14075   // to simplify previous instructions.
14076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14077   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14078       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14079     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14080
14081     // Don't optimize vector selects that map to mask-registers.
14082     if (BitWidth == 1)
14083       return SDValue();
14084
14085     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14086     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14087
14088     APInt KnownZero, KnownOne;
14089     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14090                                           DCI.isBeforeLegalizeOps());
14091     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14092         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14093       DCI.CommitTargetLoweringOpt(TLO);
14094   }
14095
14096   return SDValue();
14097 }
14098
14099 // Check whether a boolean test is testing a boolean value generated by
14100 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14101 // code.
14102 //
14103 // Simplify the following patterns:
14104 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14105 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14106 // to (Op EFLAGS Cond)
14107 //
14108 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14109 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14110 // to (Op EFLAGS !Cond)
14111 //
14112 // where Op could be BRCOND or CMOV.
14113 //
14114 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14115   // Quit if not CMP and SUB with its value result used.
14116   if (Cmp.getOpcode() != X86ISD::CMP &&
14117       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14118       return SDValue();
14119
14120   // Quit if not used as a boolean value.
14121   if (CC != X86::COND_E && CC != X86::COND_NE)
14122     return SDValue();
14123
14124   // Check CMP operands. One of them should be 0 or 1 and the other should be
14125   // an SetCC or extended from it.
14126   SDValue Op1 = Cmp.getOperand(0);
14127   SDValue Op2 = Cmp.getOperand(1);
14128
14129   SDValue SetCC;
14130   const ConstantSDNode* C = 0;
14131   bool needOppositeCond = (CC == X86::COND_E);
14132
14133   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14134     SetCC = Op2;
14135   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14136     SetCC = Op1;
14137   else // Quit if all operands are not constants.
14138     return SDValue();
14139
14140   if (C->getZExtValue() == 1)
14141     needOppositeCond = !needOppositeCond;
14142   else if (C->getZExtValue() != 0)
14143     // Quit if the constant is neither 0 or 1.
14144     return SDValue();
14145
14146   // Skip 'zext' node.
14147   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14148     SetCC = SetCC.getOperand(0);
14149
14150   // Quit if not SETCC.
14151   // FIXME: So far we only handle the boolean value generated from SETCC. If
14152   // there is other ways to generate boolean values, we need handle them here
14153   // as well.
14154   if (SetCC.getOpcode() != X86ISD::SETCC)
14155     return SDValue();
14156
14157   // Set the condition code or opposite one if necessary.
14158   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14159   if (needOppositeCond)
14160     CC = X86::GetOppositeBranchCondition(CC);
14161
14162   return SetCC.getOperand(1);
14163 }
14164
14165 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14166 /// updated. If only flag result is used and the result is evaluated from a
14167 /// series of element extraction, try to combine it into a PTEST.
14168 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14169                                      SelectionDAG &DAG,
14170                                      const X86Subtarget *Subtarget) {
14171   SDNode *N = Or.getNode();
14172   DebugLoc DL = N->getDebugLoc();
14173
14174   // Only SSE4.1 and beyond supports PTEST or like.
14175   if (!Subtarget->hasSSE41())
14176     return SDValue();
14177
14178   if (N->getOpcode() != X86ISD::OR)
14179     return SDValue();
14180
14181   // Quit if the value result of OR is used.
14182   if (N->hasAnyUseOfValue(0))
14183     return SDValue();
14184
14185   // Quit if not used as a boolean value.
14186   if (CC != X86::COND_E && CC != X86::COND_NE)
14187     return SDValue();
14188
14189   SmallVector<SDValue, 8> Opnds;
14190   SDValue VecIn;
14191   EVT VT = MVT::Other;
14192   unsigned Mask = 0;
14193
14194   // Recognize a special case where a vector is casted into wide integer to
14195   // test all 0s.
14196   Opnds.push_back(N->getOperand(0));
14197   Opnds.push_back(N->getOperand(1));
14198
14199   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14200     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14201     // BFS traverse all OR'd operands.
14202     if (I->getOpcode() == ISD::OR) {
14203       Opnds.push_back(I->getOperand(0));
14204       Opnds.push_back(I->getOperand(1));
14205       // Re-evaluate the number of nodes to be traversed.
14206       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14207       continue;
14208     }
14209
14210     // Quit if a non-EXTRACT_VECTOR_ELT
14211     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14212       return SDValue();
14213
14214     // Quit if without a constant index.
14215     SDValue Idx = I->getOperand(1);
14216     if (!isa<ConstantSDNode>(Idx))
14217       return SDValue();
14218
14219     // Check if all elements are extracted from the same vector.
14220     SDValue ExtractedFromVec = I->getOperand(0);
14221     if (VecIn.getNode() == 0) {
14222       VT = ExtractedFromVec.getValueType();
14223       // FIXME: only 128-bit vector is supported so far.
14224       if (!VT.is128BitVector())
14225         return SDValue();
14226       VecIn = ExtractedFromVec;
14227     } else if (VecIn != ExtractedFromVec)
14228       return SDValue();
14229
14230     // Record the constant index.
14231     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14232   }
14233
14234   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14235
14236   // Quit if not all elements are used.
14237   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14238     return SDValue();
14239
14240   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14241 }
14242
14243 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14244 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14245                                   TargetLowering::DAGCombinerInfo &DCI,
14246                                   const X86Subtarget *Subtarget) {
14247   DebugLoc DL = N->getDebugLoc();
14248
14249   // If the flag operand isn't dead, don't touch this CMOV.
14250   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14251     return SDValue();
14252
14253   SDValue FalseOp = N->getOperand(0);
14254   SDValue TrueOp = N->getOperand(1);
14255   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14256   SDValue Cond = N->getOperand(3);
14257
14258   if (CC == X86::COND_E || CC == X86::COND_NE) {
14259     switch (Cond.getOpcode()) {
14260     default: break;
14261     case X86ISD::BSR:
14262     case X86ISD::BSF:
14263       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14264       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14265         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14266     }
14267   }
14268
14269   SDValue Flags;
14270
14271   Flags = checkBoolTestSetCCCombine(Cond, CC);
14272   if (Flags.getNode() &&
14273       // Extra check as FCMOV only supports a subset of X86 cond.
14274       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14275     SDValue Ops[] = { FalseOp, TrueOp,
14276                       DAG.getConstant(CC, MVT::i8), Flags };
14277     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14278                        Ops, array_lengthof(Ops));
14279   }
14280
14281   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14282   if (Flags.getNode()) {
14283     SDValue Ops[] = { FalseOp, TrueOp,
14284                       DAG.getConstant(CC, MVT::i8), Flags };
14285     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14286                        Ops, array_lengthof(Ops));
14287   }
14288
14289   // If this is a select between two integer constants, try to do some
14290   // optimizations.  Note that the operands are ordered the opposite of SELECT
14291   // operands.
14292   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14293     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14294       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14295       // larger than FalseC (the false value).
14296       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14297         CC = X86::GetOppositeBranchCondition(CC);
14298         std::swap(TrueC, FalseC);
14299       }
14300
14301       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14302       // This is efficient for any integer data type (including i8/i16) and
14303       // shift amount.
14304       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14305         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14306                            DAG.getConstant(CC, MVT::i8), Cond);
14307
14308         // Zero extend the condition if needed.
14309         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14310
14311         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14312         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14313                            DAG.getConstant(ShAmt, MVT::i8));
14314         if (N->getNumValues() == 2)  // Dead flag value?
14315           return DCI.CombineTo(N, Cond, SDValue());
14316         return Cond;
14317       }
14318
14319       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14320       // for any integer data type, including i8/i16.
14321       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14322         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14323                            DAG.getConstant(CC, MVT::i8), Cond);
14324
14325         // Zero extend the condition if needed.
14326         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14327                            FalseC->getValueType(0), Cond);
14328         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14329                            SDValue(FalseC, 0));
14330
14331         if (N->getNumValues() == 2)  // Dead flag value?
14332           return DCI.CombineTo(N, Cond, SDValue());
14333         return Cond;
14334       }
14335
14336       // Optimize cases that will turn into an LEA instruction.  This requires
14337       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14338       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14339         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14340         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14341
14342         bool isFastMultiplier = false;
14343         if (Diff < 10) {
14344           switch ((unsigned char)Diff) {
14345           default: break;
14346           case 1:  // result = add base, cond
14347           case 2:  // result = lea base(    , cond*2)
14348           case 3:  // result = lea base(cond, cond*2)
14349           case 4:  // result = lea base(    , cond*4)
14350           case 5:  // result = lea base(cond, cond*4)
14351           case 8:  // result = lea base(    , cond*8)
14352           case 9:  // result = lea base(cond, cond*8)
14353             isFastMultiplier = true;
14354             break;
14355           }
14356         }
14357
14358         if (isFastMultiplier) {
14359           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14360           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14361                              DAG.getConstant(CC, MVT::i8), Cond);
14362           // Zero extend the condition if needed.
14363           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14364                              Cond);
14365           // Scale the condition by the difference.
14366           if (Diff != 1)
14367             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14368                                DAG.getConstant(Diff, Cond.getValueType()));
14369
14370           // Add the base if non-zero.
14371           if (FalseC->getAPIntValue() != 0)
14372             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14373                                SDValue(FalseC, 0));
14374           if (N->getNumValues() == 2)  // Dead flag value?
14375             return DCI.CombineTo(N, Cond, SDValue());
14376           return Cond;
14377         }
14378       }
14379     }
14380   }
14381   return SDValue();
14382 }
14383
14384
14385 /// PerformMulCombine - Optimize a single multiply with constant into two
14386 /// in order to implement it with two cheaper instructions, e.g.
14387 /// LEA + SHL, LEA + LEA.
14388 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14389                                  TargetLowering::DAGCombinerInfo &DCI) {
14390   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14391     return SDValue();
14392
14393   EVT VT = N->getValueType(0);
14394   if (VT != MVT::i64)
14395     return SDValue();
14396
14397   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14398   if (!C)
14399     return SDValue();
14400   uint64_t MulAmt = C->getZExtValue();
14401   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14402     return SDValue();
14403
14404   uint64_t MulAmt1 = 0;
14405   uint64_t MulAmt2 = 0;
14406   if ((MulAmt % 9) == 0) {
14407     MulAmt1 = 9;
14408     MulAmt2 = MulAmt / 9;
14409   } else if ((MulAmt % 5) == 0) {
14410     MulAmt1 = 5;
14411     MulAmt2 = MulAmt / 5;
14412   } else if ((MulAmt % 3) == 0) {
14413     MulAmt1 = 3;
14414     MulAmt2 = MulAmt / 3;
14415   }
14416   if (MulAmt2 &&
14417       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14418     DebugLoc DL = N->getDebugLoc();
14419
14420     if (isPowerOf2_64(MulAmt2) &&
14421         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14422       // If second multiplifer is pow2, issue it first. We want the multiply by
14423       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14424       // is an add.
14425       std::swap(MulAmt1, MulAmt2);
14426
14427     SDValue NewMul;
14428     if (isPowerOf2_64(MulAmt1))
14429       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14430                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14431     else
14432       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14433                            DAG.getConstant(MulAmt1, VT));
14434
14435     if (isPowerOf2_64(MulAmt2))
14436       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14437                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14438     else
14439       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14440                            DAG.getConstant(MulAmt2, VT));
14441
14442     // Do not add new nodes to DAG combiner worklist.
14443     DCI.CombineTo(N, NewMul, false);
14444   }
14445   return SDValue();
14446 }
14447
14448 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14449   SDValue N0 = N->getOperand(0);
14450   SDValue N1 = N->getOperand(1);
14451   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14452   EVT VT = N0.getValueType();
14453
14454   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14455   // since the result of setcc_c is all zero's or all ones.
14456   if (VT.isInteger() && !VT.isVector() &&
14457       N1C && N0.getOpcode() == ISD::AND &&
14458       N0.getOperand(1).getOpcode() == ISD::Constant) {
14459     SDValue N00 = N0.getOperand(0);
14460     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14461         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14462           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14463          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14464       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14465       APInt ShAmt = N1C->getAPIntValue();
14466       Mask = Mask.shl(ShAmt);
14467       if (Mask != 0)
14468         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14469                            N00, DAG.getConstant(Mask, VT));
14470     }
14471   }
14472
14473
14474   // Hardware support for vector shifts is sparse which makes us scalarize the
14475   // vector operations in many cases. Also, on sandybridge ADD is faster than
14476   // shl.
14477   // (shl V, 1) -> add V,V
14478   if (isSplatVector(N1.getNode())) {
14479     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14480     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14481     // We shift all of the values by one. In many cases we do not have
14482     // hardware support for this operation. This is better expressed as an ADD
14483     // of two values.
14484     if (N1C && (1 == N1C->getZExtValue())) {
14485       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14486     }
14487   }
14488
14489   return SDValue();
14490 }
14491
14492 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14493 ///                       when possible.
14494 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14495                                    TargetLowering::DAGCombinerInfo &DCI,
14496                                    const X86Subtarget *Subtarget) {
14497   EVT VT = N->getValueType(0);
14498   if (N->getOpcode() == ISD::SHL) {
14499     SDValue V = PerformSHLCombine(N, DAG);
14500     if (V.getNode()) return V;
14501   }
14502
14503   // On X86 with SSE2 support, we can transform this to a vector shift if
14504   // all elements are shifted by the same amount.  We can't do this in legalize
14505   // because the a constant vector is typically transformed to a constant pool
14506   // so we have no knowledge of the shift amount.
14507   if (!Subtarget->hasSSE2())
14508     return SDValue();
14509
14510   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14511       (!Subtarget->hasAVX2() ||
14512        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14513     return SDValue();
14514
14515   SDValue ShAmtOp = N->getOperand(1);
14516   EVT EltVT = VT.getVectorElementType();
14517   DebugLoc DL = N->getDebugLoc();
14518   SDValue BaseShAmt = SDValue();
14519   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14520     unsigned NumElts = VT.getVectorNumElements();
14521     unsigned i = 0;
14522     for (; i != NumElts; ++i) {
14523       SDValue Arg = ShAmtOp.getOperand(i);
14524       if (Arg.getOpcode() == ISD::UNDEF) continue;
14525       BaseShAmt = Arg;
14526       break;
14527     }
14528     // Handle the case where the build_vector is all undef
14529     // FIXME: Should DAG allow this?
14530     if (i == NumElts)
14531       return SDValue();
14532
14533     for (; i != NumElts; ++i) {
14534       SDValue Arg = ShAmtOp.getOperand(i);
14535       if (Arg.getOpcode() == ISD::UNDEF) continue;
14536       if (Arg != BaseShAmt) {
14537         return SDValue();
14538       }
14539     }
14540   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14541              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14542     SDValue InVec = ShAmtOp.getOperand(0);
14543     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14544       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14545       unsigned i = 0;
14546       for (; i != NumElts; ++i) {
14547         SDValue Arg = InVec.getOperand(i);
14548         if (Arg.getOpcode() == ISD::UNDEF) continue;
14549         BaseShAmt = Arg;
14550         break;
14551       }
14552     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14553        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14554          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14555          if (C->getZExtValue() == SplatIdx)
14556            BaseShAmt = InVec.getOperand(1);
14557        }
14558     }
14559     if (BaseShAmt.getNode() == 0) {
14560       // Don't create instructions with illegal types after legalize
14561       // types has run.
14562       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14563           !DCI.isBeforeLegalize())
14564         return SDValue();
14565
14566       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14567                               DAG.getIntPtrConstant(0));
14568     }
14569   } else
14570     return SDValue();
14571
14572   // The shift amount is an i32.
14573   if (EltVT.bitsGT(MVT::i32))
14574     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14575   else if (EltVT.bitsLT(MVT::i32))
14576     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14577
14578   // The shift amount is identical so we can do a vector shift.
14579   SDValue  ValOp = N->getOperand(0);
14580   switch (N->getOpcode()) {
14581   default:
14582     llvm_unreachable("Unknown shift opcode!");
14583   case ISD::SHL:
14584     switch (VT.getSimpleVT().SimpleTy) {
14585     default: return SDValue();
14586     case MVT::v2i64:
14587     case MVT::v4i32:
14588     case MVT::v8i16:
14589     case MVT::v4i64:
14590     case MVT::v8i32:
14591     case MVT::v16i16:
14592       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14593     }
14594   case ISD::SRA:
14595     switch (VT.getSimpleVT().SimpleTy) {
14596     default: return SDValue();
14597     case MVT::v4i32:
14598     case MVT::v8i16:
14599     case MVT::v8i32:
14600     case MVT::v16i16:
14601       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14602     }
14603   case ISD::SRL:
14604     switch (VT.getSimpleVT().SimpleTy) {
14605     default: return SDValue();
14606     case MVT::v2i64:
14607     case MVT::v4i32:
14608     case MVT::v8i16:
14609     case MVT::v4i64:
14610     case MVT::v8i32:
14611     case MVT::v16i16:
14612       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14613     }
14614   }
14615 }
14616
14617
14618 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14619 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14620 // and friends.  Likewise for OR -> CMPNEQSS.
14621 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14622                             TargetLowering::DAGCombinerInfo &DCI,
14623                             const X86Subtarget *Subtarget) {
14624   unsigned opcode;
14625
14626   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14627   // we're requiring SSE2 for both.
14628   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14629     SDValue N0 = N->getOperand(0);
14630     SDValue N1 = N->getOperand(1);
14631     SDValue CMP0 = N0->getOperand(1);
14632     SDValue CMP1 = N1->getOperand(1);
14633     DebugLoc DL = N->getDebugLoc();
14634
14635     // The SETCCs should both refer to the same CMP.
14636     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14637       return SDValue();
14638
14639     SDValue CMP00 = CMP0->getOperand(0);
14640     SDValue CMP01 = CMP0->getOperand(1);
14641     EVT     VT    = CMP00.getValueType();
14642
14643     if (VT == MVT::f32 || VT == MVT::f64) {
14644       bool ExpectingFlags = false;
14645       // Check for any users that want flags:
14646       for (SDNode::use_iterator UI = N->use_begin(),
14647              UE = N->use_end();
14648            !ExpectingFlags && UI != UE; ++UI)
14649         switch (UI->getOpcode()) {
14650         default:
14651         case ISD::BR_CC:
14652         case ISD::BRCOND:
14653         case ISD::SELECT:
14654           ExpectingFlags = true;
14655           break;
14656         case ISD::CopyToReg:
14657         case ISD::SIGN_EXTEND:
14658         case ISD::ZERO_EXTEND:
14659         case ISD::ANY_EXTEND:
14660           break;
14661         }
14662
14663       if (!ExpectingFlags) {
14664         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14665         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14666
14667         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14668           X86::CondCode tmp = cc0;
14669           cc0 = cc1;
14670           cc1 = tmp;
14671         }
14672
14673         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14674             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14675           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14676           X86ISD::NodeType NTOperator = is64BitFP ?
14677             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14678           // FIXME: need symbolic constants for these magic numbers.
14679           // See X86ATTInstPrinter.cpp:printSSECC().
14680           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14681           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14682                                               DAG.getConstant(x86cc, MVT::i8));
14683           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14684                                               OnesOrZeroesF);
14685           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14686                                       DAG.getConstant(1, MVT::i32));
14687           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14688           return OneBitOfTruth;
14689         }
14690       }
14691     }
14692   }
14693   return SDValue();
14694 }
14695
14696 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14697 /// so it can be folded inside ANDNP.
14698 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14699   EVT VT = N->getValueType(0);
14700
14701   // Match direct AllOnes for 128 and 256-bit vectors
14702   if (ISD::isBuildVectorAllOnes(N))
14703     return true;
14704
14705   // Look through a bit convert.
14706   if (N->getOpcode() == ISD::BITCAST)
14707     N = N->getOperand(0).getNode();
14708
14709   // Sometimes the operand may come from a insert_subvector building a 256-bit
14710   // allones vector
14711   if (VT.is256BitVector() &&
14712       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14713     SDValue V1 = N->getOperand(0);
14714     SDValue V2 = N->getOperand(1);
14715
14716     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14717         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14718         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14719         ISD::isBuildVectorAllOnes(V2.getNode()))
14720       return true;
14721   }
14722
14723   return false;
14724 }
14725
14726 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14727                                  TargetLowering::DAGCombinerInfo &DCI,
14728                                  const X86Subtarget *Subtarget) {
14729   if (DCI.isBeforeLegalizeOps())
14730     return SDValue();
14731
14732   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14733   if (R.getNode())
14734     return R;
14735
14736   EVT VT = N->getValueType(0);
14737
14738   // Create ANDN, BLSI, and BLSR instructions
14739   // BLSI is X & (-X)
14740   // BLSR is X & (X-1)
14741   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14742     SDValue N0 = N->getOperand(0);
14743     SDValue N1 = N->getOperand(1);
14744     DebugLoc DL = N->getDebugLoc();
14745
14746     // Check LHS for not
14747     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14748       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14749     // Check RHS for not
14750     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14751       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14752
14753     // Check LHS for neg
14754     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14755         isZero(N0.getOperand(0)))
14756       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14757
14758     // Check RHS for neg
14759     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14760         isZero(N1.getOperand(0)))
14761       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14762
14763     // Check LHS for X-1
14764     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14765         isAllOnes(N0.getOperand(1)))
14766       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14767
14768     // Check RHS for X-1
14769     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14770         isAllOnes(N1.getOperand(1)))
14771       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14772
14773     return SDValue();
14774   }
14775
14776   // Want to form ANDNP nodes:
14777   // 1) In the hopes of then easily combining them with OR and AND nodes
14778   //    to form PBLEND/PSIGN.
14779   // 2) To match ANDN packed intrinsics
14780   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14781     return SDValue();
14782
14783   SDValue N0 = N->getOperand(0);
14784   SDValue N1 = N->getOperand(1);
14785   DebugLoc DL = N->getDebugLoc();
14786
14787   // Check LHS for vnot
14788   if (N0.getOpcode() == ISD::XOR &&
14789       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14790       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14791     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14792
14793   // Check RHS for vnot
14794   if (N1.getOpcode() == ISD::XOR &&
14795       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14796       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14797     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14798
14799   return SDValue();
14800 }
14801
14802 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14803                                 TargetLowering::DAGCombinerInfo &DCI,
14804                                 const X86Subtarget *Subtarget) {
14805   if (DCI.isBeforeLegalizeOps())
14806     return SDValue();
14807
14808   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14809   if (R.getNode())
14810     return R;
14811
14812   EVT VT = N->getValueType(0);
14813
14814   SDValue N0 = N->getOperand(0);
14815   SDValue N1 = N->getOperand(1);
14816
14817   // look for psign/blend
14818   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14819     if (!Subtarget->hasSSSE3() ||
14820         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14821       return SDValue();
14822
14823     // Canonicalize pandn to RHS
14824     if (N0.getOpcode() == X86ISD::ANDNP)
14825       std::swap(N0, N1);
14826     // or (and (m, y), (pandn m, x))
14827     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14828       SDValue Mask = N1.getOperand(0);
14829       SDValue X    = N1.getOperand(1);
14830       SDValue Y;
14831       if (N0.getOperand(0) == Mask)
14832         Y = N0.getOperand(1);
14833       if (N0.getOperand(1) == Mask)
14834         Y = N0.getOperand(0);
14835
14836       // Check to see if the mask appeared in both the AND and ANDNP and
14837       if (!Y.getNode())
14838         return SDValue();
14839
14840       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14841       // Look through mask bitcast.
14842       if (Mask.getOpcode() == ISD::BITCAST)
14843         Mask = Mask.getOperand(0);
14844       if (X.getOpcode() == ISD::BITCAST)
14845         X = X.getOperand(0);
14846       if (Y.getOpcode() == ISD::BITCAST)
14847         Y = Y.getOperand(0);
14848
14849       EVT MaskVT = Mask.getValueType();
14850
14851       // Validate that the Mask operand is a vector sra node.
14852       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14853       // there is no psrai.b
14854       if (Mask.getOpcode() != X86ISD::VSRAI)
14855         return SDValue();
14856
14857       // Check that the SRA is all signbits.
14858       SDValue SraC = Mask.getOperand(1);
14859       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14860       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14861       if ((SraAmt + 1) != EltBits)
14862         return SDValue();
14863
14864       DebugLoc DL = N->getDebugLoc();
14865
14866       // Now we know we at least have a plendvb with the mask val.  See if
14867       // we can form a psignb/w/d.
14868       // psign = x.type == y.type == mask.type && y = sub(0, x);
14869       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14870           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14871           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14872         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14873                "Unsupported VT for PSIGN");
14874         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14875         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14876       }
14877       // PBLENDVB only available on SSE 4.1
14878       if (!Subtarget->hasSSE41())
14879         return SDValue();
14880
14881       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14882
14883       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14884       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14885       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14886       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14887       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14888     }
14889   }
14890
14891   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14892     return SDValue();
14893
14894   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14895   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14896     std::swap(N0, N1);
14897   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14898     return SDValue();
14899   if (!N0.hasOneUse() || !N1.hasOneUse())
14900     return SDValue();
14901
14902   SDValue ShAmt0 = N0.getOperand(1);
14903   if (ShAmt0.getValueType() != MVT::i8)
14904     return SDValue();
14905   SDValue ShAmt1 = N1.getOperand(1);
14906   if (ShAmt1.getValueType() != MVT::i8)
14907     return SDValue();
14908   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14909     ShAmt0 = ShAmt0.getOperand(0);
14910   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14911     ShAmt1 = ShAmt1.getOperand(0);
14912
14913   DebugLoc DL = N->getDebugLoc();
14914   unsigned Opc = X86ISD::SHLD;
14915   SDValue Op0 = N0.getOperand(0);
14916   SDValue Op1 = N1.getOperand(0);
14917   if (ShAmt0.getOpcode() == ISD::SUB) {
14918     Opc = X86ISD::SHRD;
14919     std::swap(Op0, Op1);
14920     std::swap(ShAmt0, ShAmt1);
14921   }
14922
14923   unsigned Bits = VT.getSizeInBits();
14924   if (ShAmt1.getOpcode() == ISD::SUB) {
14925     SDValue Sum = ShAmt1.getOperand(0);
14926     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14927       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14928       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14929         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14930       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14931         return DAG.getNode(Opc, DL, VT,
14932                            Op0, Op1,
14933                            DAG.getNode(ISD::TRUNCATE, DL,
14934                                        MVT::i8, ShAmt0));
14935     }
14936   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14937     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14938     if (ShAmt0C &&
14939         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14940       return DAG.getNode(Opc, DL, VT,
14941                          N0.getOperand(0), N1.getOperand(0),
14942                          DAG.getNode(ISD::TRUNCATE, DL,
14943                                        MVT::i8, ShAmt0));
14944   }
14945
14946   return SDValue();
14947 }
14948
14949 // Generate NEG and CMOV for integer abs.
14950 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14951   EVT VT = N->getValueType(0);
14952
14953   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14954   // 8-bit integer abs to NEG and CMOV.
14955   if (VT.isInteger() && VT.getSizeInBits() == 8)
14956     return SDValue();
14957
14958   SDValue N0 = N->getOperand(0);
14959   SDValue N1 = N->getOperand(1);
14960   DebugLoc DL = N->getDebugLoc();
14961
14962   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14963   // and change it to SUB and CMOV.
14964   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14965       N0.getOpcode() == ISD::ADD &&
14966       N0.getOperand(1) == N1 &&
14967       N1.getOpcode() == ISD::SRA &&
14968       N1.getOperand(0) == N0.getOperand(0))
14969     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14970       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14971         // Generate SUB & CMOV.
14972         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14973                                   DAG.getConstant(0, VT), N0.getOperand(0));
14974
14975         SDValue Ops[] = { N0.getOperand(0), Neg,
14976                           DAG.getConstant(X86::COND_GE, MVT::i8),
14977                           SDValue(Neg.getNode(), 1) };
14978         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14979                            Ops, array_lengthof(Ops));
14980       }
14981   return SDValue();
14982 }
14983
14984 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14985 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14986                                  TargetLowering::DAGCombinerInfo &DCI,
14987                                  const X86Subtarget *Subtarget) {
14988   if (DCI.isBeforeLegalizeOps())
14989     return SDValue();
14990
14991   if (Subtarget->hasCMov()) {
14992     SDValue RV = performIntegerAbsCombine(N, DAG);
14993     if (RV.getNode())
14994       return RV;
14995   }
14996
14997   // Try forming BMI if it is available.
14998   if (!Subtarget->hasBMI())
14999     return SDValue();
15000
15001   EVT VT = N->getValueType(0);
15002
15003   if (VT != MVT::i32 && VT != MVT::i64)
15004     return SDValue();
15005
15006   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15007
15008   // Create BLSMSK instructions by finding X ^ (X-1)
15009   SDValue N0 = N->getOperand(0);
15010   SDValue N1 = N->getOperand(1);
15011   DebugLoc DL = N->getDebugLoc();
15012
15013   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15014       isAllOnes(N0.getOperand(1)))
15015     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15016
15017   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15018       isAllOnes(N1.getOperand(1)))
15019     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15020
15021   return SDValue();
15022 }
15023
15024 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15025 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15026                                   TargetLowering::DAGCombinerInfo &DCI,
15027                                   const X86Subtarget *Subtarget) {
15028   LoadSDNode *Ld = cast<LoadSDNode>(N);
15029   EVT RegVT = Ld->getValueType(0);
15030   EVT MemVT = Ld->getMemoryVT();
15031   DebugLoc dl = Ld->getDebugLoc();
15032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15033
15034   ISD::LoadExtType Ext = Ld->getExtensionType();
15035
15036   // If this is a vector EXT Load then attempt to optimize it using a
15037   // shuffle. We need SSE4 for the shuffles.
15038   // TODO: It is possible to support ZExt by zeroing the undef values
15039   // during the shuffle phase or after the shuffle.
15040   if (RegVT.isVector() && RegVT.isInteger() &&
15041       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15042     assert(MemVT != RegVT && "Cannot extend to the same type");
15043     assert(MemVT.isVector() && "Must load a vector from memory");
15044
15045     unsigned NumElems = RegVT.getVectorNumElements();
15046     unsigned RegSz = RegVT.getSizeInBits();
15047     unsigned MemSz = MemVT.getSizeInBits();
15048     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15049
15050     // All sizes must be a power of two.
15051     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15052       return SDValue();
15053
15054     // Attempt to load the original value using scalar loads.
15055     // Find the largest scalar type that divides the total loaded size.
15056     MVT SclrLoadTy = MVT::i8;
15057     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15058          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15059       MVT Tp = (MVT::SimpleValueType)tp;
15060       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15061         SclrLoadTy = Tp;
15062       }
15063     }
15064
15065     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15066     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15067         (64 <= MemSz))
15068       SclrLoadTy = MVT::f64;
15069
15070     // Calculate the number of scalar loads that we need to perform
15071     // in order to load our vector from memory.
15072     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15073
15074     // Represent our vector as a sequence of elements which are the
15075     // largest scalar that we can load.
15076     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15077       RegSz/SclrLoadTy.getSizeInBits());
15078
15079     // Represent the data using the same element type that is stored in
15080     // memory. In practice, we ''widen'' MemVT.
15081     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15082                                   RegSz/MemVT.getScalarType().getSizeInBits());
15083
15084     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15085       "Invalid vector type");
15086
15087     // We can't shuffle using an illegal type.
15088     if (!TLI.isTypeLegal(WideVecVT))
15089       return SDValue();
15090
15091     SmallVector<SDValue, 8> Chains;
15092     SDValue Ptr = Ld->getBasePtr();
15093     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15094                                         TLI.getPointerTy());
15095     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15096
15097     for (unsigned i = 0; i < NumLoads; ++i) {
15098       // Perform a single load.
15099       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15100                                        Ptr, Ld->getPointerInfo(),
15101                                        Ld->isVolatile(), Ld->isNonTemporal(),
15102                                        Ld->isInvariant(), Ld->getAlignment());
15103       Chains.push_back(ScalarLoad.getValue(1));
15104       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15105       // another round of DAGCombining.
15106       if (i == 0)
15107         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15108       else
15109         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15110                           ScalarLoad, DAG.getIntPtrConstant(i));
15111
15112       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15113     }
15114
15115     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15116                                Chains.size());
15117
15118     // Bitcast the loaded value to a vector of the original element type, in
15119     // the size of the target vector type.
15120     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15121     unsigned SizeRatio = RegSz/MemSz;
15122
15123     // Redistribute the loaded elements into the different locations.
15124     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15125     for (unsigned i = 0; i != NumElems; ++i)
15126       ShuffleVec[i*SizeRatio] = i;
15127
15128     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15129                                          DAG.getUNDEF(WideVecVT),
15130                                          &ShuffleVec[0]);
15131
15132     // Bitcast to the requested type.
15133     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15134     // Replace the original load with the new sequence
15135     // and return the new chain.
15136     return DCI.CombineTo(N, Shuff, TF, true);
15137   }
15138
15139   return SDValue();
15140 }
15141
15142 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15143 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15144                                    const X86Subtarget *Subtarget) {
15145   StoreSDNode *St = cast<StoreSDNode>(N);
15146   EVT VT = St->getValue().getValueType();
15147   EVT StVT = St->getMemoryVT();
15148   DebugLoc dl = St->getDebugLoc();
15149   SDValue StoredVal = St->getOperand(1);
15150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15151
15152   // If we are saving a concatenation of two XMM registers, perform two stores.
15153   // On Sandy Bridge, 256-bit memory operations are executed by two
15154   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15155   // memory  operation.
15156   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15157       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15158       StoredVal.getNumOperands() == 2) {
15159     SDValue Value0 = StoredVal.getOperand(0);
15160     SDValue Value1 = StoredVal.getOperand(1);
15161
15162     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15163     SDValue Ptr0 = St->getBasePtr();
15164     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15165
15166     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15167                                 St->getPointerInfo(), St->isVolatile(),
15168                                 St->isNonTemporal(), St->getAlignment());
15169     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15170                                 St->getPointerInfo(), St->isVolatile(),
15171                                 St->isNonTemporal(), St->getAlignment());
15172     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15173   }
15174
15175   // Optimize trunc store (of multiple scalars) to shuffle and store.
15176   // First, pack all of the elements in one place. Next, store to memory
15177   // in fewer chunks.
15178   if (St->isTruncatingStore() && VT.isVector()) {
15179     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15180     unsigned NumElems = VT.getVectorNumElements();
15181     assert(StVT != VT && "Cannot truncate to the same type");
15182     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15183     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15184
15185     // From, To sizes and ElemCount must be pow of two
15186     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15187     // We are going to use the original vector elt for storing.
15188     // Accumulated smaller vector elements must be a multiple of the store size.
15189     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15190
15191     unsigned SizeRatio  = FromSz / ToSz;
15192
15193     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15194
15195     // Create a type on which we perform the shuffle
15196     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15197             StVT.getScalarType(), NumElems*SizeRatio);
15198
15199     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15200
15201     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15202     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15203     for (unsigned i = 0; i != NumElems; ++i)
15204       ShuffleVec[i] = i * SizeRatio;
15205
15206     // Can't shuffle using an illegal type.
15207     if (!TLI.isTypeLegal(WideVecVT))
15208       return SDValue();
15209
15210     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15211                                          DAG.getUNDEF(WideVecVT),
15212                                          &ShuffleVec[0]);
15213     // At this point all of the data is stored at the bottom of the
15214     // register. We now need to save it to mem.
15215
15216     // Find the largest store unit
15217     MVT StoreType = MVT::i8;
15218     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15219          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15220       MVT Tp = (MVT::SimpleValueType)tp;
15221       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15222         StoreType = Tp;
15223     }
15224
15225     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15226     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15227         (64 <= NumElems * ToSz))
15228       StoreType = MVT::f64;
15229
15230     // Bitcast the original vector into a vector of store-size units
15231     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15232             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15233     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15234     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15235     SmallVector<SDValue, 8> Chains;
15236     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15237                                         TLI.getPointerTy());
15238     SDValue Ptr = St->getBasePtr();
15239
15240     // Perform one or more big stores into memory.
15241     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15242       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15243                                    StoreType, ShuffWide,
15244                                    DAG.getIntPtrConstant(i));
15245       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15246                                 St->getPointerInfo(), St->isVolatile(),
15247                                 St->isNonTemporal(), St->getAlignment());
15248       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15249       Chains.push_back(Ch);
15250     }
15251
15252     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15253                                Chains.size());
15254   }
15255
15256
15257   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15258   // the FP state in cases where an emms may be missing.
15259   // A preferable solution to the general problem is to figure out the right
15260   // places to insert EMMS.  This qualifies as a quick hack.
15261
15262   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15263   if (VT.getSizeInBits() != 64)
15264     return SDValue();
15265
15266   const Function *F = DAG.getMachineFunction().getFunction();
15267   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15268   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15269                      && Subtarget->hasSSE2();
15270   if ((VT.isVector() ||
15271        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15272       isa<LoadSDNode>(St->getValue()) &&
15273       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15274       St->getChain().hasOneUse() && !St->isVolatile()) {
15275     SDNode* LdVal = St->getValue().getNode();
15276     LoadSDNode *Ld = 0;
15277     int TokenFactorIndex = -1;
15278     SmallVector<SDValue, 8> Ops;
15279     SDNode* ChainVal = St->getChain().getNode();
15280     // Must be a store of a load.  We currently handle two cases:  the load
15281     // is a direct child, and it's under an intervening TokenFactor.  It is
15282     // possible to dig deeper under nested TokenFactors.
15283     if (ChainVal == LdVal)
15284       Ld = cast<LoadSDNode>(St->getChain());
15285     else if (St->getValue().hasOneUse() &&
15286              ChainVal->getOpcode() == ISD::TokenFactor) {
15287       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15288         if (ChainVal->getOperand(i).getNode() == LdVal) {
15289           TokenFactorIndex = i;
15290           Ld = cast<LoadSDNode>(St->getValue());
15291         } else
15292           Ops.push_back(ChainVal->getOperand(i));
15293       }
15294     }
15295
15296     if (!Ld || !ISD::isNormalLoad(Ld))
15297       return SDValue();
15298
15299     // If this is not the MMX case, i.e. we are just turning i64 load/store
15300     // into f64 load/store, avoid the transformation if there are multiple
15301     // uses of the loaded value.
15302     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15303       return SDValue();
15304
15305     DebugLoc LdDL = Ld->getDebugLoc();
15306     DebugLoc StDL = N->getDebugLoc();
15307     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15308     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15309     // pair instead.
15310     if (Subtarget->is64Bit() || F64IsLegal) {
15311       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15312       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15313                                   Ld->getPointerInfo(), Ld->isVolatile(),
15314                                   Ld->isNonTemporal(), Ld->isInvariant(),
15315                                   Ld->getAlignment());
15316       SDValue NewChain = NewLd.getValue(1);
15317       if (TokenFactorIndex != -1) {
15318         Ops.push_back(NewChain);
15319         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15320                                Ops.size());
15321       }
15322       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15323                           St->getPointerInfo(),
15324                           St->isVolatile(), St->isNonTemporal(),
15325                           St->getAlignment());
15326     }
15327
15328     // Otherwise, lower to two pairs of 32-bit loads / stores.
15329     SDValue LoAddr = Ld->getBasePtr();
15330     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15331                                  DAG.getConstant(4, MVT::i32));
15332
15333     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15334                                Ld->getPointerInfo(),
15335                                Ld->isVolatile(), Ld->isNonTemporal(),
15336                                Ld->isInvariant(), Ld->getAlignment());
15337     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15338                                Ld->getPointerInfo().getWithOffset(4),
15339                                Ld->isVolatile(), Ld->isNonTemporal(),
15340                                Ld->isInvariant(),
15341                                MinAlign(Ld->getAlignment(), 4));
15342
15343     SDValue NewChain = LoLd.getValue(1);
15344     if (TokenFactorIndex != -1) {
15345       Ops.push_back(LoLd);
15346       Ops.push_back(HiLd);
15347       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15348                              Ops.size());
15349     }
15350
15351     LoAddr = St->getBasePtr();
15352     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15353                          DAG.getConstant(4, MVT::i32));
15354
15355     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15356                                 St->getPointerInfo(),
15357                                 St->isVolatile(), St->isNonTemporal(),
15358                                 St->getAlignment());
15359     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15360                                 St->getPointerInfo().getWithOffset(4),
15361                                 St->isVolatile(),
15362                                 St->isNonTemporal(),
15363                                 MinAlign(St->getAlignment(), 4));
15364     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15365   }
15366   return SDValue();
15367 }
15368
15369 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15370 /// and return the operands for the horizontal operation in LHS and RHS.  A
15371 /// horizontal operation performs the binary operation on successive elements
15372 /// of its first operand, then on successive elements of its second operand,
15373 /// returning the resulting values in a vector.  For example, if
15374 ///   A = < float a0, float a1, float a2, float a3 >
15375 /// and
15376 ///   B = < float b0, float b1, float b2, float b3 >
15377 /// then the result of doing a horizontal operation on A and B is
15378 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15379 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15380 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15381 /// set to A, RHS to B, and the routine returns 'true'.
15382 /// Note that the binary operation should have the property that if one of the
15383 /// operands is UNDEF then the result is UNDEF.
15384 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15385   // Look for the following pattern: if
15386   //   A = < float a0, float a1, float a2, float a3 >
15387   //   B = < float b0, float b1, float b2, float b3 >
15388   // and
15389   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15390   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15391   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15392   // which is A horizontal-op B.
15393
15394   // At least one of the operands should be a vector shuffle.
15395   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15396       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15397     return false;
15398
15399   EVT VT = LHS.getValueType();
15400
15401   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15402          "Unsupported vector type for horizontal add/sub");
15403
15404   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15405   // operate independently on 128-bit lanes.
15406   unsigned NumElts = VT.getVectorNumElements();
15407   unsigned NumLanes = VT.getSizeInBits()/128;
15408   unsigned NumLaneElts = NumElts / NumLanes;
15409   assert((NumLaneElts % 2 == 0) &&
15410          "Vector type should have an even number of elements in each lane");
15411   unsigned HalfLaneElts = NumLaneElts/2;
15412
15413   // View LHS in the form
15414   //   LHS = VECTOR_SHUFFLE A, B, LMask
15415   // If LHS is not a shuffle then pretend it is the shuffle
15416   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15417   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15418   // type VT.
15419   SDValue A, B;
15420   SmallVector<int, 16> LMask(NumElts);
15421   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15422     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15423       A = LHS.getOperand(0);
15424     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15425       B = LHS.getOperand(1);
15426     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15427     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15428   } else {
15429     if (LHS.getOpcode() != ISD::UNDEF)
15430       A = LHS;
15431     for (unsigned i = 0; i != NumElts; ++i)
15432       LMask[i] = i;
15433   }
15434
15435   // Likewise, view RHS in the form
15436   //   RHS = VECTOR_SHUFFLE C, D, RMask
15437   SDValue C, D;
15438   SmallVector<int, 16> RMask(NumElts);
15439   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15440     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15441       C = RHS.getOperand(0);
15442     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15443       D = RHS.getOperand(1);
15444     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15445     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15446   } else {
15447     if (RHS.getOpcode() != ISD::UNDEF)
15448       C = RHS;
15449     for (unsigned i = 0; i != NumElts; ++i)
15450       RMask[i] = i;
15451   }
15452
15453   // Check that the shuffles are both shuffling the same vectors.
15454   if (!(A == C && B == D) && !(A == D && B == C))
15455     return false;
15456
15457   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15458   if (!A.getNode() && !B.getNode())
15459     return false;
15460
15461   // If A and B occur in reverse order in RHS, then "swap" them (which means
15462   // rewriting the mask).
15463   if (A != C)
15464     CommuteVectorShuffleMask(RMask, NumElts);
15465
15466   // At this point LHS and RHS are equivalent to
15467   //   LHS = VECTOR_SHUFFLE A, B, LMask
15468   //   RHS = VECTOR_SHUFFLE A, B, RMask
15469   // Check that the masks correspond to performing a horizontal operation.
15470   for (unsigned i = 0; i != NumElts; ++i) {
15471     int LIdx = LMask[i], RIdx = RMask[i];
15472
15473     // Ignore any UNDEF components.
15474     if (LIdx < 0 || RIdx < 0 ||
15475         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15476         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15477       continue;
15478
15479     // Check that successive elements are being operated on.  If not, this is
15480     // not a horizontal operation.
15481     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15482     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15483     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15484     if (!(LIdx == Index && RIdx == Index + 1) &&
15485         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15486       return false;
15487   }
15488
15489   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15490   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15491   return true;
15492 }
15493
15494 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15495 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15496                                   const X86Subtarget *Subtarget) {
15497   EVT VT = N->getValueType(0);
15498   SDValue LHS = N->getOperand(0);
15499   SDValue RHS = N->getOperand(1);
15500
15501   // Try to synthesize horizontal adds from adds of shuffles.
15502   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15503        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15504       isHorizontalBinOp(LHS, RHS, true))
15505     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15506   return SDValue();
15507 }
15508
15509 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15510 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15511                                   const X86Subtarget *Subtarget) {
15512   EVT VT = N->getValueType(0);
15513   SDValue LHS = N->getOperand(0);
15514   SDValue RHS = N->getOperand(1);
15515
15516   // Try to synthesize horizontal subs from subs of shuffles.
15517   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15518        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15519       isHorizontalBinOp(LHS, RHS, false))
15520     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15521   return SDValue();
15522 }
15523
15524 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15525 /// X86ISD::FXOR nodes.
15526 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15527   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15528   // F[X]OR(0.0, x) -> x
15529   // F[X]OR(x, 0.0) -> x
15530   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15531     if (C->getValueAPF().isPosZero())
15532       return N->getOperand(1);
15533   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15534     if (C->getValueAPF().isPosZero())
15535       return N->getOperand(0);
15536   return SDValue();
15537 }
15538
15539 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15540 /// X86ISD::FMAX nodes.
15541 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15542   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15543
15544   // Only perform optimizations if UnsafeMath is used.
15545   if (!DAG.getTarget().Options.UnsafeFPMath)
15546     return SDValue();
15547
15548   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15549   // into FMINC and FMAXC, which are Commutative operations.
15550   unsigned NewOp = 0;
15551   switch (N->getOpcode()) {
15552     default: llvm_unreachable("unknown opcode");
15553     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15554     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15555   }
15556
15557   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15558                      N->getOperand(0), N->getOperand(1));
15559 }
15560
15561
15562 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15563 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15564   // FAND(0.0, x) -> 0.0
15565   // FAND(x, 0.0) -> 0.0
15566   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15567     if (C->getValueAPF().isPosZero())
15568       return N->getOperand(0);
15569   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15570     if (C->getValueAPF().isPosZero())
15571       return N->getOperand(1);
15572   return SDValue();
15573 }
15574
15575 static SDValue PerformBTCombine(SDNode *N,
15576                                 SelectionDAG &DAG,
15577                                 TargetLowering::DAGCombinerInfo &DCI) {
15578   // BT ignores high bits in the bit index operand.
15579   SDValue Op1 = N->getOperand(1);
15580   if (Op1.hasOneUse()) {
15581     unsigned BitWidth = Op1.getValueSizeInBits();
15582     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15583     APInt KnownZero, KnownOne;
15584     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15585                                           !DCI.isBeforeLegalizeOps());
15586     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15587     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15588         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15589       DCI.CommitTargetLoweringOpt(TLO);
15590   }
15591   return SDValue();
15592 }
15593
15594 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15595   SDValue Op = N->getOperand(0);
15596   if (Op.getOpcode() == ISD::BITCAST)
15597     Op = Op.getOperand(0);
15598   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15599   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15600       VT.getVectorElementType().getSizeInBits() ==
15601       OpVT.getVectorElementType().getSizeInBits()) {
15602     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15603   }
15604   return SDValue();
15605 }
15606
15607 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15608                                   TargetLowering::DAGCombinerInfo &DCI,
15609                                   const X86Subtarget *Subtarget) {
15610   if (!DCI.isBeforeLegalizeOps())
15611     return SDValue();
15612
15613   if (!Subtarget->hasAVX())
15614     return SDValue();
15615
15616   EVT VT = N->getValueType(0);
15617   SDValue Op = N->getOperand(0);
15618   EVT OpVT = Op.getValueType();
15619   DebugLoc dl = N->getDebugLoc();
15620
15621   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15622       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15623
15624     if (Subtarget->hasAVX2())
15625       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15626
15627     // Optimize vectors in AVX mode
15628     // Sign extend  v8i16 to v8i32 and
15629     //              v4i32 to v4i64
15630     //
15631     // Divide input vector into two parts
15632     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15633     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15634     // concat the vectors to original VT
15635
15636     unsigned NumElems = OpVT.getVectorNumElements();
15637     SDValue Undef = DAG.getUNDEF(OpVT);
15638
15639     SmallVector<int,8> ShufMask1(NumElems, -1);
15640     for (unsigned i = 0; i != NumElems/2; ++i)
15641       ShufMask1[i] = i;
15642
15643     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15644
15645     SmallVector<int,8> ShufMask2(NumElems, -1);
15646     for (unsigned i = 0; i != NumElems/2; ++i)
15647       ShufMask2[i] = i + NumElems/2;
15648
15649     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15650
15651     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15652                                   VT.getVectorNumElements()/2);
15653
15654     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15655     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15656
15657     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15658   }
15659   return SDValue();
15660 }
15661
15662 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15663                                  const X86Subtarget* Subtarget) {
15664   DebugLoc dl = N->getDebugLoc();
15665   EVT VT = N->getValueType(0);
15666
15667   // Let legalize expand this if it isn't a legal type yet.
15668   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15669     return SDValue();
15670
15671   EVT ScalarVT = VT.getScalarType();
15672   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15673       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15674     return SDValue();
15675
15676   SDValue A = N->getOperand(0);
15677   SDValue B = N->getOperand(1);
15678   SDValue C = N->getOperand(2);
15679
15680   bool NegA = (A.getOpcode() == ISD::FNEG);
15681   bool NegB = (B.getOpcode() == ISD::FNEG);
15682   bool NegC = (C.getOpcode() == ISD::FNEG);
15683
15684   // Negative multiplication when NegA xor NegB
15685   bool NegMul = (NegA != NegB);
15686   if (NegA)
15687     A = A.getOperand(0);
15688   if (NegB)
15689     B = B.getOperand(0);
15690   if (NegC)
15691     C = C.getOperand(0);
15692
15693   unsigned Opcode;
15694   if (!NegMul)
15695     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15696   else
15697     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15698
15699   return DAG.getNode(Opcode, dl, VT, A, B, C);
15700 }
15701
15702 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15703                                   TargetLowering::DAGCombinerInfo &DCI,
15704                                   const X86Subtarget *Subtarget) {
15705   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15706   //           (and (i32 x86isd::setcc_carry), 1)
15707   // This eliminates the zext. This transformation is necessary because
15708   // ISD::SETCC is always legalized to i8.
15709   DebugLoc dl = N->getDebugLoc();
15710   SDValue N0 = N->getOperand(0);
15711   EVT VT = N->getValueType(0);
15712   EVT OpVT = N0.getValueType();
15713
15714   if (N0.getOpcode() == ISD::AND &&
15715       N0.hasOneUse() &&
15716       N0.getOperand(0).hasOneUse()) {
15717     SDValue N00 = N0.getOperand(0);
15718     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15719       return SDValue();
15720     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15721     if (!C || C->getZExtValue() != 1)
15722       return SDValue();
15723     return DAG.getNode(ISD::AND, dl, VT,
15724                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15725                                    N00.getOperand(0), N00.getOperand(1)),
15726                        DAG.getConstant(1, VT));
15727   }
15728
15729   // Optimize vectors in AVX mode:
15730   //
15731   //   v8i16 -> v8i32
15732   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15733   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15734   //   Concat upper and lower parts.
15735   //
15736   //   v4i32 -> v4i64
15737   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15738   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15739   //   Concat upper and lower parts.
15740   //
15741   if (!DCI.isBeforeLegalizeOps())
15742     return SDValue();
15743
15744   if (!Subtarget->hasAVX())
15745     return SDValue();
15746
15747   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15748       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15749
15750     if (Subtarget->hasAVX2())
15751       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15752
15753     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15754     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15755     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15756
15757     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15758                                VT.getVectorNumElements()/2);
15759
15760     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15761     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15762
15763     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15764   }
15765
15766   return SDValue();
15767 }
15768
15769 // Optimize x == -y --> x+y == 0
15770 //          x != -y --> x+y != 0
15771 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15772   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15773   SDValue LHS = N->getOperand(0);
15774   SDValue RHS = N->getOperand(1);
15775
15776   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15777     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15778       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15779         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15780                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15781         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15782                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15783       }
15784   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15785     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15786       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15787         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15788                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15789         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15790                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15791       }
15792   return SDValue();
15793 }
15794
15795 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15796 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15797                                    TargetLowering::DAGCombinerInfo &DCI,
15798                                    const X86Subtarget *Subtarget) {
15799   DebugLoc DL = N->getDebugLoc();
15800   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15801   SDValue EFLAGS = N->getOperand(1);
15802
15803   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15804   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15805   // cases.
15806   if (CC == X86::COND_B)
15807     return DAG.getNode(ISD::AND, DL, MVT::i8,
15808                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15809                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15810                        DAG.getConstant(1, MVT::i8));
15811
15812   SDValue Flags;
15813
15814   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15815   if (Flags.getNode()) {
15816     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15817     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15818   }
15819
15820   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15821   if (Flags.getNode()) {
15822     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15823     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15824   }
15825
15826   return SDValue();
15827 }
15828
15829 // Optimize branch condition evaluation.
15830 //
15831 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15832                                     TargetLowering::DAGCombinerInfo &DCI,
15833                                     const X86Subtarget *Subtarget) {
15834   DebugLoc DL = N->getDebugLoc();
15835   SDValue Chain = N->getOperand(0);
15836   SDValue Dest = N->getOperand(1);
15837   SDValue EFLAGS = N->getOperand(3);
15838   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15839
15840   SDValue Flags;
15841
15842   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15843   if (Flags.getNode()) {
15844     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15845     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15846                        Flags);
15847   }
15848
15849   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15850   if (Flags.getNode()) {
15851     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15852     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15853                        Flags);
15854   }
15855
15856   return SDValue();
15857 }
15858
15859 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15860   SDValue Op0 = N->getOperand(0);
15861   EVT InVT = Op0->getValueType(0);
15862
15863   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15864   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15865     DebugLoc dl = N->getDebugLoc();
15866     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15867     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15868     // Notice that we use SINT_TO_FP because we know that the high bits
15869     // are zero and SINT_TO_FP is better supported by the hardware.
15870     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15871   }
15872
15873   return SDValue();
15874 }
15875
15876 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15877                                         const X86TargetLowering *XTLI) {
15878   SDValue Op0 = N->getOperand(0);
15879   EVT InVT = Op0->getValueType(0);
15880
15881   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15882   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15883     DebugLoc dl = N->getDebugLoc();
15884     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15885     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15886     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15887   }
15888
15889   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15890   // a 32-bit target where SSE doesn't support i64->FP operations.
15891   if (Op0.getOpcode() == ISD::LOAD) {
15892     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15893     EVT VT = Ld->getValueType(0);
15894     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15895         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15896         !XTLI->getSubtarget()->is64Bit() &&
15897         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15898       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15899                                           Ld->getChain(), Op0, DAG);
15900       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15901       return FILDChain;
15902     }
15903   }
15904   return SDValue();
15905 }
15906
15907 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15908   EVT VT = N->getValueType(0);
15909
15910   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15911   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15912     DebugLoc dl = N->getDebugLoc();
15913     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15914     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15915     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15916   }
15917
15918   return SDValue();
15919 }
15920
15921 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15922 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15923                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15924   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15925   // the result is either zero or one (depending on the input carry bit).
15926   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15927   if (X86::isZeroNode(N->getOperand(0)) &&
15928       X86::isZeroNode(N->getOperand(1)) &&
15929       // We don't have a good way to replace an EFLAGS use, so only do this when
15930       // dead right now.
15931       SDValue(N, 1).use_empty()) {
15932     DebugLoc DL = N->getDebugLoc();
15933     EVT VT = N->getValueType(0);
15934     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15935     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15936                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15937                                            DAG.getConstant(X86::COND_B,MVT::i8),
15938                                            N->getOperand(2)),
15939                                DAG.getConstant(1, VT));
15940     return DCI.CombineTo(N, Res1, CarryOut);
15941   }
15942
15943   return SDValue();
15944 }
15945
15946 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15947 //      (add Y, (setne X, 0)) -> sbb -1, Y
15948 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15949 //      (sub (setne X, 0), Y) -> adc -1, Y
15950 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15951   DebugLoc DL = N->getDebugLoc();
15952
15953   // Look through ZExts.
15954   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15955   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15956     return SDValue();
15957
15958   SDValue SetCC = Ext.getOperand(0);
15959   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15960     return SDValue();
15961
15962   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15963   if (CC != X86::COND_E && CC != X86::COND_NE)
15964     return SDValue();
15965
15966   SDValue Cmp = SetCC.getOperand(1);
15967   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15968       !X86::isZeroNode(Cmp.getOperand(1)) ||
15969       !Cmp.getOperand(0).getValueType().isInteger())
15970     return SDValue();
15971
15972   SDValue CmpOp0 = Cmp.getOperand(0);
15973   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15974                                DAG.getConstant(1, CmpOp0.getValueType()));
15975
15976   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15977   if (CC == X86::COND_NE)
15978     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15979                        DL, OtherVal.getValueType(), OtherVal,
15980                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15981   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15982                      DL, OtherVal.getValueType(), OtherVal,
15983                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15984 }
15985
15986 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15987 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15988                                  const X86Subtarget *Subtarget) {
15989   EVT VT = N->getValueType(0);
15990   SDValue Op0 = N->getOperand(0);
15991   SDValue Op1 = N->getOperand(1);
15992
15993   // Try to synthesize horizontal adds from adds of shuffles.
15994   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15995        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15996       isHorizontalBinOp(Op0, Op1, true))
15997     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15998
15999   return OptimizeConditionalInDecrement(N, DAG);
16000 }
16001
16002 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16003                                  const X86Subtarget *Subtarget) {
16004   SDValue Op0 = N->getOperand(0);
16005   SDValue Op1 = N->getOperand(1);
16006
16007   // X86 can't encode an immediate LHS of a sub. See if we can push the
16008   // negation into a preceding instruction.
16009   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16010     // If the RHS of the sub is a XOR with one use and a constant, invert the
16011     // immediate. Then add one to the LHS of the sub so we can turn
16012     // X-Y -> X+~Y+1, saving one register.
16013     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16014         isa<ConstantSDNode>(Op1.getOperand(1))) {
16015       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16016       EVT VT = Op0.getValueType();
16017       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16018                                    Op1.getOperand(0),
16019                                    DAG.getConstant(~XorC, VT));
16020       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16021                          DAG.getConstant(C->getAPIntValue()+1, VT));
16022     }
16023   }
16024
16025   // Try to synthesize horizontal adds from adds of shuffles.
16026   EVT VT = N->getValueType(0);
16027   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16028        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16029       isHorizontalBinOp(Op0, Op1, true))
16030     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16031
16032   return OptimizeConditionalInDecrement(N, DAG);
16033 }
16034
16035 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16036                                              DAGCombinerInfo &DCI) const {
16037   SelectionDAG &DAG = DCI.DAG;
16038   switch (N->getOpcode()) {
16039   default: break;
16040   case ISD::EXTRACT_VECTOR_ELT:
16041     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16042   case ISD::VSELECT:
16043   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16044   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16045   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16046   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16047   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16048   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16049   case ISD::SHL:
16050   case ISD::SRA:
16051   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16052   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16053   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16054   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16055   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16056   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16057   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16058   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16059   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16060   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16061   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16062   case X86ISD::FXOR:
16063   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16064   case X86ISD::FMIN:
16065   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16066   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16067   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16068   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16069   case ISD::ANY_EXTEND:
16070   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16071   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16072   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16073   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16074   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16075   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16076   case X86ISD::SHUFP:       // Handle all target specific shuffles
16077   case X86ISD::PALIGN:
16078   case X86ISD::UNPCKH:
16079   case X86ISD::UNPCKL:
16080   case X86ISD::MOVHLPS:
16081   case X86ISD::MOVLHPS:
16082   case X86ISD::PSHUFD:
16083   case X86ISD::PSHUFHW:
16084   case X86ISD::PSHUFLW:
16085   case X86ISD::MOVSS:
16086   case X86ISD::MOVSD:
16087   case X86ISD::VPERMILP:
16088   case X86ISD::VPERM2X128:
16089   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16090   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16091   }
16092
16093   return SDValue();
16094 }
16095
16096 /// isTypeDesirableForOp - Return true if the target has native support for
16097 /// the specified value type and it is 'desirable' to use the type for the
16098 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16099 /// instruction encodings are longer and some i16 instructions are slow.
16100 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16101   if (!isTypeLegal(VT))
16102     return false;
16103   if (VT != MVT::i16)
16104     return true;
16105
16106   switch (Opc) {
16107   default:
16108     return true;
16109   case ISD::LOAD:
16110   case ISD::SIGN_EXTEND:
16111   case ISD::ZERO_EXTEND:
16112   case ISD::ANY_EXTEND:
16113   case ISD::SHL:
16114   case ISD::SRL:
16115   case ISD::SUB:
16116   case ISD::ADD:
16117   case ISD::MUL:
16118   case ISD::AND:
16119   case ISD::OR:
16120   case ISD::XOR:
16121     return false;
16122   }
16123 }
16124
16125 /// IsDesirableToPromoteOp - This method query the target whether it is
16126 /// beneficial for dag combiner to promote the specified node. If true, it
16127 /// should return the desired promotion type by reference.
16128 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16129   EVT VT = Op.getValueType();
16130   if (VT != MVT::i16)
16131     return false;
16132
16133   bool Promote = false;
16134   bool Commute = false;
16135   switch (Op.getOpcode()) {
16136   default: break;
16137   case ISD::LOAD: {
16138     LoadSDNode *LD = cast<LoadSDNode>(Op);
16139     // If the non-extending load has a single use and it's not live out, then it
16140     // might be folded.
16141     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16142                                                      Op.hasOneUse()*/) {
16143       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16144              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16145         // The only case where we'd want to promote LOAD (rather then it being
16146         // promoted as an operand is when it's only use is liveout.
16147         if (UI->getOpcode() != ISD::CopyToReg)
16148           return false;
16149       }
16150     }
16151     Promote = true;
16152     break;
16153   }
16154   case ISD::SIGN_EXTEND:
16155   case ISD::ZERO_EXTEND:
16156   case ISD::ANY_EXTEND:
16157     Promote = true;
16158     break;
16159   case ISD::SHL:
16160   case ISD::SRL: {
16161     SDValue N0 = Op.getOperand(0);
16162     // Look out for (store (shl (load), x)).
16163     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16164       return false;
16165     Promote = true;
16166     break;
16167   }
16168   case ISD::ADD:
16169   case ISD::MUL:
16170   case ISD::AND:
16171   case ISD::OR:
16172   case ISD::XOR:
16173     Commute = true;
16174     // fallthrough
16175   case ISD::SUB: {
16176     SDValue N0 = Op.getOperand(0);
16177     SDValue N1 = Op.getOperand(1);
16178     if (!Commute && MayFoldLoad(N1))
16179       return false;
16180     // Avoid disabling potential load folding opportunities.
16181     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16182       return false;
16183     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16184       return false;
16185     Promote = true;
16186   }
16187   }
16188
16189   PVT = MVT::i32;
16190   return Promote;
16191 }
16192
16193 //===----------------------------------------------------------------------===//
16194 //                           X86 Inline Assembly Support
16195 //===----------------------------------------------------------------------===//
16196
16197 namespace {
16198   // Helper to match a string separated by whitespace.
16199   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16200     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16201
16202     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16203       StringRef piece(*args[i]);
16204       if (!s.startswith(piece)) // Check if the piece matches.
16205         return false;
16206
16207       s = s.substr(piece.size());
16208       StringRef::size_type pos = s.find_first_not_of(" \t");
16209       if (pos == 0) // We matched a prefix.
16210         return false;
16211
16212       s = s.substr(pos);
16213     }
16214
16215     return s.empty();
16216   }
16217   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16218 }
16219
16220 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16221   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16222
16223   std::string AsmStr = IA->getAsmString();
16224
16225   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16226   if (!Ty || Ty->getBitWidth() % 16 != 0)
16227     return false;
16228
16229   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16230   SmallVector<StringRef, 4> AsmPieces;
16231   SplitString(AsmStr, AsmPieces, ";\n");
16232
16233   switch (AsmPieces.size()) {
16234   default: return false;
16235   case 1:
16236     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16237     // we will turn this bswap into something that will be lowered to logical
16238     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16239     // lower so don't worry about this.
16240     // bswap $0
16241     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16242         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16243         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16244         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16245         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16246         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16247       // No need to check constraints, nothing other than the equivalent of
16248       // "=r,0" would be valid here.
16249       return IntrinsicLowering::LowerToByteSwap(CI);
16250     }
16251
16252     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16253     if (CI->getType()->isIntegerTy(16) &&
16254         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16255         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16256          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16257       AsmPieces.clear();
16258       const std::string &ConstraintsStr = IA->getConstraintString();
16259       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16260       std::sort(AsmPieces.begin(), AsmPieces.end());
16261       if (AsmPieces.size() == 4 &&
16262           AsmPieces[0] == "~{cc}" &&
16263           AsmPieces[1] == "~{dirflag}" &&
16264           AsmPieces[2] == "~{flags}" &&
16265           AsmPieces[3] == "~{fpsr}")
16266       return IntrinsicLowering::LowerToByteSwap(CI);
16267     }
16268     break;
16269   case 3:
16270     if (CI->getType()->isIntegerTy(32) &&
16271         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16272         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16273         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16274         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16275       AsmPieces.clear();
16276       const std::string &ConstraintsStr = IA->getConstraintString();
16277       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16278       std::sort(AsmPieces.begin(), AsmPieces.end());
16279       if (AsmPieces.size() == 4 &&
16280           AsmPieces[0] == "~{cc}" &&
16281           AsmPieces[1] == "~{dirflag}" &&
16282           AsmPieces[2] == "~{flags}" &&
16283           AsmPieces[3] == "~{fpsr}")
16284         return IntrinsicLowering::LowerToByteSwap(CI);
16285     }
16286
16287     if (CI->getType()->isIntegerTy(64)) {
16288       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16289       if (Constraints.size() >= 2 &&
16290           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16291           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16292         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16293         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16294             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16295             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16296           return IntrinsicLowering::LowerToByteSwap(CI);
16297       }
16298     }
16299     break;
16300   }
16301   return false;
16302 }
16303
16304
16305
16306 /// getConstraintType - Given a constraint letter, return the type of
16307 /// constraint it is for this target.
16308 X86TargetLowering::ConstraintType
16309 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16310   if (Constraint.size() == 1) {
16311     switch (Constraint[0]) {
16312     case 'R':
16313     case 'q':
16314     case 'Q':
16315     case 'f':
16316     case 't':
16317     case 'u':
16318     case 'y':
16319     case 'x':
16320     case 'Y':
16321     case 'l':
16322       return C_RegisterClass;
16323     case 'a':
16324     case 'b':
16325     case 'c':
16326     case 'd':
16327     case 'S':
16328     case 'D':
16329     case 'A':
16330       return C_Register;
16331     case 'I':
16332     case 'J':
16333     case 'K':
16334     case 'L':
16335     case 'M':
16336     case 'N':
16337     case 'G':
16338     case 'C':
16339     case 'e':
16340     case 'Z':
16341       return C_Other;
16342     default:
16343       break;
16344     }
16345   }
16346   return TargetLowering::getConstraintType(Constraint);
16347 }
16348
16349 /// Examine constraint type and operand type and determine a weight value.
16350 /// This object must already have been set up with the operand type
16351 /// and the current alternative constraint selected.
16352 TargetLowering::ConstraintWeight
16353   X86TargetLowering::getSingleConstraintMatchWeight(
16354     AsmOperandInfo &info, const char *constraint) const {
16355   ConstraintWeight weight = CW_Invalid;
16356   Value *CallOperandVal = info.CallOperandVal;
16357     // If we don't have a value, we can't do a match,
16358     // but allow it at the lowest weight.
16359   if (CallOperandVal == NULL)
16360     return CW_Default;
16361   Type *type = CallOperandVal->getType();
16362   // Look at the constraint type.
16363   switch (*constraint) {
16364   default:
16365     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16366   case 'R':
16367   case 'q':
16368   case 'Q':
16369   case 'a':
16370   case 'b':
16371   case 'c':
16372   case 'd':
16373   case 'S':
16374   case 'D':
16375   case 'A':
16376     if (CallOperandVal->getType()->isIntegerTy())
16377       weight = CW_SpecificReg;
16378     break;
16379   case 'f':
16380   case 't':
16381   case 'u':
16382       if (type->isFloatingPointTy())
16383         weight = CW_SpecificReg;
16384       break;
16385   case 'y':
16386       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16387         weight = CW_SpecificReg;
16388       break;
16389   case 'x':
16390   case 'Y':
16391     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16392         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16393       weight = CW_Register;
16394     break;
16395   case 'I':
16396     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16397       if (C->getZExtValue() <= 31)
16398         weight = CW_Constant;
16399     }
16400     break;
16401   case 'J':
16402     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16403       if (C->getZExtValue() <= 63)
16404         weight = CW_Constant;
16405     }
16406     break;
16407   case 'K':
16408     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16409       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16410         weight = CW_Constant;
16411     }
16412     break;
16413   case 'L':
16414     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16415       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16416         weight = CW_Constant;
16417     }
16418     break;
16419   case 'M':
16420     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16421       if (C->getZExtValue() <= 3)
16422         weight = CW_Constant;
16423     }
16424     break;
16425   case 'N':
16426     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16427       if (C->getZExtValue() <= 0xff)
16428         weight = CW_Constant;
16429     }
16430     break;
16431   case 'G':
16432   case 'C':
16433     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16434       weight = CW_Constant;
16435     }
16436     break;
16437   case 'e':
16438     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16439       if ((C->getSExtValue() >= -0x80000000LL) &&
16440           (C->getSExtValue() <= 0x7fffffffLL))
16441         weight = CW_Constant;
16442     }
16443     break;
16444   case 'Z':
16445     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16446       if (C->getZExtValue() <= 0xffffffff)
16447         weight = CW_Constant;
16448     }
16449     break;
16450   }
16451   return weight;
16452 }
16453
16454 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16455 /// with another that has more specific requirements based on the type of the
16456 /// corresponding operand.
16457 const char *X86TargetLowering::
16458 LowerXConstraint(EVT ConstraintVT) const {
16459   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16460   // 'f' like normal targets.
16461   if (ConstraintVT.isFloatingPoint()) {
16462     if (Subtarget->hasSSE2())
16463       return "Y";
16464     if (Subtarget->hasSSE1())
16465       return "x";
16466   }
16467
16468   return TargetLowering::LowerXConstraint(ConstraintVT);
16469 }
16470
16471 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16472 /// vector.  If it is invalid, don't add anything to Ops.
16473 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16474                                                      std::string &Constraint,
16475                                                      std::vector<SDValue>&Ops,
16476                                                      SelectionDAG &DAG) const {
16477   SDValue Result(0, 0);
16478
16479   // Only support length 1 constraints for now.
16480   if (Constraint.length() > 1) return;
16481
16482   char ConstraintLetter = Constraint[0];
16483   switch (ConstraintLetter) {
16484   default: break;
16485   case 'I':
16486     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16487       if (C->getZExtValue() <= 31) {
16488         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16489         break;
16490       }
16491     }
16492     return;
16493   case 'J':
16494     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16495       if (C->getZExtValue() <= 63) {
16496         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16497         break;
16498       }
16499     }
16500     return;
16501   case 'K':
16502     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16503       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16504         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16505         break;
16506       }
16507     }
16508     return;
16509   case 'N':
16510     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16511       if (C->getZExtValue() <= 255) {
16512         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16513         break;
16514       }
16515     }
16516     return;
16517   case 'e': {
16518     // 32-bit signed value
16519     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16520       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16521                                            C->getSExtValue())) {
16522         // Widen to 64 bits here to get it sign extended.
16523         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16524         break;
16525       }
16526     // FIXME gcc accepts some relocatable values here too, but only in certain
16527     // memory models; it's complicated.
16528     }
16529     return;
16530   }
16531   case 'Z': {
16532     // 32-bit unsigned value
16533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16534       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16535                                            C->getZExtValue())) {
16536         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16537         break;
16538       }
16539     }
16540     // FIXME gcc accepts some relocatable values here too, but only in certain
16541     // memory models; it's complicated.
16542     return;
16543   }
16544   case 'i': {
16545     // Literal immediates are always ok.
16546     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16547       // Widen to 64 bits here to get it sign extended.
16548       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16549       break;
16550     }
16551
16552     // In any sort of PIC mode addresses need to be computed at runtime by
16553     // adding in a register or some sort of table lookup.  These can't
16554     // be used as immediates.
16555     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16556       return;
16557
16558     // If we are in non-pic codegen mode, we allow the address of a global (with
16559     // an optional displacement) to be used with 'i'.
16560     GlobalAddressSDNode *GA = 0;
16561     int64_t Offset = 0;
16562
16563     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16564     while (1) {
16565       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16566         Offset += GA->getOffset();
16567         break;
16568       } else if (Op.getOpcode() == ISD::ADD) {
16569         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16570           Offset += C->getZExtValue();
16571           Op = Op.getOperand(0);
16572           continue;
16573         }
16574       } else if (Op.getOpcode() == ISD::SUB) {
16575         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16576           Offset += -C->getZExtValue();
16577           Op = Op.getOperand(0);
16578           continue;
16579         }
16580       }
16581
16582       // Otherwise, this isn't something we can handle, reject it.
16583       return;
16584     }
16585
16586     const GlobalValue *GV = GA->getGlobal();
16587     // If we require an extra load to get this address, as in PIC mode, we
16588     // can't accept it.
16589     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16590                                                         getTargetMachine())))
16591       return;
16592
16593     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16594                                         GA->getValueType(0), Offset);
16595     break;
16596   }
16597   }
16598
16599   if (Result.getNode()) {
16600     Ops.push_back(Result);
16601     return;
16602   }
16603   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16604 }
16605
16606 std::pair<unsigned, const TargetRegisterClass*>
16607 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16608                                                 EVT VT) const {
16609   // First, see if this is a constraint that directly corresponds to an LLVM
16610   // register class.
16611   if (Constraint.size() == 1) {
16612     // GCC Constraint Letters
16613     switch (Constraint[0]) {
16614     default: break;
16615       // TODO: Slight differences here in allocation order and leaving
16616       // RIP in the class. Do they matter any more here than they do
16617       // in the normal allocation?
16618     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16619       if (Subtarget->is64Bit()) {
16620         if (VT == MVT::i32 || VT == MVT::f32)
16621           return std::make_pair(0U, &X86::GR32RegClass);
16622         if (VT == MVT::i16)
16623           return std::make_pair(0U, &X86::GR16RegClass);
16624         if (VT == MVT::i8 || VT == MVT::i1)
16625           return std::make_pair(0U, &X86::GR8RegClass);
16626         if (VT == MVT::i64 || VT == MVT::f64)
16627           return std::make_pair(0U, &X86::GR64RegClass);
16628         break;
16629       }
16630       // 32-bit fallthrough
16631     case 'Q':   // Q_REGS
16632       if (VT == MVT::i32 || VT == MVT::f32)
16633         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16634       if (VT == MVT::i16)
16635         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16636       if (VT == MVT::i8 || VT == MVT::i1)
16637         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16638       if (VT == MVT::i64)
16639         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16640       break;
16641     case 'r':   // GENERAL_REGS
16642     case 'l':   // INDEX_REGS
16643       if (VT == MVT::i8 || VT == MVT::i1)
16644         return std::make_pair(0U, &X86::GR8RegClass);
16645       if (VT == MVT::i16)
16646         return std::make_pair(0U, &X86::GR16RegClass);
16647       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16648         return std::make_pair(0U, &X86::GR32RegClass);
16649       return std::make_pair(0U, &X86::GR64RegClass);
16650     case 'R':   // LEGACY_REGS
16651       if (VT == MVT::i8 || VT == MVT::i1)
16652         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16653       if (VT == MVT::i16)
16654         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16655       if (VT == MVT::i32 || !Subtarget->is64Bit())
16656         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16657       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16658     case 'f':  // FP Stack registers.
16659       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16660       // value to the correct fpstack register class.
16661       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16662         return std::make_pair(0U, &X86::RFP32RegClass);
16663       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16664         return std::make_pair(0U, &X86::RFP64RegClass);
16665       return std::make_pair(0U, &X86::RFP80RegClass);
16666     case 'y':   // MMX_REGS if MMX allowed.
16667       if (!Subtarget->hasMMX()) break;
16668       return std::make_pair(0U, &X86::VR64RegClass);
16669     case 'Y':   // SSE_REGS if SSE2 allowed
16670       if (!Subtarget->hasSSE2()) break;
16671       // FALL THROUGH.
16672     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16673       if (!Subtarget->hasSSE1()) break;
16674
16675       switch (VT.getSimpleVT().SimpleTy) {
16676       default: break;
16677       // Scalar SSE types.
16678       case MVT::f32:
16679       case MVT::i32:
16680         return std::make_pair(0U, &X86::FR32RegClass);
16681       case MVT::f64:
16682       case MVT::i64:
16683         return std::make_pair(0U, &X86::FR64RegClass);
16684       // Vector types.
16685       case MVT::v16i8:
16686       case MVT::v8i16:
16687       case MVT::v4i32:
16688       case MVT::v2i64:
16689       case MVT::v4f32:
16690       case MVT::v2f64:
16691         return std::make_pair(0U, &X86::VR128RegClass);
16692       // AVX types.
16693       case MVT::v32i8:
16694       case MVT::v16i16:
16695       case MVT::v8i32:
16696       case MVT::v4i64:
16697       case MVT::v8f32:
16698       case MVT::v4f64:
16699         return std::make_pair(0U, &X86::VR256RegClass);
16700       }
16701       break;
16702     }
16703   }
16704
16705   // Use the default implementation in TargetLowering to convert the register
16706   // constraint into a member of a register class.
16707   std::pair<unsigned, const TargetRegisterClass*> Res;
16708   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16709
16710   // Not found as a standard register?
16711   if (Res.second == 0) {
16712     // Map st(0) -> st(7) -> ST0
16713     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16714         tolower(Constraint[1]) == 's' &&
16715         tolower(Constraint[2]) == 't' &&
16716         Constraint[3] == '(' &&
16717         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16718         Constraint[5] == ')' &&
16719         Constraint[6] == '}') {
16720
16721       Res.first = X86::ST0+Constraint[4]-'0';
16722       Res.second = &X86::RFP80RegClass;
16723       return Res;
16724     }
16725
16726     // GCC allows "st(0)" to be called just plain "st".
16727     if (StringRef("{st}").equals_lower(Constraint)) {
16728       Res.first = X86::ST0;
16729       Res.second = &X86::RFP80RegClass;
16730       return Res;
16731     }
16732
16733     // flags -> EFLAGS
16734     if (StringRef("{flags}").equals_lower(Constraint)) {
16735       Res.first = X86::EFLAGS;
16736       Res.second = &X86::CCRRegClass;
16737       return Res;
16738     }
16739
16740     // 'A' means EAX + EDX.
16741     if (Constraint == "A") {
16742       Res.first = X86::EAX;
16743       Res.second = &X86::GR32_ADRegClass;
16744       return Res;
16745     }
16746     return Res;
16747   }
16748
16749   // Otherwise, check to see if this is a register class of the wrong value
16750   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16751   // turn into {ax},{dx}.
16752   if (Res.second->hasType(VT))
16753     return Res;   // Correct type already, nothing to do.
16754
16755   // All of the single-register GCC register classes map their values onto
16756   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16757   // really want an 8-bit or 32-bit register, map to the appropriate register
16758   // class and return the appropriate register.
16759   if (Res.second == &X86::GR16RegClass) {
16760     if (VT == MVT::i8) {
16761       unsigned DestReg = 0;
16762       switch (Res.first) {
16763       default: break;
16764       case X86::AX: DestReg = X86::AL; break;
16765       case X86::DX: DestReg = X86::DL; break;
16766       case X86::CX: DestReg = X86::CL; break;
16767       case X86::BX: DestReg = X86::BL; break;
16768       }
16769       if (DestReg) {
16770         Res.first = DestReg;
16771         Res.second = &X86::GR8RegClass;
16772       }
16773     } else if (VT == MVT::i32) {
16774       unsigned DestReg = 0;
16775       switch (Res.first) {
16776       default: break;
16777       case X86::AX: DestReg = X86::EAX; break;
16778       case X86::DX: DestReg = X86::EDX; break;
16779       case X86::CX: DestReg = X86::ECX; break;
16780       case X86::BX: DestReg = X86::EBX; break;
16781       case X86::SI: DestReg = X86::ESI; break;
16782       case X86::DI: DestReg = X86::EDI; break;
16783       case X86::BP: DestReg = X86::EBP; break;
16784       case X86::SP: DestReg = X86::ESP; break;
16785       }
16786       if (DestReg) {
16787         Res.first = DestReg;
16788         Res.second = &X86::GR32RegClass;
16789       }
16790     } else if (VT == MVT::i64) {
16791       unsigned DestReg = 0;
16792       switch (Res.first) {
16793       default: break;
16794       case X86::AX: DestReg = X86::RAX; break;
16795       case X86::DX: DestReg = X86::RDX; break;
16796       case X86::CX: DestReg = X86::RCX; break;
16797       case X86::BX: DestReg = X86::RBX; break;
16798       case X86::SI: DestReg = X86::RSI; break;
16799       case X86::DI: DestReg = X86::RDI; break;
16800       case X86::BP: DestReg = X86::RBP; break;
16801       case X86::SP: DestReg = X86::RSP; break;
16802       }
16803       if (DestReg) {
16804         Res.first = DestReg;
16805         Res.second = &X86::GR64RegClass;
16806       }
16807     }
16808   } else if (Res.second == &X86::FR32RegClass ||
16809              Res.second == &X86::FR64RegClass ||
16810              Res.second == &X86::VR128RegClass) {
16811     // Handle references to XMM physical registers that got mapped into the
16812     // wrong class.  This can happen with constraints like {xmm0} where the
16813     // target independent register mapper will just pick the first match it can
16814     // find, ignoring the required type.
16815
16816     if (VT == MVT::f32 || VT == MVT::i32)
16817       Res.second = &X86::FR32RegClass;
16818     else if (VT == MVT::f64 || VT == MVT::i64)
16819       Res.second = &X86::FR64RegClass;
16820     else if (X86::VR128RegClass.hasType(VT))
16821       Res.second = &X86::VR128RegClass;
16822     else if (X86::VR256RegClass.hasType(VT))
16823       Res.second = &X86::VR256RegClass;
16824   }
16825
16826   return Res;
16827 }