Check SSSE3 instead of SSE4.1
[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 = getDataLayout();
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     addBypassSlowDiv(32, 8);
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   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462   // support continuation, user-level threading, and etc.. As a result, no
463   // other SjLj exception interfaces are implemented and please don't build
464   // your own exception handling based on them.
465   // LLVM/Clang supports zero-cost DWARF exception handling.
466   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
468
469   // Darwin ABI issue.
470   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
471   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
473   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
474   if (Subtarget->is64Bit())
475     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
477   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
480     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
481     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
482     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
483     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
484   }
485   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
488   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
489   if (Subtarget->is64Bit()) {
490     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
492     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasSSE1())
496     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
497
498   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
499   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
500
501   // On X86 and X86-64, atomic operations are lowered to locked instructions.
502   // Locked instructions, in turn, have implicit fence semantics (all memory
503   // operations are flushed before issuing the locked instruction, and they
504   // are not buffered), so we can fold away the common pattern of
505   // fence-atomic-fence.
506   setShouldFoldAtomicFences(true);
507
508   // Expand certain atomics
509   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510     MVT VT = IntVTs[i];
511     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
514   }
515
516   if (!Subtarget->is64Bit()) {
517     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
529   }
530
531   if (Subtarget->hasCmpxchg16b()) {
532     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
533   }
534
535   // FIXME - use subtarget debug flags
536   if (!Subtarget->isTargetDarwin() &&
537       !Subtarget->isTargetELF() &&
538       !Subtarget->isTargetCygMing()) {
539     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
540   }
541
542   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
544   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
546   if (Subtarget->is64Bit()) {
547     setExceptionPointerRegister(X86::RAX);
548     setExceptionSelectorRegister(X86::RDX);
549   } else {
550     setExceptionPointerRegister(X86::EAX);
551     setExceptionSelectorRegister(X86::EDX);
552   }
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555
556   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558
559   setOperationAction(ISD::TRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
729            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
730     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
745     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
747     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
784     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
785     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
789     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
790              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
791       setTruncStoreAction((MVT::SimpleValueType)VT,
792                           (MVT::SimpleValueType)InnerVT, Expand);
793     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
794     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
796   }
797
798   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
799   // with -msoft-float, disable use of MMX as well.
800   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
801     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
802     // No operations on x86mmx supported, everything uses intrinsics.
803   }
804
805   // MMX-sized vectors (other than x86mmx) are expected to be expanded
806   // into smaller operations.
807   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
808   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
809   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
811   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
812   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
813   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
814   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
815   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
816   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
817   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
818   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
819   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
820   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
821   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
822   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
823   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
827   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
828   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
829   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
830   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
832   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
836
837   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
838     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
839
840     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
846     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
847     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
848     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
849     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
850     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
852   }
853
854   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
855     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
856
857     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
858     // registers cannot be used even for integer operations.
859     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
860     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
861     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
862     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
863
864     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
865     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
866     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
867     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
868     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
869     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
870     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
871     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
872     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
874     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
875     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
879     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
880     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
881
882     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
883     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
886
887     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
892
893     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
894     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895       MVT VT = (MVT::SimpleValueType)i;
896       // Do not attempt to custom lower non-power-of-2 vectors
897       if (!isPowerOf2_32(VT.getVectorNumElements()))
898         continue;
899       // Do not attempt to custom lower non-128-bit vectors
900       if (!VT.is128BitVector())
901         continue;
902       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
903       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
904       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
905     }
906
907     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
909     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
912     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
913
914     if (Subtarget->is64Bit()) {
915       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
917     }
918
919     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
920     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
921       MVT VT = (MVT::SimpleValueType)i;
922
923       // Do not attempt to promote non-128-bit vectors
924       if (!VT.is128BitVector())
925         continue;
926
927       setOperationAction(ISD::AND,    VT, Promote);
928       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
929       setOperationAction(ISD::OR,     VT, Promote);
930       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
931       setOperationAction(ISD::XOR,    VT, Promote);
932       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
933       setOperationAction(ISD::LOAD,   VT, Promote);
934       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
935       setOperationAction(ISD::SELECT, VT, Promote);
936       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
937     }
938
939     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
940
941     // Custom lower v2i64 and v2f64 selects.
942     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
943     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
944     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
945     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
946
947     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
948     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
949
950     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
951     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
952
953     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
954   }
955
956   if (Subtarget->hasSSE41()) {
957     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
958     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
959     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
960     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
961     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
962     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
963     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
964     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
965     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
966     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
967
968     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
969     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
970
971     // FIXME: Do we need to handle scalar-to-vector here?
972     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
973
974     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
975     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
976     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
977     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
978     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
979
980     // i8 and i16 vectors are custom , because the source register and source
981     // source memory operand types are not the same width.  f32 vectors are
982     // custom since the immediate controlling the insert encodes additional
983     // information.
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
988
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
993
994     // FIXME: these should be Legal but thats only for the case where
995     // the index is constant.  For now custom expand to deal with that.
996     if (Subtarget->is64Bit()) {
997       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
998       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999     }
1000   }
1001
1002   if (Subtarget->hasSSE2()) {
1003     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1004     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1005
1006     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1007     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1008
1009     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1010     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1011
1012     if (Subtarget->hasAVX2()) {
1013       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1014       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1015
1016       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1017       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1018
1019       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1020     } else {
1021       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1022       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1023
1024       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1025       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1026
1027       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1028     }
1029   }
1030
1031   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1059     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1060
1061     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1062
1063     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1064
1065     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1066     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1067     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1068
1069     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1070
1071     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1072     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1073
1074     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1075     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1076
1077     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1078     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1079
1080     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1081     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1084
1085     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1086     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1088
1089     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1090     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1091     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1092     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1093
1094     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1095       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1096       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1097       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1098       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1099       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1100       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1101     }
1102
1103     if (Subtarget->hasAVX2()) {
1104       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1105       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1106       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1107       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1108
1109       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1110       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1111       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1112       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1113
1114       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1116       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1117       // Don't lower v32i8 because there is no 128-bit byte mul
1118
1119       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1120
1121       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1122       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1123
1124       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1125       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1126
1127       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1128     } else {
1129       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1130       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1131       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1132       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1133
1134       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1135       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1136       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1137       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1138
1139       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1140       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1141       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1142       // Don't lower v32i8 because there is no 128-bit byte mul
1143
1144       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1145       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1146
1147       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1149
1150       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1151     }
1152
1153     // Custom lower several nodes for 256-bit types.
1154     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1155              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1156       MVT VT = (MVT::SimpleValueType)i;
1157
1158       // Extract subvector is special because the value type
1159       // (result) is 128-bit but the source is 256-bit wide.
1160       if (VT.is128BitVector())
1161         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1162
1163       // Do not attempt to custom lower other non-256-bit vectors
1164       if (!VT.is256BitVector())
1165         continue;
1166
1167       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1168       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1169       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1170       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1171       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1172       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1173       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1174     }
1175
1176     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1177     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1178       MVT VT = (MVT::SimpleValueType)i;
1179
1180       // Do not attempt to promote non-256-bit vectors
1181       if (!VT.is256BitVector())
1182         continue;
1183
1184       setOperationAction(ISD::AND,    VT, Promote);
1185       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1186       setOperationAction(ISD::OR,     VT, Promote);
1187       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1188       setOperationAction(ISD::XOR,    VT, Promote);
1189       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1190       setOperationAction(ISD::LOAD,   VT, Promote);
1191       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1192       setOperationAction(ISD::SELECT, VT, Promote);
1193       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1194     }
1195   }
1196
1197   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1198   // of this type with custom code.
1199   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1200            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1201     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1202                        Custom);
1203   }
1204
1205   // We want to custom lower some of our intrinsics.
1206   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1207   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1208
1209
1210   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1211   // handle type legalization for these operations here.
1212   //
1213   // FIXME: We really should do custom legalization for addition and
1214   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1215   // than generic legalization for 64-bit multiplication-with-overflow, though.
1216   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1217     // Add/Sub/Mul with overflow operations are custom lowered.
1218     MVT VT = IntVTs[i];
1219     setOperationAction(ISD::SADDO, VT, Custom);
1220     setOperationAction(ISD::UADDO, VT, Custom);
1221     setOperationAction(ISD::SSUBO, VT, Custom);
1222     setOperationAction(ISD::USUBO, VT, Custom);
1223     setOperationAction(ISD::SMULO, VT, Custom);
1224     setOperationAction(ISD::UMULO, VT, Custom);
1225   }
1226
1227   // There are no 8-bit 3-address imul/mul instructions
1228   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1229   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1230
1231   if (!Subtarget->is64Bit()) {
1232     // These libcalls are not available in 32-bit.
1233     setLibcallName(RTLIB::SHL_I128, 0);
1234     setLibcallName(RTLIB::SRL_I128, 0);
1235     setLibcallName(RTLIB::SRA_I128, 0);
1236   }
1237
1238   // We have target-specific dag combine patterns for the following nodes:
1239   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1240   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1241   setTargetDAGCombine(ISD::VSELECT);
1242   setTargetDAGCombine(ISD::SELECT);
1243   setTargetDAGCombine(ISD::SHL);
1244   setTargetDAGCombine(ISD::SRA);
1245   setTargetDAGCombine(ISD::SRL);
1246   setTargetDAGCombine(ISD::OR);
1247   setTargetDAGCombine(ISD::AND);
1248   setTargetDAGCombine(ISD::ADD);
1249   setTargetDAGCombine(ISD::FADD);
1250   setTargetDAGCombine(ISD::FSUB);
1251   setTargetDAGCombine(ISD::FMA);
1252   setTargetDAGCombine(ISD::SUB);
1253   setTargetDAGCombine(ISD::LOAD);
1254   setTargetDAGCombine(ISD::STORE);
1255   setTargetDAGCombine(ISD::ZERO_EXTEND);
1256   setTargetDAGCombine(ISD::ANY_EXTEND);
1257   setTargetDAGCombine(ISD::SIGN_EXTEND);
1258   setTargetDAGCombine(ISD::TRUNCATE);
1259   setTargetDAGCombine(ISD::UINT_TO_FP);
1260   setTargetDAGCombine(ISD::SINT_TO_FP);
1261   setTargetDAGCombine(ISD::SETCC);
1262   if (Subtarget->is64Bit())
1263     setTargetDAGCombine(ISD::MUL);
1264   setTargetDAGCombine(ISD::XOR);
1265
1266   computeRegisterProperties();
1267
1268   // On Darwin, -Os means optimize for size without hurting performance,
1269   // do not reduce the limit.
1270   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1271   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1272   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1273   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1274   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1275   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1276   setPrefLoopAlignment(4); // 2^4 bytes.
1277   benefitFromCodePlacementOpt = true;
1278
1279   // Predictable cmov don't hurt on atom because it's in-order.
1280   predictableSelectIsExpensive = !Subtarget->isAtom();
1281
1282   setPrefFunctionAlignment(4); // 2^4 bytes.
1283 }
1284
1285
1286 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1287   if (!VT.isVector()) return MVT::i8;
1288   return VT.changeVectorElementTypeToInteger();
1289 }
1290
1291
1292 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1293 /// the desired ByVal argument alignment.
1294 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1295   if (MaxAlign == 16)
1296     return;
1297   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1298     if (VTy->getBitWidth() == 128)
1299       MaxAlign = 16;
1300   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1301     unsigned EltAlign = 0;
1302     getMaxByValAlign(ATy->getElementType(), EltAlign);
1303     if (EltAlign > MaxAlign)
1304       MaxAlign = EltAlign;
1305   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1306     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1307       unsigned EltAlign = 0;
1308       getMaxByValAlign(STy->getElementType(i), EltAlign);
1309       if (EltAlign > MaxAlign)
1310         MaxAlign = EltAlign;
1311       if (MaxAlign == 16)
1312         break;
1313     }
1314   }
1315 }
1316
1317 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1318 /// function arguments in the caller parameter area. For X86, aggregates
1319 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1320 /// are at 4-byte boundaries.
1321 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1322   if (Subtarget->is64Bit()) {
1323     // Max of 8 and alignment of type.
1324     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1325     if (TyAlign > 8)
1326       return TyAlign;
1327     return 8;
1328   }
1329
1330   unsigned Align = 4;
1331   if (Subtarget->hasSSE1())
1332     getMaxByValAlign(Ty, Align);
1333   return Align;
1334 }
1335
1336 /// getOptimalMemOpType - Returns the target specific optimal type for load
1337 /// and store operations as a result of memset, memcpy, and memmove
1338 /// lowering. If DstAlign is zero that means it's safe to destination
1339 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1340 /// means there isn't a need to check it against alignment requirement,
1341 /// probably because the source does not need to be loaded. If
1342 /// 'IsZeroVal' is true, that means it's safe to return a
1343 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1344 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1345 /// constant so it does not need to be loaded.
1346 /// It returns EVT::Other if the type should be determined using generic
1347 /// target-independent logic.
1348 EVT
1349 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1350                                        unsigned DstAlign, unsigned SrcAlign,
1351                                        bool IsZeroVal,
1352                                        bool MemcpyStrSrc,
1353                                        MachineFunction &MF) const {
1354   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1355   // linux.  This is because the stack realignment code can't handle certain
1356   // cases like PR2962.  This should be removed when PR2962 is fixed.
1357   const Function *F = MF.getFunction();
1358   if (IsZeroVal &&
1359       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1360     if (Size >= 16 &&
1361         (Subtarget->isUnalignedMemAccessFast() ||
1362          ((DstAlign == 0 || DstAlign >= 16) &&
1363           (SrcAlign == 0 || SrcAlign >= 16))) &&
1364         Subtarget->getStackAlignment() >= 16) {
1365       if (Subtarget->getStackAlignment() >= 32) {
1366         if (Subtarget->hasAVX2())
1367           return MVT::v8i32;
1368         if (Subtarget->hasAVX())
1369           return MVT::v8f32;
1370       }
1371       if (Subtarget->hasSSE2())
1372         return MVT::v4i32;
1373       if (Subtarget->hasSSE1())
1374         return MVT::v4f32;
1375     } else if (!MemcpyStrSrc && Size >= 8 &&
1376                !Subtarget->is64Bit() &&
1377                Subtarget->getStackAlignment() >= 8 &&
1378                Subtarget->hasSSE2()) {
1379       // Do not use f64 to lower memcpy if source is string constant. It's
1380       // better to use i32 to avoid the loads.
1381       return MVT::f64;
1382     }
1383   }
1384   if (Subtarget->is64Bit() && Size >= 8)
1385     return MVT::i64;
1386   return MVT::i32;
1387 }
1388
1389 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1390 /// current function.  The returned value is a member of the
1391 /// MachineJumpTableInfo::JTEntryKind enum.
1392 unsigned X86TargetLowering::getJumpTableEncoding() const {
1393   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1394   // symbol.
1395   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1396       Subtarget->isPICStyleGOT())
1397     return MachineJumpTableInfo::EK_Custom32;
1398
1399   // Otherwise, use the normal jump table encoding heuristics.
1400   return TargetLowering::getJumpTableEncoding();
1401 }
1402
1403 const MCExpr *
1404 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1405                                              const MachineBasicBlock *MBB,
1406                                              unsigned uid,MCContext &Ctx) const{
1407   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1408          Subtarget->isPICStyleGOT());
1409   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1410   // entries.
1411   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1412                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1413 }
1414
1415 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1416 /// jumptable.
1417 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1418                                                     SelectionDAG &DAG) const {
1419   if (!Subtarget->is64Bit())
1420     // This doesn't have DebugLoc associated with it, but is not really the
1421     // same as a Register.
1422     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1423   return Table;
1424 }
1425
1426 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1427 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1428 /// MCExpr.
1429 const MCExpr *X86TargetLowering::
1430 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1431                              MCContext &Ctx) const {
1432   // X86-64 uses RIP relative addressing based on the jump table label.
1433   if (Subtarget->isPICStyleRIPRel())
1434     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1435
1436   // Otherwise, the reference is relative to the PIC base.
1437   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1438 }
1439
1440 // FIXME: Why this routine is here? Move to RegInfo!
1441 std::pair<const TargetRegisterClass*, uint8_t>
1442 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1443   const TargetRegisterClass *RRC = 0;
1444   uint8_t Cost = 1;
1445   switch (VT.getSimpleVT().SimpleTy) {
1446   default:
1447     return TargetLowering::findRepresentativeClass(VT);
1448   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1449     RRC = Subtarget->is64Bit() ?
1450       (const TargetRegisterClass*)&X86::GR64RegClass :
1451       (const TargetRegisterClass*)&X86::GR32RegClass;
1452     break;
1453   case MVT::x86mmx:
1454     RRC = &X86::VR64RegClass;
1455     break;
1456   case MVT::f32: case MVT::f64:
1457   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1458   case MVT::v4f32: case MVT::v2f64:
1459   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1460   case MVT::v4f64:
1461     RRC = &X86::VR128RegClass;
1462     break;
1463   }
1464   return std::make_pair(RRC, Cost);
1465 }
1466
1467 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1468                                                unsigned &Offset) const {
1469   if (!Subtarget->isTargetLinux())
1470     return false;
1471
1472   if (Subtarget->is64Bit()) {
1473     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1474     Offset = 0x28;
1475     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1476       AddressSpace = 256;
1477     else
1478       AddressSpace = 257;
1479   } else {
1480     // %gs:0x14 on i386
1481     Offset = 0x14;
1482     AddressSpace = 256;
1483   }
1484   return true;
1485 }
1486
1487
1488 //===----------------------------------------------------------------------===//
1489 //               Return Value Calling Convention Implementation
1490 //===----------------------------------------------------------------------===//
1491
1492 #include "X86GenCallingConv.inc"
1493
1494 bool
1495 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1496                                   MachineFunction &MF, bool isVarArg,
1497                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1498                         LLVMContext &Context) const {
1499   SmallVector<CCValAssign, 16> RVLocs;
1500   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1501                  RVLocs, Context);
1502   return CCInfo.CheckReturn(Outs, RetCC_X86);
1503 }
1504
1505 SDValue
1506 X86TargetLowering::LowerReturn(SDValue Chain,
1507                                CallingConv::ID CallConv, bool isVarArg,
1508                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1509                                const SmallVectorImpl<SDValue> &OutVals,
1510                                DebugLoc dl, SelectionDAG &DAG) const {
1511   MachineFunction &MF = DAG.getMachineFunction();
1512   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1513
1514   SmallVector<CCValAssign, 16> RVLocs;
1515   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1516                  RVLocs, *DAG.getContext());
1517   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1518
1519   // Add the regs to the liveout set for the function.
1520   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1521   for (unsigned i = 0; i != RVLocs.size(); ++i)
1522     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1523       MRI.addLiveOut(RVLocs[i].getLocReg());
1524
1525   SDValue Flag;
1526
1527   SmallVector<SDValue, 6> RetOps;
1528   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1529   // Operand #1 = Bytes To Pop
1530   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1531                    MVT::i16));
1532
1533   // Copy the result values into the output registers.
1534   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1535     CCValAssign &VA = RVLocs[i];
1536     assert(VA.isRegLoc() && "Can only return in registers!");
1537     SDValue ValToCopy = OutVals[i];
1538     EVT ValVT = ValToCopy.getValueType();
1539
1540     // Promote values to the appropriate types
1541     if (VA.getLocInfo() == CCValAssign::SExt)
1542       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1543     else if (VA.getLocInfo() == CCValAssign::ZExt)
1544       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1545     else if (VA.getLocInfo() == CCValAssign::AExt)
1546       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1547     else if (VA.getLocInfo() == CCValAssign::BCvt)
1548       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1549
1550     // If this is x86-64, and we disabled SSE, we can't return FP values,
1551     // or SSE or MMX vectors.
1552     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1553          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1554           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1555       report_fatal_error("SSE register return with SSE disabled");
1556     }
1557     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1558     // llvm-gcc has never done it right and no one has noticed, so this
1559     // should be OK for now.
1560     if (ValVT == MVT::f64 &&
1561         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1562       report_fatal_error("SSE2 register return with SSE2 disabled");
1563
1564     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1565     // the RET instruction and handled by the FP Stackifier.
1566     if (VA.getLocReg() == X86::ST0 ||
1567         VA.getLocReg() == X86::ST1) {
1568       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1569       // change the value to the FP stack register class.
1570       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1571         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1572       RetOps.push_back(ValToCopy);
1573       // Don't emit a copytoreg.
1574       continue;
1575     }
1576
1577     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1578     // which is returned in RAX / RDX.
1579     if (Subtarget->is64Bit()) {
1580       if (ValVT == MVT::x86mmx) {
1581         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1582           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1583           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1584                                   ValToCopy);
1585           // If we don't have SSE2 available, convert to v4f32 so the generated
1586           // register is legal.
1587           if (!Subtarget->hasSSE2())
1588             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1589         }
1590       }
1591     }
1592
1593     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1594     Flag = Chain.getValue(1);
1595   }
1596
1597   // The x86-64 ABI for returning structs by value requires that we copy
1598   // the sret argument into %rax for the return. We saved the argument into
1599   // a virtual register in the entry block, so now we copy the value out
1600   // and into %rax.
1601   if (Subtarget->is64Bit() &&
1602       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1603     MachineFunction &MF = DAG.getMachineFunction();
1604     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1605     unsigned Reg = FuncInfo->getSRetReturnReg();
1606     assert(Reg &&
1607            "SRetReturnReg should have been set in LowerFormalArguments().");
1608     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1609
1610     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1611     Flag = Chain.getValue(1);
1612
1613     // RAX now acts like a return value.
1614     MRI.addLiveOut(X86::RAX);
1615   }
1616
1617   RetOps[0] = Chain;  // Update chain.
1618
1619   // Add the flag if we have it.
1620   if (Flag.getNode())
1621     RetOps.push_back(Flag);
1622
1623   return DAG.getNode(X86ISD::RET_FLAG, dl,
1624                      MVT::Other, &RetOps[0], RetOps.size());
1625 }
1626
1627 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1628   if (N->getNumValues() != 1)
1629     return false;
1630   if (!N->hasNUsesOfValue(1, 0))
1631     return false;
1632
1633   SDValue TCChain = Chain;
1634   SDNode *Copy = *N->use_begin();
1635   if (Copy->getOpcode() == ISD::CopyToReg) {
1636     // If the copy has a glue operand, we conservatively assume it isn't safe to
1637     // perform a tail call.
1638     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1639       return false;
1640     TCChain = Copy->getOperand(0);
1641   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1642     return false;
1643
1644   bool HasRet = false;
1645   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1646        UI != UE; ++UI) {
1647     if (UI->getOpcode() != X86ISD::RET_FLAG)
1648       return false;
1649     HasRet = true;
1650   }
1651
1652   if (!HasRet)
1653     return false;
1654
1655   Chain = TCChain;
1656   return true;
1657 }
1658
1659 EVT
1660 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1661                                             ISD::NodeType ExtendKind) const {
1662   MVT ReturnMVT;
1663   // TODO: Is this also valid on 32-bit?
1664   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1665     ReturnMVT = MVT::i8;
1666   else
1667     ReturnMVT = MVT::i32;
1668
1669   EVT MinVT = getRegisterType(Context, ReturnMVT);
1670   return VT.bitsLT(MinVT) ? MinVT : VT;
1671 }
1672
1673 /// LowerCallResult - Lower the result values of a call into the
1674 /// appropriate copies out of appropriate physical registers.
1675 ///
1676 SDValue
1677 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1678                                    CallingConv::ID CallConv, bool isVarArg,
1679                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1680                                    DebugLoc dl, SelectionDAG &DAG,
1681                                    SmallVectorImpl<SDValue> &InVals) const {
1682
1683   // Assign locations to each value returned by this call.
1684   SmallVector<CCValAssign, 16> RVLocs;
1685   bool Is64Bit = Subtarget->is64Bit();
1686   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1687                  getTargetMachine(), RVLocs, *DAG.getContext());
1688   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1689
1690   // Copy all of the result registers out of their specified physreg.
1691   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1692     CCValAssign &VA = RVLocs[i];
1693     EVT CopyVT = VA.getValVT();
1694
1695     // If this is x86-64, and we disabled SSE, we can't return FP values
1696     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1697         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1698       report_fatal_error("SSE register return with SSE disabled");
1699     }
1700
1701     SDValue Val;
1702
1703     // If this is a call to a function that returns an fp value on the floating
1704     // point stack, we must guarantee the value is popped from the stack, so
1705     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1706     // if the return value is not used. We use the FpPOP_RETVAL instruction
1707     // instead.
1708     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1709       // If we prefer to use the value in xmm registers, copy it out as f80 and
1710       // use a truncate to move it from fp stack reg to xmm reg.
1711       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1712       SDValue Ops[] = { Chain, InFlag };
1713       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1714                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1715       Val = Chain.getValue(0);
1716
1717       // Round the f80 to the right size, which also moves it to the appropriate
1718       // xmm register.
1719       if (CopyVT != VA.getValVT())
1720         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1721                           // This truncation won't change the value.
1722                           DAG.getIntPtrConstant(1));
1723     } else {
1724       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1725                                  CopyVT, InFlag).getValue(1);
1726       Val = Chain.getValue(0);
1727     }
1728     InFlag = Chain.getValue(2);
1729     InVals.push_back(Val);
1730   }
1731
1732   return Chain;
1733 }
1734
1735
1736 //===----------------------------------------------------------------------===//
1737 //                C & StdCall & Fast Calling Convention implementation
1738 //===----------------------------------------------------------------------===//
1739 //  StdCall calling convention seems to be standard for many Windows' API
1740 //  routines and around. It differs from C calling convention just a little:
1741 //  callee should clean up the stack, not caller. Symbols should be also
1742 //  decorated in some fancy way :) It doesn't support any vector arguments.
1743 //  For info on fast calling convention see Fast Calling Convention (tail call)
1744 //  implementation LowerX86_32FastCCCallTo.
1745
1746 /// CallIsStructReturn - Determines whether a call uses struct return
1747 /// semantics.
1748 enum StructReturnType {
1749   NotStructReturn,
1750   RegStructReturn,
1751   StackStructReturn
1752 };
1753 static StructReturnType
1754 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1755   if (Outs.empty())
1756     return NotStructReturn;
1757
1758   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1759   if (!Flags.isSRet())
1760     return NotStructReturn;
1761   if (Flags.isInReg())
1762     return RegStructReturn;
1763   return StackStructReturn;
1764 }
1765
1766 /// ArgsAreStructReturn - Determines whether a function uses struct
1767 /// return semantics.
1768 static StructReturnType
1769 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1770   if (Ins.empty())
1771     return NotStructReturn;
1772
1773   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1774   if (!Flags.isSRet())
1775     return NotStructReturn;
1776   if (Flags.isInReg())
1777     return RegStructReturn;
1778   return StackStructReturn;
1779 }
1780
1781 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1782 /// by "Src" to address "Dst" with size and alignment information specified by
1783 /// the specific parameter attribute. The copy will be passed as a byval
1784 /// function parameter.
1785 static SDValue
1786 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1787                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1788                           DebugLoc dl) {
1789   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1790
1791   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1792                        /*isVolatile*/false, /*AlwaysInline=*/true,
1793                        MachinePointerInfo(), MachinePointerInfo());
1794 }
1795
1796 /// IsTailCallConvention - Return true if the calling convention is one that
1797 /// supports tail call optimization.
1798 static bool IsTailCallConvention(CallingConv::ID CC) {
1799   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1800 }
1801
1802 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1803   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1804     return false;
1805
1806   CallSite CS(CI);
1807   CallingConv::ID CalleeCC = CS.getCallingConv();
1808   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1809     return false;
1810
1811   return true;
1812 }
1813
1814 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1815 /// a tailcall target by changing its ABI.
1816 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1817                                    bool GuaranteedTailCallOpt) {
1818   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1819 }
1820
1821 SDValue
1822 X86TargetLowering::LowerMemArgument(SDValue Chain,
1823                                     CallingConv::ID CallConv,
1824                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1825                                     DebugLoc dl, SelectionDAG &DAG,
1826                                     const CCValAssign &VA,
1827                                     MachineFrameInfo *MFI,
1828                                     unsigned i) const {
1829   // Create the nodes corresponding to a load from this parameter slot.
1830   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1831   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1832                               getTargetMachine().Options.GuaranteedTailCallOpt);
1833   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1834   EVT ValVT;
1835
1836   // If value is passed by pointer we have address passed instead of the value
1837   // itself.
1838   if (VA.getLocInfo() == CCValAssign::Indirect)
1839     ValVT = VA.getLocVT();
1840   else
1841     ValVT = VA.getValVT();
1842
1843   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1844   // changed with more analysis.
1845   // In case of tail call optimization mark all arguments mutable. Since they
1846   // could be overwritten by lowering of arguments in case of a tail call.
1847   if (Flags.isByVal()) {
1848     unsigned Bytes = Flags.getByValSize();
1849     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1850     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1851     return DAG.getFrameIndex(FI, getPointerTy());
1852   } else {
1853     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1854                                     VA.getLocMemOffset(), isImmutable);
1855     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1856     return DAG.getLoad(ValVT, dl, Chain, FIN,
1857                        MachinePointerInfo::getFixedStack(FI),
1858                        false, false, false, 0);
1859   }
1860 }
1861
1862 SDValue
1863 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1864                                         CallingConv::ID CallConv,
1865                                         bool isVarArg,
1866                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1867                                         DebugLoc dl,
1868                                         SelectionDAG &DAG,
1869                                         SmallVectorImpl<SDValue> &InVals)
1870                                           const {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873
1874   const Function* Fn = MF.getFunction();
1875   if (Fn->hasExternalLinkage() &&
1876       Subtarget->isTargetCygMing() &&
1877       Fn->getName() == "main")
1878     FuncInfo->setForceFramePointer(true);
1879
1880   MachineFrameInfo *MFI = MF.getFrameInfo();
1881   bool Is64Bit = Subtarget->is64Bit();
1882   bool IsWindows = Subtarget->isTargetWindows();
1883   bool IsWin64 = Subtarget->isTargetWin64();
1884
1885   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1886          "Var args not supported with calling convention fastcc or ghc");
1887
1888   // Assign locations to all of the incoming arguments.
1889   SmallVector<CCValAssign, 16> ArgLocs;
1890   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1891                  ArgLocs, *DAG.getContext());
1892
1893   // Allocate shadow area for Win64
1894   if (IsWin64) {
1895     CCInfo.AllocateStack(32, 8);
1896   }
1897
1898   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1899
1900   unsigned LastVal = ~0U;
1901   SDValue ArgValue;
1902   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1903     CCValAssign &VA = ArgLocs[i];
1904     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1905     // places.
1906     assert(VA.getValNo() != LastVal &&
1907            "Don't support value assigned to multiple locs yet");
1908     (void)LastVal;
1909     LastVal = VA.getValNo();
1910
1911     if (VA.isRegLoc()) {
1912       EVT RegVT = VA.getLocVT();
1913       const TargetRegisterClass *RC;
1914       if (RegVT == MVT::i32)
1915         RC = &X86::GR32RegClass;
1916       else if (Is64Bit && RegVT == MVT::i64)
1917         RC = &X86::GR64RegClass;
1918       else if (RegVT == MVT::f32)
1919         RC = &X86::FR32RegClass;
1920       else if (RegVT == MVT::f64)
1921         RC = &X86::FR64RegClass;
1922       else if (RegVT.is256BitVector())
1923         RC = &X86::VR256RegClass;
1924       else if (RegVT.is128BitVector())
1925         RC = &X86::VR128RegClass;
1926       else if (RegVT == MVT::x86mmx)
1927         RC = &X86::VR64RegClass;
1928       else
1929         llvm_unreachable("Unknown argument type!");
1930
1931       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1932       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1933
1934       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1935       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1936       // right size.
1937       if (VA.getLocInfo() == CCValAssign::SExt)
1938         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1939                                DAG.getValueType(VA.getValVT()));
1940       else if (VA.getLocInfo() == CCValAssign::ZExt)
1941         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1942                                DAG.getValueType(VA.getValVT()));
1943       else if (VA.getLocInfo() == CCValAssign::BCvt)
1944         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1945
1946       if (VA.isExtInLoc()) {
1947         // Handle MMX values passed in XMM regs.
1948         if (RegVT.isVector()) {
1949           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1950                                  ArgValue);
1951         } else
1952           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1953       }
1954     } else {
1955       assert(VA.isMemLoc());
1956       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1957     }
1958
1959     // If value is passed via pointer - do a load.
1960     if (VA.getLocInfo() == CCValAssign::Indirect)
1961       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1962                              MachinePointerInfo(), false, false, false, 0);
1963
1964     InVals.push_back(ArgValue);
1965   }
1966
1967   // The x86-64 ABI for returning structs by value requires that we copy
1968   // the sret argument into %rax for the return. Save the argument into
1969   // a virtual register so that we can access it from the return points.
1970   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1971     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1972     unsigned Reg = FuncInfo->getSRetReturnReg();
1973     if (!Reg) {
1974       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1975       FuncInfo->setSRetReturnReg(Reg);
1976     }
1977     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1978     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1979   }
1980
1981   unsigned StackSize = CCInfo.getNextStackOffset();
1982   // Align stack specially for tail calls.
1983   if (FuncIsMadeTailCallSafe(CallConv,
1984                              MF.getTarget().Options.GuaranteedTailCallOpt))
1985     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1986
1987   // If the function takes variable number of arguments, make a frame index for
1988   // the start of the first vararg value... for expansion of llvm.va_start.
1989   if (isVarArg) {
1990     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1991                     CallConv != CallingConv::X86_ThisCall)) {
1992       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1993     }
1994     if (Is64Bit) {
1995       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1996
1997       // FIXME: We should really autogenerate these arrays
1998       static const uint16_t GPR64ArgRegsWin64[] = {
1999         X86::RCX, X86::RDX, X86::R8,  X86::R9
2000       };
2001       static const uint16_t GPR64ArgRegs64Bit[] = {
2002         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2003       };
2004       static const uint16_t XMMArgRegs64Bit[] = {
2005         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2006         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2007       };
2008       const uint16_t *GPR64ArgRegs;
2009       unsigned NumXMMRegs = 0;
2010
2011       if (IsWin64) {
2012         // The XMM registers which might contain var arg parameters are shadowed
2013         // in their paired GPR.  So we only need to save the GPR to their home
2014         // slots.
2015         TotalNumIntRegs = 4;
2016         GPR64ArgRegs = GPR64ArgRegsWin64;
2017       } else {
2018         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2019         GPR64ArgRegs = GPR64ArgRegs64Bit;
2020
2021         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2022                                                 TotalNumXMMRegs);
2023       }
2024       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2025                                                        TotalNumIntRegs);
2026
2027       bool NoImplicitFloatOps = Fn->getFnAttributes().
2028         hasAttribute(Attributes::NoImplicitFloat);
2029       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2030              "SSE register cannot be used when SSE is disabled!");
2031       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2032                NoImplicitFloatOps) &&
2033              "SSE register cannot be used when SSE is disabled!");
2034       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2035           !Subtarget->hasSSE1())
2036         // Kernel mode asks for SSE to be disabled, so don't push them
2037         // on the stack.
2038         TotalNumXMMRegs = 0;
2039
2040       if (IsWin64) {
2041         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2042         // Get to the caller-allocated home save location.  Add 8 to account
2043         // for the return address.
2044         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2045         FuncInfo->setRegSaveFrameIndex(
2046           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2047         // Fixup to set vararg frame on shadow area (4 x i64).
2048         if (NumIntRegs < 4)
2049           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2050       } else {
2051         // For X86-64, if there are vararg parameters that are passed via
2052         // registers, then we must store them to their spots on the stack so
2053         // they may be loaded by deferencing the result of va_next.
2054         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2055         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2056         FuncInfo->setRegSaveFrameIndex(
2057           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2058                                false));
2059       }
2060
2061       // Store the integer parameter registers.
2062       SmallVector<SDValue, 8> MemOps;
2063       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2064                                         getPointerTy());
2065       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2066       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2067         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2068                                   DAG.getIntPtrConstant(Offset));
2069         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2070                                      &X86::GR64RegClass);
2071         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2072         SDValue Store =
2073           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2074                        MachinePointerInfo::getFixedStack(
2075                          FuncInfo->getRegSaveFrameIndex(), Offset),
2076                        false, false, 0);
2077         MemOps.push_back(Store);
2078         Offset += 8;
2079       }
2080
2081       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2082         // Now store the XMM (fp + vector) parameter registers.
2083         SmallVector<SDValue, 11> SaveXMMOps;
2084         SaveXMMOps.push_back(Chain);
2085
2086         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2087         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2088         SaveXMMOps.push_back(ALVal);
2089
2090         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2091                                FuncInfo->getRegSaveFrameIndex()));
2092         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2093                                FuncInfo->getVarArgsFPOffset()));
2094
2095         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2096           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2097                                        &X86::VR128RegClass);
2098           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2099           SaveXMMOps.push_back(Val);
2100         }
2101         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2102                                      MVT::Other,
2103                                      &SaveXMMOps[0], SaveXMMOps.size()));
2104       }
2105
2106       if (!MemOps.empty())
2107         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2108                             &MemOps[0], MemOps.size());
2109     }
2110   }
2111
2112   // Some CCs need callee pop.
2113   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2114                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2115     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2116   } else {
2117     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2118     // If this is an sret function, the return should pop the hidden pointer.
2119     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2120         argsAreStructReturn(Ins) == StackStructReturn)
2121       FuncInfo->setBytesToPopOnReturn(4);
2122   }
2123
2124   if (!Is64Bit) {
2125     // RegSaveFrameIndex is X86-64 only.
2126     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2127     if (CallConv == CallingConv::X86_FastCall ||
2128         CallConv == CallingConv::X86_ThisCall)
2129       // fastcc functions can't have varargs.
2130       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2131   }
2132
2133   FuncInfo->setArgumentStackSize(StackSize);
2134
2135   return Chain;
2136 }
2137
2138 SDValue
2139 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2140                                     SDValue StackPtr, SDValue Arg,
2141                                     DebugLoc dl, SelectionDAG &DAG,
2142                                     const CCValAssign &VA,
2143                                     ISD::ArgFlagsTy Flags) const {
2144   unsigned LocMemOffset = VA.getLocMemOffset();
2145   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2146   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2147   if (Flags.isByVal())
2148     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2149
2150   return DAG.getStore(Chain, dl, Arg, PtrOff,
2151                       MachinePointerInfo::getStack(LocMemOffset),
2152                       false, false, 0);
2153 }
2154
2155 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2156 /// optimization is performed and it is required.
2157 SDValue
2158 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2159                                            SDValue &OutRetAddr, SDValue Chain,
2160                                            bool IsTailCall, bool Is64Bit,
2161                                            int FPDiff, DebugLoc dl) const {
2162   // Adjust the Return address stack slot.
2163   EVT VT = getPointerTy();
2164   OutRetAddr = getReturnAddressFrameIndex(DAG);
2165
2166   // Load the "old" Return address.
2167   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2168                            false, false, false, 0);
2169   return SDValue(OutRetAddr.getNode(), 1);
2170 }
2171
2172 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2173 /// optimization is performed and it is required (FPDiff!=0).
2174 static SDValue
2175 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2176                          SDValue Chain, SDValue RetAddrFrIdx,
2177                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2178   // Store the return address to the appropriate stack slot.
2179   if (!FPDiff) return Chain;
2180   // Calculate the new stack slot for the return address.
2181   int SlotSize = Is64Bit ? 8 : 4;
2182   int NewReturnAddrFI =
2183     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2184   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2186   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2187                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2188                        false, false, 0);
2189   return Chain;
2190 }
2191
2192 SDValue
2193 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2194                              SmallVectorImpl<SDValue> &InVals) const {
2195   SelectionDAG &DAG                     = CLI.DAG;
2196   DebugLoc &dl                          = CLI.DL;
2197   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2198   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2199   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2200   SDValue Chain                         = CLI.Chain;
2201   SDValue Callee                        = CLI.Callee;
2202   CallingConv::ID CallConv              = CLI.CallConv;
2203   bool &isTailCall                      = CLI.IsTailCall;
2204   bool isVarArg                         = CLI.IsVarArg;
2205
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   bool Is64Bit        = Subtarget->is64Bit();
2208   bool IsWin64        = Subtarget->isTargetWin64();
2209   bool IsWindows      = Subtarget->isTargetWindows();
2210   StructReturnType SR = callIsStructReturn(Outs);
2211   bool IsSibcall      = false;
2212
2213   if (MF.getTarget().Options.DisableTailCalls)
2214     isTailCall = false;
2215
2216   if (isTailCall) {
2217     // Check if it's really possible to do a tail call.
2218     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2219                     isVarArg, SR != NotStructReturn,
2220                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2221                     Outs, OutVals, Ins, DAG);
2222
2223     // Sibcalls are automatically detected tailcalls which do not require
2224     // ABI changes.
2225     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2226       IsSibcall = true;
2227
2228     if (isTailCall)
2229       ++NumTailCalls;
2230   }
2231
2232   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2233          "Var args not supported with calling convention fastcc or ghc");
2234
2235   // Analyze operands of the call, assigning locations to each operand.
2236   SmallVector<CCValAssign, 16> ArgLocs;
2237   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2238                  ArgLocs, *DAG.getContext());
2239
2240   // Allocate shadow area for Win64
2241   if (IsWin64) {
2242     CCInfo.AllocateStack(32, 8);
2243   }
2244
2245   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2246
2247   // Get a count of how many bytes are to be pushed on the stack.
2248   unsigned NumBytes = CCInfo.getNextStackOffset();
2249   if (IsSibcall)
2250     // This is a sibcall. The memory operands are available in caller's
2251     // own caller's stack.
2252     NumBytes = 0;
2253   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2254            IsTailCallConvention(CallConv))
2255     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2256
2257   int FPDiff = 0;
2258   if (isTailCall && !IsSibcall) {
2259     // Lower arguments at fp - stackoffset + fpdiff.
2260     unsigned NumBytesCallerPushed =
2261       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2262     FPDiff = NumBytesCallerPushed - NumBytes;
2263
2264     // Set the delta of movement of the returnaddr stackslot.
2265     // But only set if delta is greater than previous delta.
2266     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2267       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2268   }
2269
2270   if (!IsSibcall)
2271     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2272
2273   SDValue RetAddrFrIdx;
2274   // Load return address for tail calls.
2275   if (isTailCall && FPDiff)
2276     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2277                                     Is64Bit, FPDiff, dl);
2278
2279   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2280   SmallVector<SDValue, 8> MemOpChains;
2281   SDValue StackPtr;
2282
2283   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2284   // of tail call optimization arguments are handle later.
2285   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2286     CCValAssign &VA = ArgLocs[i];
2287     EVT RegVT = VA.getLocVT();
2288     SDValue Arg = OutVals[i];
2289     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2290     bool isByVal = Flags.isByVal();
2291
2292     // Promote the value if needed.
2293     switch (VA.getLocInfo()) {
2294     default: llvm_unreachable("Unknown loc info!");
2295     case CCValAssign::Full: break;
2296     case CCValAssign::SExt:
2297       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2298       break;
2299     case CCValAssign::ZExt:
2300       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2301       break;
2302     case CCValAssign::AExt:
2303       if (RegVT.is128BitVector()) {
2304         // Special case: passing MMX values in XMM registers.
2305         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2306         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2307         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2308       } else
2309         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2310       break;
2311     case CCValAssign::BCvt:
2312       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2313       break;
2314     case CCValAssign::Indirect: {
2315       // Store the argument.
2316       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2317       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2318       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2319                            MachinePointerInfo::getFixedStack(FI),
2320                            false, false, 0);
2321       Arg = SpillSlot;
2322       break;
2323     }
2324     }
2325
2326     if (VA.isRegLoc()) {
2327       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2328       if (isVarArg && IsWin64) {
2329         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2330         // shadow reg if callee is a varargs function.
2331         unsigned ShadowReg = 0;
2332         switch (VA.getLocReg()) {
2333         case X86::XMM0: ShadowReg = X86::RCX; break;
2334         case X86::XMM1: ShadowReg = X86::RDX; break;
2335         case X86::XMM2: ShadowReg = X86::R8; break;
2336         case X86::XMM3: ShadowReg = X86::R9; break;
2337         }
2338         if (ShadowReg)
2339           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2340       }
2341     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2342       assert(VA.isMemLoc());
2343       if (StackPtr.getNode() == 0)
2344         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2345       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2346                                              dl, DAG, VA, Flags));
2347     }
2348   }
2349
2350   if (!MemOpChains.empty())
2351     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2352                         &MemOpChains[0], MemOpChains.size());
2353
2354   if (Subtarget->isPICStyleGOT()) {
2355     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2356     // GOT pointer.
2357     if (!isTailCall) {
2358       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2359                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2360     } else {
2361       // If we are tail calling and generating PIC/GOT style code load the
2362       // address of the callee into ECX. The value in ecx is used as target of
2363       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2364       // for tail calls on PIC/GOT architectures. Normally we would just put the
2365       // address of GOT into ebx and then call target@PLT. But for tail calls
2366       // ebx would be restored (since ebx is callee saved) before jumping to the
2367       // target@PLT.
2368
2369       // Note: The actual moving to ECX is done further down.
2370       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2371       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2372           !G->getGlobal()->hasProtectedVisibility())
2373         Callee = LowerGlobalAddress(Callee, DAG);
2374       else if (isa<ExternalSymbolSDNode>(Callee))
2375         Callee = LowerExternalSymbol(Callee, DAG);
2376     }
2377   }
2378
2379   if (Is64Bit && isVarArg && !IsWin64) {
2380     // From AMD64 ABI document:
2381     // For calls that may call functions that use varargs or stdargs
2382     // (prototype-less calls or calls to functions containing ellipsis (...) in
2383     // the declaration) %al is used as hidden argument to specify the number
2384     // of SSE registers used. The contents of %al do not need to match exactly
2385     // the number of registers, but must be an ubound on the number of SSE
2386     // registers used and is in the range 0 - 8 inclusive.
2387
2388     // Count the number of XMM registers allocated.
2389     static const uint16_t XMMArgRegs[] = {
2390       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2391       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2392     };
2393     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2394     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2395            && "SSE registers cannot be used when SSE is disabled");
2396
2397     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2398                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2399   }
2400
2401   // For tail calls lower the arguments to the 'real' stack slot.
2402   if (isTailCall) {
2403     // Force all the incoming stack arguments to be loaded from the stack
2404     // before any new outgoing arguments are stored to the stack, because the
2405     // outgoing stack slots may alias the incoming argument stack slots, and
2406     // the alias isn't otherwise explicit. This is slightly more conservative
2407     // than necessary, because it means that each store effectively depends
2408     // on every argument instead of just those arguments it would clobber.
2409     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2410
2411     SmallVector<SDValue, 8> MemOpChains2;
2412     SDValue FIN;
2413     int FI = 0;
2414     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2415       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416         CCValAssign &VA = ArgLocs[i];
2417         if (VA.isRegLoc())
2418           continue;
2419         assert(VA.isMemLoc());
2420         SDValue Arg = OutVals[i];
2421         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2422         // Create frame index.
2423         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2424         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2425         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2426         FIN = DAG.getFrameIndex(FI, getPointerTy());
2427
2428         if (Flags.isByVal()) {
2429           // Copy relative to framepointer.
2430           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2431           if (StackPtr.getNode() == 0)
2432             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2433                                           getPointerTy());
2434           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2435
2436           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2437                                                            ArgChain,
2438                                                            Flags, DAG, dl));
2439         } else {
2440           // Store relative to framepointer.
2441           MemOpChains2.push_back(
2442             DAG.getStore(ArgChain, dl, Arg, FIN,
2443                          MachinePointerInfo::getFixedStack(FI),
2444                          false, false, 0));
2445         }
2446       }
2447     }
2448
2449     if (!MemOpChains2.empty())
2450       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2451                           &MemOpChains2[0], MemOpChains2.size());
2452
2453     // Store the return address to the appropriate stack slot.
2454     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2455                                      FPDiff, dl);
2456   }
2457
2458   // Build a sequence of copy-to-reg nodes chained together with token chain
2459   // and flag operands which copy the outgoing args into registers.
2460   SDValue InFlag;
2461   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2462     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2463                              RegsToPass[i].second, InFlag);
2464     InFlag = Chain.getValue(1);
2465   }
2466
2467   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2468     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2469     // In the 64-bit large code model, we have to make all calls
2470     // through a register, since the call instruction's 32-bit
2471     // pc-relative offset may not be large enough to hold the whole
2472     // address.
2473   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2474     // If the callee is a GlobalAddress node (quite common, every direct call
2475     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2476     // it.
2477
2478     // We should use extra load for direct calls to dllimported functions in
2479     // non-JIT mode.
2480     const GlobalValue *GV = G->getGlobal();
2481     if (!GV->hasDLLImportLinkage()) {
2482       unsigned char OpFlags = 0;
2483       bool ExtraLoad = false;
2484       unsigned WrapperKind = ISD::DELETED_NODE;
2485
2486       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2487       // external symbols most go through the PLT in PIC mode.  If the symbol
2488       // has hidden or protected visibility, or if it is static or local, then
2489       // we don't need to use the PLT - we can directly call it.
2490       if (Subtarget->isTargetELF() &&
2491           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2492           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2493         OpFlags = X86II::MO_PLT;
2494       } else if (Subtarget->isPICStyleStubAny() &&
2495                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2496                  (!Subtarget->getTargetTriple().isMacOSX() ||
2497                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2498         // PC-relative references to external symbols should go through $stub,
2499         // unless we're building with the leopard linker or later, which
2500         // automatically synthesizes these stubs.
2501         OpFlags = X86II::MO_DARWIN_STUB;
2502       } else if (Subtarget->isPICStyleRIPRel() &&
2503                  isa<Function>(GV) &&
2504                  cast<Function>(GV)->getFnAttributes().
2505                    hasAttribute(Attributes::NonLazyBind)) {
2506         // If the function is marked as non-lazy, generate an indirect call
2507         // which loads from the GOT directly. This avoids runtime overhead
2508         // at the cost of eager binding (and one extra byte of encoding).
2509         OpFlags = X86II::MO_GOTPCREL;
2510         WrapperKind = X86ISD::WrapperRIP;
2511         ExtraLoad = true;
2512       }
2513
2514       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2515                                           G->getOffset(), OpFlags);
2516
2517       // Add a wrapper if needed.
2518       if (WrapperKind != ISD::DELETED_NODE)
2519         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2520       // Add extra indirection if needed.
2521       if (ExtraLoad)
2522         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2523                              MachinePointerInfo::getGOT(),
2524                              false, false, false, 0);
2525     }
2526   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2527     unsigned char OpFlags = 0;
2528
2529     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2530     // external symbols should go through the PLT.
2531     if (Subtarget->isTargetELF() &&
2532         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2533       OpFlags = X86II::MO_PLT;
2534     } else if (Subtarget->isPICStyleStubAny() &&
2535                (!Subtarget->getTargetTriple().isMacOSX() ||
2536                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537       // PC-relative references to external symbols should go through $stub,
2538       // unless we're building with the leopard linker or later, which
2539       // automatically synthesizes these stubs.
2540       OpFlags = X86II::MO_DARWIN_STUB;
2541     }
2542
2543     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2544                                          OpFlags);
2545   }
2546
2547   // Returns a chain & a flag for retval copy to use.
2548   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2549   SmallVector<SDValue, 8> Ops;
2550
2551   if (!IsSibcall && isTailCall) {
2552     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2553                            DAG.getIntPtrConstant(0, true), InFlag);
2554     InFlag = Chain.getValue(1);
2555   }
2556
2557   Ops.push_back(Chain);
2558   Ops.push_back(Callee);
2559
2560   if (isTailCall)
2561     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2562
2563   // Add argument registers to the end of the list so that they are known live
2564   // into the call.
2565   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2566     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2567                                   RegsToPass[i].second.getValueType()));
2568
2569   // Add a register mask operand representing the call-preserved registers.
2570   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2571   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2572   assert(Mask && "Missing call preserved mask for calling convention");
2573   Ops.push_back(DAG.getRegisterMask(Mask));
2574
2575   if (InFlag.getNode())
2576     Ops.push_back(InFlag);
2577
2578   if (isTailCall) {
2579     // We used to do:
2580     //// If this is the first return lowered for this function, add the regs
2581     //// to the liveout set for the function.
2582     // This isn't right, although it's probably harmless on x86; liveouts
2583     // should be computed from returns not tail calls.  Consider a void
2584     // function making a tail call to a function returning int.
2585     return DAG.getNode(X86ISD::TC_RETURN, dl,
2586                        NodeTys, &Ops[0], Ops.size());
2587   }
2588
2589   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2590   InFlag = Chain.getValue(1);
2591
2592   // Create the CALLSEQ_END node.
2593   unsigned NumBytesForCalleeToPush;
2594   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2595                        getTargetMachine().Options.GuaranteedTailCallOpt))
2596     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2597   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2598            SR == StackStructReturn)
2599     // If this is a call to a struct-return function, the callee
2600     // pops the hidden struct pointer, so we have to push it back.
2601     // This is common for Darwin/X86, Linux & Mingw32 targets.
2602     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2603     NumBytesForCalleeToPush = 4;
2604   else
2605     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2606
2607   // Returns a flag for retval copy to use.
2608   if (!IsSibcall) {
2609     Chain = DAG.getCALLSEQ_END(Chain,
2610                                DAG.getIntPtrConstant(NumBytes, true),
2611                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2612                                                      true),
2613                                InFlag);
2614     InFlag = Chain.getValue(1);
2615   }
2616
2617   // Handle result values, copying them out of physregs into vregs that we
2618   // return.
2619   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2620                          Ins, dl, DAG, InVals);
2621 }
2622
2623
2624 //===----------------------------------------------------------------------===//
2625 //                Fast Calling Convention (tail call) implementation
2626 //===----------------------------------------------------------------------===//
2627
2628 //  Like std call, callee cleans arguments, convention except that ECX is
2629 //  reserved for storing the tail called function address. Only 2 registers are
2630 //  free for argument passing (inreg). Tail call optimization is performed
2631 //  provided:
2632 //                * tailcallopt is enabled
2633 //                * caller/callee are fastcc
2634 //  On X86_64 architecture with GOT-style position independent code only local
2635 //  (within module) calls are supported at the moment.
2636 //  To keep the stack aligned according to platform abi the function
2637 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2638 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2639 //  If a tail called function callee has more arguments than the caller the
2640 //  caller needs to make sure that there is room to move the RETADDR to. This is
2641 //  achieved by reserving an area the size of the argument delta right after the
2642 //  original REtADDR, but before the saved framepointer or the spilled registers
2643 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2644 //  stack layout:
2645 //    arg1
2646 //    arg2
2647 //    RETADDR
2648 //    [ new RETADDR
2649 //      move area ]
2650 //    (possible EBP)
2651 //    ESI
2652 //    EDI
2653 //    local1 ..
2654
2655 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2656 /// for a 16 byte align requirement.
2657 unsigned
2658 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2659                                                SelectionDAG& DAG) const {
2660   MachineFunction &MF = DAG.getMachineFunction();
2661   const TargetMachine &TM = MF.getTarget();
2662   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2663   unsigned StackAlignment = TFI.getStackAlignment();
2664   uint64_t AlignMask = StackAlignment - 1;
2665   int64_t Offset = StackSize;
2666   uint64_t SlotSize = TD->getPointerSize(0);
2667   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2668     // Number smaller than 12 so just add the difference.
2669     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2670   } else {
2671     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2672     Offset = ((~AlignMask) & Offset) + StackAlignment +
2673       (StackAlignment-SlotSize);
2674   }
2675   return Offset;
2676 }
2677
2678 /// MatchingStackOffset - Return true if the given stack call argument is
2679 /// already available in the same position (relatively) of the caller's
2680 /// incoming argument stack.
2681 static
2682 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2683                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2684                          const X86InstrInfo *TII) {
2685   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2686   int FI = INT_MAX;
2687   if (Arg.getOpcode() == ISD::CopyFromReg) {
2688     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2689     if (!TargetRegisterInfo::isVirtualRegister(VR))
2690       return false;
2691     MachineInstr *Def = MRI->getVRegDef(VR);
2692     if (!Def)
2693       return false;
2694     if (!Flags.isByVal()) {
2695       if (!TII->isLoadFromStackSlot(Def, FI))
2696         return false;
2697     } else {
2698       unsigned Opcode = Def->getOpcode();
2699       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2700           Def->getOperand(1).isFI()) {
2701         FI = Def->getOperand(1).getIndex();
2702         Bytes = Flags.getByValSize();
2703       } else
2704         return false;
2705     }
2706   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2707     if (Flags.isByVal())
2708       // ByVal argument is passed in as a pointer but it's now being
2709       // dereferenced. e.g.
2710       // define @foo(%struct.X* %A) {
2711       //   tail call @bar(%struct.X* byval %A)
2712       // }
2713       return false;
2714     SDValue Ptr = Ld->getBasePtr();
2715     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2716     if (!FINode)
2717       return false;
2718     FI = FINode->getIndex();
2719   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2720     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2721     FI = FINode->getIndex();
2722     Bytes = Flags.getByValSize();
2723   } else
2724     return false;
2725
2726   assert(FI != INT_MAX);
2727   if (!MFI->isFixedObjectIndex(FI))
2728     return false;
2729   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2730 }
2731
2732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2733 /// for tail call optimization. Targets which want to do tail call
2734 /// optimization should implement this function.
2735 bool
2736 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2737                                                      CallingConv::ID CalleeCC,
2738                                                      bool isVarArg,
2739                                                      bool isCalleeStructRet,
2740                                                      bool isCallerStructRet,
2741                                                      Type *RetTy,
2742                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2743                                     const SmallVectorImpl<SDValue> &OutVals,
2744                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2745                                                      SelectionDAG& DAG) const {
2746   if (!IsTailCallConvention(CalleeCC) &&
2747       CalleeCC != CallingConv::C)
2748     return false;
2749
2750   // If -tailcallopt is specified, make fastcc functions tail-callable.
2751   const MachineFunction &MF = DAG.getMachineFunction();
2752   const Function *CallerF = DAG.getMachineFunction().getFunction();
2753
2754   // If the function return type is x86_fp80 and the callee return type is not,
2755   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2756   // perform a tailcall optimization here.
2757   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2758     return false;
2759
2760   CallingConv::ID CallerCC = CallerF->getCallingConv();
2761   bool CCMatch = CallerCC == CalleeCC;
2762
2763   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2764     if (IsTailCallConvention(CalleeCC) && CCMatch)
2765       return true;
2766     return false;
2767   }
2768
2769   // Look for obvious safe cases to perform tail call optimization that do not
2770   // require ABI changes. This is what gcc calls sibcall.
2771
2772   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2773   // emit a special epilogue.
2774   if (RegInfo->needsStackRealignment(MF))
2775     return false;
2776
2777   // Also avoid sibcall optimization if either caller or callee uses struct
2778   // return semantics.
2779   if (isCalleeStructRet || isCallerStructRet)
2780     return false;
2781
2782   // An stdcall caller is expected to clean up its arguments; the callee
2783   // isn't going to do that.
2784   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2785     return false;
2786
2787   // Do not sibcall optimize vararg calls unless all arguments are passed via
2788   // registers.
2789   if (isVarArg && !Outs.empty()) {
2790
2791     // Optimizing for varargs on Win64 is unlikely to be safe without
2792     // additional testing.
2793     if (Subtarget->isTargetWin64())
2794       return false;
2795
2796     SmallVector<CCValAssign, 16> ArgLocs;
2797     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2798                    getTargetMachine(), ArgLocs, *DAG.getContext());
2799
2800     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2802       if (!ArgLocs[i].isRegLoc())
2803         return false;
2804   }
2805
2806   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2807   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2808   // this into a sibcall.
2809   bool Unused = false;
2810   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2811     if (!Ins[i].Used) {
2812       Unused = true;
2813       break;
2814     }
2815   }
2816   if (Unused) {
2817     SmallVector<CCValAssign, 16> RVLocs;
2818     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2819                    getTargetMachine(), RVLocs, *DAG.getContext());
2820     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2821     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2822       CCValAssign &VA = RVLocs[i];
2823       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2824         return false;
2825     }
2826   }
2827
2828   // If the calling conventions do not match, then we'd better make sure the
2829   // results are returned in the same way as what the caller expects.
2830   if (!CCMatch) {
2831     SmallVector<CCValAssign, 16> RVLocs1;
2832     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2833                     getTargetMachine(), RVLocs1, *DAG.getContext());
2834     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2835
2836     SmallVector<CCValAssign, 16> RVLocs2;
2837     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2838                     getTargetMachine(), RVLocs2, *DAG.getContext());
2839     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2840
2841     if (RVLocs1.size() != RVLocs2.size())
2842       return false;
2843     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2844       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2845         return false;
2846       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2847         return false;
2848       if (RVLocs1[i].isRegLoc()) {
2849         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2850           return false;
2851       } else {
2852         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2853           return false;
2854       }
2855     }
2856   }
2857
2858   // If the callee takes no arguments then go on to check the results of the
2859   // call.
2860   if (!Outs.empty()) {
2861     // Check if stack adjustment is needed. For now, do not do this if any
2862     // argument is passed on the stack.
2863     SmallVector<CCValAssign, 16> ArgLocs;
2864     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2865                    getTargetMachine(), ArgLocs, *DAG.getContext());
2866
2867     // Allocate shadow area for Win64
2868     if (Subtarget->isTargetWin64()) {
2869       CCInfo.AllocateStack(32, 8);
2870     }
2871
2872     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2873     if (CCInfo.getNextStackOffset()) {
2874       MachineFunction &MF = DAG.getMachineFunction();
2875       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2876         return false;
2877
2878       // Check if the arguments are already laid out in the right way as
2879       // the caller's fixed stack objects.
2880       MachineFrameInfo *MFI = MF.getFrameInfo();
2881       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2882       const X86InstrInfo *TII =
2883         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2884       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2885         CCValAssign &VA = ArgLocs[i];
2886         SDValue Arg = OutVals[i];
2887         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888         if (VA.getLocInfo() == CCValAssign::Indirect)
2889           return false;
2890         if (!VA.isRegLoc()) {
2891           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2892                                    MFI, MRI, TII))
2893             return false;
2894         }
2895       }
2896     }
2897
2898     // If the tailcall address may be in a register, then make sure it's
2899     // possible to register allocate for it. In 32-bit, the call address can
2900     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2901     // callee-saved registers are restored. These happen to be the same
2902     // registers used to pass 'inreg' arguments so watch out for those.
2903     if (!Subtarget->is64Bit() &&
2904         !isa<GlobalAddressSDNode>(Callee) &&
2905         !isa<ExternalSymbolSDNode>(Callee)) {
2906       unsigned NumInRegs = 0;
2907       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2908         CCValAssign &VA = ArgLocs[i];
2909         if (!VA.isRegLoc())
2910           continue;
2911         unsigned Reg = VA.getLocReg();
2912         switch (Reg) {
2913         default: break;
2914         case X86::EAX: case X86::EDX: case X86::ECX:
2915           if (++NumInRegs == 3)
2916             return false;
2917           break;
2918         }
2919       }
2920     }
2921   }
2922
2923   return true;
2924 }
2925
2926 FastISel *
2927 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2928                                   const TargetLibraryInfo *libInfo) const {
2929   return X86::createFastISel(funcInfo, libInfo);
2930 }
2931
2932
2933 //===----------------------------------------------------------------------===//
2934 //                           Other Lowering Hooks
2935 //===----------------------------------------------------------------------===//
2936
2937 static bool MayFoldLoad(SDValue Op) {
2938   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2939 }
2940
2941 static bool MayFoldIntoStore(SDValue Op) {
2942   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2943 }
2944
2945 static bool isTargetShuffle(unsigned Opcode) {
2946   switch(Opcode) {
2947   default: return false;
2948   case X86ISD::PSHUFD:
2949   case X86ISD::PSHUFHW:
2950   case X86ISD::PSHUFLW:
2951   case X86ISD::SHUFP:
2952   case X86ISD::PALIGN:
2953   case X86ISD::MOVLHPS:
2954   case X86ISD::MOVLHPD:
2955   case X86ISD::MOVHLPS:
2956   case X86ISD::MOVLPS:
2957   case X86ISD::MOVLPD:
2958   case X86ISD::MOVSHDUP:
2959   case X86ISD::MOVSLDUP:
2960   case X86ISD::MOVDDUP:
2961   case X86ISD::MOVSS:
2962   case X86ISD::MOVSD:
2963   case X86ISD::UNPCKL:
2964   case X86ISD::UNPCKH:
2965   case X86ISD::VPERMILP:
2966   case X86ISD::VPERM2X128:
2967   case X86ISD::VPERMI:
2968     return true;
2969   }
2970 }
2971
2972 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2973                                     SDValue V1, SelectionDAG &DAG) {
2974   switch(Opc) {
2975   default: llvm_unreachable("Unknown x86 shuffle node");
2976   case X86ISD::MOVSHDUP:
2977   case X86ISD::MOVSLDUP:
2978   case X86ISD::MOVDDUP:
2979     return DAG.getNode(Opc, dl, VT, V1);
2980   }
2981 }
2982
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984                                     SDValue V1, unsigned TargetMask,
2985                                     SelectionDAG &DAG) {
2986   switch(Opc) {
2987   default: llvm_unreachable("Unknown x86 shuffle node");
2988   case X86ISD::PSHUFD:
2989   case X86ISD::PSHUFHW:
2990   case X86ISD::PSHUFLW:
2991   case X86ISD::VPERMILP:
2992   case X86ISD::VPERMI:
2993     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2994   }
2995 }
2996
2997 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2998                                     SDValue V1, SDValue V2, unsigned TargetMask,
2999                                     SelectionDAG &DAG) {
3000   switch(Opc) {
3001   default: llvm_unreachable("Unknown x86 shuffle node");
3002   case X86ISD::PALIGN:
3003   case X86ISD::SHUFP:
3004   case X86ISD::VPERM2X128:
3005     return DAG.getNode(Opc, dl, VT, V1, V2,
3006                        DAG.getConstant(TargetMask, MVT::i8));
3007   }
3008 }
3009
3010 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3011                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3012   switch(Opc) {
3013   default: llvm_unreachable("Unknown x86 shuffle node");
3014   case X86ISD::MOVLHPS:
3015   case X86ISD::MOVLHPD:
3016   case X86ISD::MOVHLPS:
3017   case X86ISD::MOVLPS:
3018   case X86ISD::MOVLPD:
3019   case X86ISD::MOVSS:
3020   case X86ISD::MOVSD:
3021   case X86ISD::UNPCKL:
3022   case X86ISD::UNPCKH:
3023     return DAG.getNode(Opc, dl, VT, V1, V2);
3024   }
3025 }
3026
3027 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3028   MachineFunction &MF = DAG.getMachineFunction();
3029   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3030   int ReturnAddrIndex = FuncInfo->getRAIndex();
3031
3032   if (ReturnAddrIndex == 0) {
3033     // Set up a frame object for the return address.
3034     uint64_t SlotSize = TD->getPointerSize(0);
3035     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3036                                                            false);
3037     FuncInfo->setRAIndex(ReturnAddrIndex);
3038   }
3039
3040   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3041 }
3042
3043
3044 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3045                                        bool hasSymbolicDisplacement) {
3046   // Offset should fit into 32 bit immediate field.
3047   if (!isInt<32>(Offset))
3048     return false;
3049
3050   // If we don't have a symbolic displacement - we don't have any extra
3051   // restrictions.
3052   if (!hasSymbolicDisplacement)
3053     return true;
3054
3055   // FIXME: Some tweaks might be needed for medium code model.
3056   if (M != CodeModel::Small && M != CodeModel::Kernel)
3057     return false;
3058
3059   // For small code model we assume that latest object is 16MB before end of 31
3060   // bits boundary. We may also accept pretty large negative constants knowing
3061   // that all objects are in the positive half of address space.
3062   if (M == CodeModel::Small && Offset < 16*1024*1024)
3063     return true;
3064
3065   // For kernel code model we know that all object resist in the negative half
3066   // of 32bits address space. We may not accept negative offsets, since they may
3067   // be just off and we may accept pretty large positive ones.
3068   if (M == CodeModel::Kernel && Offset > 0)
3069     return true;
3070
3071   return false;
3072 }
3073
3074 /// isCalleePop - Determines whether the callee is required to pop its
3075 /// own arguments. Callee pop is necessary to support tail calls.
3076 bool X86::isCalleePop(CallingConv::ID CallingConv,
3077                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3078   if (IsVarArg)
3079     return false;
3080
3081   switch (CallingConv) {
3082   default:
3083     return false;
3084   case CallingConv::X86_StdCall:
3085     return !is64Bit;
3086   case CallingConv::X86_FastCall:
3087     return !is64Bit;
3088   case CallingConv::X86_ThisCall:
3089     return !is64Bit;
3090   case CallingConv::Fast:
3091     return TailCallOpt;
3092   case CallingConv::GHC:
3093     return TailCallOpt;
3094   }
3095 }
3096
3097 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3098 /// specific condition code, returning the condition code and the LHS/RHS of the
3099 /// comparison to make.
3100 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3101                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3102   if (!isFP) {
3103     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3104       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3105         // X > -1   -> X == 0, jump !sign.
3106         RHS = DAG.getConstant(0, RHS.getValueType());
3107         return X86::COND_NS;
3108       }
3109       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3110         // X < 0   -> X == 0, jump on sign.
3111         return X86::COND_S;
3112       }
3113       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3114         // X < 1   -> X <= 0
3115         RHS = DAG.getConstant(0, RHS.getValueType());
3116         return X86::COND_LE;
3117       }
3118     }
3119
3120     switch (SetCCOpcode) {
3121     default: llvm_unreachable("Invalid integer condition!");
3122     case ISD::SETEQ:  return X86::COND_E;
3123     case ISD::SETGT:  return X86::COND_G;
3124     case ISD::SETGE:  return X86::COND_GE;
3125     case ISD::SETLT:  return X86::COND_L;
3126     case ISD::SETLE:  return X86::COND_LE;
3127     case ISD::SETNE:  return X86::COND_NE;
3128     case ISD::SETULT: return X86::COND_B;
3129     case ISD::SETUGT: return X86::COND_A;
3130     case ISD::SETULE: return X86::COND_BE;
3131     case ISD::SETUGE: return X86::COND_AE;
3132     }
3133   }
3134
3135   // First determine if it is required or is profitable to flip the operands.
3136
3137   // If LHS is a foldable load, but RHS is not, flip the condition.
3138   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3139       !ISD::isNON_EXTLoad(RHS.getNode())) {
3140     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3141     std::swap(LHS, RHS);
3142   }
3143
3144   switch (SetCCOpcode) {
3145   default: break;
3146   case ISD::SETOLT:
3147   case ISD::SETOLE:
3148   case ISD::SETUGT:
3149   case ISD::SETUGE:
3150     std::swap(LHS, RHS);
3151     break;
3152   }
3153
3154   // On a floating point condition, the flags are set as follows:
3155   // ZF  PF  CF   op
3156   //  0 | 0 | 0 | X > Y
3157   //  0 | 0 | 1 | X < Y
3158   //  1 | 0 | 0 | X == Y
3159   //  1 | 1 | 1 | unordered
3160   switch (SetCCOpcode) {
3161   default: llvm_unreachable("Condcode should be pre-legalized away");
3162   case ISD::SETUEQ:
3163   case ISD::SETEQ:   return X86::COND_E;
3164   case ISD::SETOLT:              // flipped
3165   case ISD::SETOGT:
3166   case ISD::SETGT:   return X86::COND_A;
3167   case ISD::SETOLE:              // flipped
3168   case ISD::SETOGE:
3169   case ISD::SETGE:   return X86::COND_AE;
3170   case ISD::SETUGT:              // flipped
3171   case ISD::SETULT:
3172   case ISD::SETLT:   return X86::COND_B;
3173   case ISD::SETUGE:              // flipped
3174   case ISD::SETULE:
3175   case ISD::SETLE:   return X86::COND_BE;
3176   case ISD::SETONE:
3177   case ISD::SETNE:   return X86::COND_NE;
3178   case ISD::SETUO:   return X86::COND_P;
3179   case ISD::SETO:    return X86::COND_NP;
3180   case ISD::SETOEQ:
3181   case ISD::SETUNE:  return X86::COND_INVALID;
3182   }
3183 }
3184
3185 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3186 /// code. Current x86 isa includes the following FP cmov instructions:
3187 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3188 static bool hasFPCMov(unsigned X86CC) {
3189   switch (X86CC) {
3190   default:
3191     return false;
3192   case X86::COND_B:
3193   case X86::COND_BE:
3194   case X86::COND_E:
3195   case X86::COND_P:
3196   case X86::COND_A:
3197   case X86::COND_AE:
3198   case X86::COND_NE:
3199   case X86::COND_NP:
3200     return true;
3201   }
3202 }
3203
3204 /// isFPImmLegal - Returns true if the target can instruction select the
3205 /// specified FP immediate natively. If false, the legalizer will
3206 /// materialize the FP immediate as a load from a constant pool.
3207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3208   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3209     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3210       return true;
3211   }
3212   return false;
3213 }
3214
3215 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3216 /// the specified range (L, H].
3217 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3218   return (Val < 0) || (Val >= Low && Val < Hi);
3219 }
3220
3221 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3222 /// specified value.
3223 static bool isUndefOrEqual(int Val, int CmpVal) {
3224   if (Val < 0 || Val == CmpVal)
3225     return true;
3226   return false;
3227 }
3228
3229 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3230 /// from position Pos and ending in Pos+Size, falls within the specified
3231 /// sequential range (L, L+Pos]. or is undef.
3232 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3233                                        unsigned Pos, unsigned Size, int Low) {
3234   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3235     if (!isUndefOrEqual(Mask[i], Low))
3236       return false;
3237   return true;
3238 }
3239
3240 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3241 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3242 /// the second operand.
3243 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3244   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3245     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3246   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3247     return (Mask[0] < 2 && Mask[1] < 2);
3248   return false;
3249 }
3250
3251 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3252 /// is suitable for input to PSHUFHW.
3253 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3254   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3255     return false;
3256
3257   // Lower quadword copied in order or undef.
3258   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3259     return false;
3260
3261   // Upper quadword shuffled.
3262   for (unsigned i = 4; i != 8; ++i)
3263     if (!isUndefOrInRange(Mask[i], 4, 8))
3264       return false;
3265
3266   if (VT == MVT::v16i16) {
3267     // Lower quadword copied in order or undef.
3268     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3269       return false;
3270
3271     // Upper quadword shuffled.
3272     for (unsigned i = 12; i != 16; ++i)
3273       if (!isUndefOrInRange(Mask[i], 12, 16))
3274         return false;
3275   }
3276
3277   return true;
3278 }
3279
3280 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3281 /// is suitable for input to PSHUFLW.
3282 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3283   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3284     return false;
3285
3286   // Upper quadword copied in order.
3287   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3288     return false;
3289
3290   // Lower quadword shuffled.
3291   for (unsigned i = 0; i != 4; ++i)
3292     if (!isUndefOrInRange(Mask[i], 0, 4))
3293       return false;
3294
3295   if (VT == MVT::v16i16) {
3296     // Upper quadword copied in order.
3297     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3298       return false;
3299
3300     // Lower quadword shuffled.
3301     for (unsigned i = 8; i != 12; ++i)
3302       if (!isUndefOrInRange(Mask[i], 8, 12))
3303         return false;
3304   }
3305
3306   return true;
3307 }
3308
3309 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3310 /// is suitable for input to PALIGNR.
3311 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3312                           const X86Subtarget *Subtarget) {
3313   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3314       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3315     return false;
3316
3317   unsigned NumElts = VT.getVectorNumElements();
3318   unsigned NumLanes = VT.getSizeInBits()/128;
3319   unsigned NumLaneElts = NumElts/NumLanes;
3320
3321   // Do not handle 64-bit element shuffles with palignr.
3322   if (NumLaneElts == 2)
3323     return false;
3324
3325   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3326     unsigned i;
3327     for (i = 0; i != NumLaneElts; ++i) {
3328       if (Mask[i+l] >= 0)
3329         break;
3330     }
3331
3332     // Lane is all undef, go to next lane
3333     if (i == NumLaneElts)
3334       continue;
3335
3336     int Start = Mask[i+l];
3337
3338     // Make sure its in this lane in one of the sources
3339     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3340         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3341       return false;
3342
3343     // If not lane 0, then we must match lane 0
3344     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3345       return false;
3346
3347     // Correct second source to be contiguous with first source
3348     if (Start >= (int)NumElts)
3349       Start -= NumElts - NumLaneElts;
3350
3351     // Make sure we're shifting in the right direction.
3352     if (Start <= (int)(i+l))
3353       return false;
3354
3355     Start -= i;
3356
3357     // Check the rest of the elements to see if they are consecutive.
3358     for (++i; i != NumLaneElts; ++i) {
3359       int Idx = Mask[i+l];
3360
3361       // Make sure its in this lane
3362       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3363           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3364         return false;
3365
3366       // If not lane 0, then we must match lane 0
3367       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3368         return false;
3369
3370       if (Idx >= (int)NumElts)
3371         Idx -= NumElts - NumLaneElts;
3372
3373       if (!isUndefOrEqual(Idx, Start+i))
3374         return false;
3375
3376     }
3377   }
3378
3379   return true;
3380 }
3381
3382 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3383 /// the two vector operands have swapped position.
3384 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3385                                      unsigned NumElems) {
3386   for (unsigned i = 0; i != NumElems; ++i) {
3387     int idx = Mask[i];
3388     if (idx < 0)
3389       continue;
3390     else if (idx < (int)NumElems)
3391       Mask[i] = idx + NumElems;
3392     else
3393       Mask[i] = idx - NumElems;
3394   }
3395 }
3396
3397 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3398 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3399 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3400 /// reverse of what x86 shuffles want.
3401 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3402                         bool Commuted = false) {
3403   if (!HasAVX && VT.getSizeInBits() == 256)
3404     return false;
3405
3406   unsigned NumElems = VT.getVectorNumElements();
3407   unsigned NumLanes = VT.getSizeInBits()/128;
3408   unsigned NumLaneElems = NumElems/NumLanes;
3409
3410   if (NumLaneElems != 2 && NumLaneElems != 4)
3411     return false;
3412
3413   // VSHUFPSY divides the resulting vector into 4 chunks.
3414   // The sources are also splitted into 4 chunks, and each destination
3415   // chunk must come from a different source chunk.
3416   //
3417   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3418   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3419   //
3420   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3421   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3422   //
3423   // VSHUFPDY divides the resulting vector into 4 chunks.
3424   // The sources are also splitted into 4 chunks, and each destination
3425   // chunk must come from a different source chunk.
3426   //
3427   //  SRC1 =>      X3       X2       X1       X0
3428   //  SRC2 =>      Y3       Y2       Y1       Y0
3429   //
3430   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3431   //
3432   unsigned HalfLaneElems = NumLaneElems/2;
3433   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3434     for (unsigned i = 0; i != NumLaneElems; ++i) {
3435       int Idx = Mask[i+l];
3436       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3437       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3438         return false;
3439       // For VSHUFPSY, the mask of the second half must be the same as the
3440       // first but with the appropriate offsets. This works in the same way as
3441       // VPERMILPS works with masks.
3442       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3443         continue;
3444       if (!isUndefOrEqual(Idx, Mask[i]+l))
3445         return false;
3446     }
3447   }
3448
3449   return true;
3450 }
3451
3452 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3453 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3454 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3455   if (!VT.is128BitVector())
3456     return false;
3457
3458   unsigned NumElems = VT.getVectorNumElements();
3459
3460   if (NumElems != 4)
3461     return false;
3462
3463   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3464   return isUndefOrEqual(Mask[0], 6) &&
3465          isUndefOrEqual(Mask[1], 7) &&
3466          isUndefOrEqual(Mask[2], 2) &&
3467          isUndefOrEqual(Mask[3], 3);
3468 }
3469
3470 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3471 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3472 /// <2, 3, 2, 3>
3473 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3474   if (!VT.is128BitVector())
3475     return false;
3476
3477   unsigned NumElems = VT.getVectorNumElements();
3478
3479   if (NumElems != 4)
3480     return false;
3481
3482   return isUndefOrEqual(Mask[0], 2) &&
3483          isUndefOrEqual(Mask[1], 3) &&
3484          isUndefOrEqual(Mask[2], 2) &&
3485          isUndefOrEqual(Mask[3], 3);
3486 }
3487
3488 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3490 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3491   if (!VT.is128BitVector())
3492     return false;
3493
3494   unsigned NumElems = VT.getVectorNumElements();
3495
3496   if (NumElems != 2 && NumElems != 4)
3497     return false;
3498
3499   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3500     if (!isUndefOrEqual(Mask[i], i + NumElems))
3501       return false;
3502
3503   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3504     if (!isUndefOrEqual(Mask[i], i))
3505       return false;
3506
3507   return true;
3508 }
3509
3510 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3511 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3512 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3513   if (!VT.is128BitVector())
3514     return false;
3515
3516   unsigned NumElems = VT.getVectorNumElements();
3517
3518   if (NumElems != 2 && NumElems != 4)
3519     return false;
3520
3521   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3522     if (!isUndefOrEqual(Mask[i], i))
3523       return false;
3524
3525   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3526     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3527       return false;
3528
3529   return true;
3530 }
3531
3532 //
3533 // Some special combinations that can be optimized.
3534 //
3535 static
3536 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3537                                SelectionDAG &DAG) {
3538   EVT VT = SVOp->getValueType(0);
3539   DebugLoc dl = SVOp->getDebugLoc();
3540
3541   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3542     return SDValue();
3543
3544   ArrayRef<int> Mask = SVOp->getMask();
3545
3546   // These are the special masks that may be optimized.
3547   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3548   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3549   bool MatchEvenMask = true;
3550   bool MatchOddMask  = true;
3551   for (int i=0; i<8; ++i) {
3552     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3553       MatchEvenMask = false;
3554     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3555       MatchOddMask = false;
3556   }
3557
3558   if (!MatchEvenMask && !MatchOddMask)
3559     return SDValue();
3560
3561   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3562
3563   SDValue Op0 = SVOp->getOperand(0);
3564   SDValue Op1 = SVOp->getOperand(1);
3565
3566   if (MatchEvenMask) {
3567     // Shift the second operand right to 32 bits.
3568     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3569     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3570   } else {
3571     // Shift the first operand left to 32 bits.
3572     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3573     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3574   }
3575   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3576   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3577 }
3578
3579 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3580 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3581 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3582                          bool HasAVX2, bool V2IsSplat = false) {
3583   unsigned NumElts = VT.getVectorNumElements();
3584
3585   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586          "Unsupported vector type for unpckh");
3587
3588   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3590     return false;
3591
3592   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593   // independently on 128-bit lanes.
3594   unsigned NumLanes = VT.getSizeInBits()/128;
3595   unsigned NumLaneElts = NumElts/NumLanes;
3596
3597   for (unsigned l = 0; l != NumLanes; ++l) {
3598     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3599          i != (l+1)*NumLaneElts;
3600          i += 2, ++j) {
3601       int BitI  = Mask[i];
3602       int BitI1 = Mask[i+1];
3603       if (!isUndefOrEqual(BitI, j))
3604         return false;
3605       if (V2IsSplat) {
3606         if (!isUndefOrEqual(BitI1, NumElts))
3607           return false;
3608       } else {
3609         if (!isUndefOrEqual(BitI1, j + NumElts))
3610           return false;
3611       }
3612     }
3613   }
3614
3615   return true;
3616 }
3617
3618 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3619 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3620 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3621                          bool HasAVX2, bool V2IsSplat = false) {
3622   unsigned NumElts = VT.getVectorNumElements();
3623
3624   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3625          "Unsupported vector type for unpckh");
3626
3627   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3628       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3629     return false;
3630
3631   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3632   // independently on 128-bit lanes.
3633   unsigned NumLanes = VT.getSizeInBits()/128;
3634   unsigned NumLaneElts = NumElts/NumLanes;
3635
3636   for (unsigned l = 0; l != NumLanes; ++l) {
3637     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3638          i != (l+1)*NumLaneElts; i += 2, ++j) {
3639       int BitI  = Mask[i];
3640       int BitI1 = Mask[i+1];
3641       if (!isUndefOrEqual(BitI, j))
3642         return false;
3643       if (V2IsSplat) {
3644         if (isUndefOrEqual(BitI1, NumElts))
3645           return false;
3646       } else {
3647         if (!isUndefOrEqual(BitI1, j+NumElts))
3648           return false;
3649       }
3650     }
3651   }
3652   return true;
3653 }
3654
3655 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3656 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3657 /// <0, 0, 1, 1>
3658 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3659                                   bool HasAVX2) {
3660   unsigned NumElts = VT.getVectorNumElements();
3661
3662   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3663          "Unsupported vector type for unpckh");
3664
3665   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3666       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3667     return false;
3668
3669   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3670   // FIXME: Need a better way to get rid of this, there's no latency difference
3671   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3672   // the former later. We should also remove the "_undef" special mask.
3673   if (NumElts == 4 && VT.getSizeInBits() == 256)
3674     return false;
3675
3676   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3677   // independently on 128-bit lanes.
3678   unsigned NumLanes = VT.getSizeInBits()/128;
3679   unsigned NumLaneElts = NumElts/NumLanes;
3680
3681   for (unsigned l = 0; l != NumLanes; ++l) {
3682     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3683          i != (l+1)*NumLaneElts;
3684          i += 2, ++j) {
3685       int BitI  = Mask[i];
3686       int BitI1 = Mask[i+1];
3687
3688       if (!isUndefOrEqual(BitI, j))
3689         return false;
3690       if (!isUndefOrEqual(BitI1, j))
3691         return false;
3692     }
3693   }
3694
3695   return true;
3696 }
3697
3698 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3699 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3700 /// <2, 2, 3, 3>
3701 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3702   unsigned NumElts = VT.getVectorNumElements();
3703
3704   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3705          "Unsupported vector type for unpckh");
3706
3707   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3708       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3709     return false;
3710
3711   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3712   // independently on 128-bit lanes.
3713   unsigned NumLanes = VT.getSizeInBits()/128;
3714   unsigned NumLaneElts = NumElts/NumLanes;
3715
3716   for (unsigned l = 0; l != NumLanes; ++l) {
3717     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3718          i != (l+1)*NumLaneElts; i += 2, ++j) {
3719       int BitI  = Mask[i];
3720       int BitI1 = Mask[i+1];
3721       if (!isUndefOrEqual(BitI, j))
3722         return false;
3723       if (!isUndefOrEqual(BitI1, j))
3724         return false;
3725     }
3726   }
3727   return true;
3728 }
3729
3730 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3731 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3732 /// MOVSD, and MOVD, i.e. setting the lowest element.
3733 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3734   if (VT.getVectorElementType().getSizeInBits() < 32)
3735     return false;
3736   if (!VT.is128BitVector())
3737     return false;
3738
3739   unsigned NumElts = VT.getVectorNumElements();
3740
3741   if (!isUndefOrEqual(Mask[0], NumElts))
3742     return false;
3743
3744   for (unsigned i = 1; i != NumElts; ++i)
3745     if (!isUndefOrEqual(Mask[i], i))
3746       return false;
3747
3748   return true;
3749 }
3750
3751 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3752 /// as permutations between 128-bit chunks or halves. As an example: this
3753 /// shuffle bellow:
3754 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3755 /// The first half comes from the second half of V1 and the second half from the
3756 /// the second half of V2.
3757 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3758   if (!HasAVX || !VT.is256BitVector())
3759     return false;
3760
3761   // The shuffle result is divided into half A and half B. In total the two
3762   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3763   // B must come from C, D, E or F.
3764   unsigned HalfSize = VT.getVectorNumElements()/2;
3765   bool MatchA = false, MatchB = false;
3766
3767   // Check if A comes from one of C, D, E, F.
3768   for (unsigned Half = 0; Half != 4; ++Half) {
3769     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3770       MatchA = true;
3771       break;
3772     }
3773   }
3774
3775   // Check if B comes from one of C, D, E, F.
3776   for (unsigned Half = 0; Half != 4; ++Half) {
3777     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3778       MatchB = true;
3779       break;
3780     }
3781   }
3782
3783   return MatchA && MatchB;
3784 }
3785
3786 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3787 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3788 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3789   EVT VT = SVOp->getValueType(0);
3790
3791   unsigned HalfSize = VT.getVectorNumElements()/2;
3792
3793   unsigned FstHalf = 0, SndHalf = 0;
3794   for (unsigned i = 0; i < HalfSize; ++i) {
3795     if (SVOp->getMaskElt(i) > 0) {
3796       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3797       break;
3798     }
3799   }
3800   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3801     if (SVOp->getMaskElt(i) > 0) {
3802       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3803       break;
3804     }
3805   }
3806
3807   return (FstHalf | (SndHalf << 4));
3808 }
3809
3810 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3812 /// Note that VPERMIL mask matching is different depending whether theunderlying
3813 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3814 /// to the same elements of the low, but to the higher half of the source.
3815 /// In VPERMILPD the two lanes could be shuffled independently of each other
3816 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3817 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3818   if (!HasAVX)
3819     return false;
3820
3821   unsigned NumElts = VT.getVectorNumElements();
3822   // Only match 256-bit with 32/64-bit types
3823   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3824     return false;
3825
3826   unsigned NumLanes = VT.getSizeInBits()/128;
3827   unsigned LaneSize = NumElts/NumLanes;
3828   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3829     for (unsigned i = 0; i != LaneSize; ++i) {
3830       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3831         return false;
3832       if (NumElts != 8 || l == 0)
3833         continue;
3834       // VPERMILPS handling
3835       if (Mask[i] < 0)
3836         continue;
3837       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3838         return false;
3839     }
3840   }
3841
3842   return true;
3843 }
3844
3845 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3846 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3847 /// element of vector 2 and the other elements to come from vector 1 in order.
3848 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3849                                bool V2IsSplat = false, bool V2IsUndef = false) {
3850   if (!VT.is128BitVector())
3851     return false;
3852
3853   unsigned NumOps = VT.getVectorNumElements();
3854   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3855     return false;
3856
3857   if (!isUndefOrEqual(Mask[0], 0))
3858     return false;
3859
3860   for (unsigned i = 1; i != NumOps; ++i)
3861     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3862           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3863           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3864       return false;
3865
3866   return true;
3867 }
3868
3869 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3870 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3871 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3872 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3873                            const X86Subtarget *Subtarget) {
3874   if (!Subtarget->hasSSE3())
3875     return false;
3876
3877   unsigned NumElems = VT.getVectorNumElements();
3878
3879   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3880       (VT.getSizeInBits() == 256 && NumElems != 8))
3881     return false;
3882
3883   // "i+1" is the value the indexed mask element must have
3884   for (unsigned i = 0; i != NumElems; i += 2)
3885     if (!isUndefOrEqual(Mask[i], i+1) ||
3886         !isUndefOrEqual(Mask[i+1], i+1))
3887       return false;
3888
3889   return true;
3890 }
3891
3892 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3894 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3895 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3896                            const X86Subtarget *Subtarget) {
3897   if (!Subtarget->hasSSE3())
3898     return false;
3899
3900   unsigned NumElems = VT.getVectorNumElements();
3901
3902   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3903       (VT.getSizeInBits() == 256 && NumElems != 8))
3904     return false;
3905
3906   // "i" is the value the indexed mask element must have
3907   for (unsigned i = 0; i != NumElems; i += 2)
3908     if (!isUndefOrEqual(Mask[i], i) ||
3909         !isUndefOrEqual(Mask[i+1], i))
3910       return false;
3911
3912   return true;
3913 }
3914
3915 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to 256-bit
3917 /// version of MOVDDUP.
3918 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3919   if (!HasAVX || !VT.is256BitVector())
3920     return false;
3921
3922   unsigned NumElts = VT.getVectorNumElements();
3923   if (NumElts != 4)
3924     return false;
3925
3926   for (unsigned i = 0; i != NumElts/2; ++i)
3927     if (!isUndefOrEqual(Mask[i], 0))
3928       return false;
3929   for (unsigned i = NumElts/2; i != NumElts; ++i)
3930     if (!isUndefOrEqual(Mask[i], NumElts/2))
3931       return false;
3932   return true;
3933 }
3934
3935 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to 128-bit
3937 /// version of MOVDDUP.
3938 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3939   if (!VT.is128BitVector())
3940     return false;
3941
3942   unsigned e = VT.getVectorNumElements() / 2;
3943   for (unsigned i = 0; i != e; ++i)
3944     if (!isUndefOrEqual(Mask[i], i))
3945       return false;
3946   for (unsigned i = 0; i != e; ++i)
3947     if (!isUndefOrEqual(Mask[e+i], i))
3948       return false;
3949   return true;
3950 }
3951
3952 /// isVEXTRACTF128Index - Return true if the specified
3953 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3954 /// suitable for input to VEXTRACTF128.
3955 bool X86::isVEXTRACTF128Index(SDNode *N) {
3956   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3957     return false;
3958
3959   // The index should be aligned on a 128-bit boundary.
3960   uint64_t Index =
3961     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3962
3963   unsigned VL = N->getValueType(0).getVectorNumElements();
3964   unsigned VBits = N->getValueType(0).getSizeInBits();
3965   unsigned ElSize = VBits / VL;
3966   bool Result = (Index * ElSize) % 128 == 0;
3967
3968   return Result;
3969 }
3970
3971 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3972 /// operand specifies a subvector insert that is suitable for input to
3973 /// VINSERTF128.
3974 bool X86::isVINSERTF128Index(SDNode *N) {
3975   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3976     return false;
3977
3978   // The index should be aligned on a 128-bit boundary.
3979   uint64_t Index =
3980     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3981
3982   unsigned VL = N->getValueType(0).getVectorNumElements();
3983   unsigned VBits = N->getValueType(0).getSizeInBits();
3984   unsigned ElSize = VBits / VL;
3985   bool Result = (Index * ElSize) % 128 == 0;
3986
3987   return Result;
3988 }
3989
3990 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3991 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3992 /// Handles 128-bit and 256-bit.
3993 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3994   EVT VT = N->getValueType(0);
3995
3996   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997          "Unsupported vector type for PSHUF/SHUFP");
3998
3999   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4000   // independently on 128-bit lanes.
4001   unsigned NumElts = VT.getVectorNumElements();
4002   unsigned NumLanes = VT.getSizeInBits()/128;
4003   unsigned NumLaneElts = NumElts/NumLanes;
4004
4005   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4006          "Only supports 2 or 4 elements per lane");
4007
4008   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4009   unsigned Mask = 0;
4010   for (unsigned i = 0; i != NumElts; ++i) {
4011     int Elt = N->getMaskElt(i);
4012     if (Elt < 0) continue;
4013     Elt &= NumLaneElts - 1;
4014     unsigned ShAmt = (i << Shift) % 8;
4015     Mask |= Elt << ShAmt;
4016   }
4017
4018   return Mask;
4019 }
4020
4021 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4022 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4023 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4024   EVT VT = N->getValueType(0);
4025
4026   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4027          "Unsupported vector type for PSHUFHW");
4028
4029   unsigned NumElts = VT.getVectorNumElements();
4030
4031   unsigned Mask = 0;
4032   for (unsigned l = 0; l != NumElts; l += 8) {
4033     // 8 nodes per lane, but we only care about the last 4.
4034     for (unsigned i = 0; i < 4; ++i) {
4035       int Elt = N->getMaskElt(l+i+4);
4036       if (Elt < 0) continue;
4037       Elt &= 0x3; // only 2-bits.
4038       Mask |= Elt << (i * 2);
4039     }
4040   }
4041
4042   return Mask;
4043 }
4044
4045 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4046 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4047 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4048   EVT VT = N->getValueType(0);
4049
4050   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4051          "Unsupported vector type for PSHUFHW");
4052
4053   unsigned NumElts = VT.getVectorNumElements();
4054
4055   unsigned Mask = 0;
4056   for (unsigned l = 0; l != NumElts; l += 8) {
4057     // 8 nodes per lane, but we only care about the first 4.
4058     for (unsigned i = 0; i < 4; ++i) {
4059       int Elt = N->getMaskElt(l+i);
4060       if (Elt < 0) continue;
4061       Elt &= 0x3; // only 2-bits
4062       Mask |= Elt << (i * 2);
4063     }
4064   }
4065
4066   return Mask;
4067 }
4068
4069 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4070 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4071 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4072   EVT VT = SVOp->getValueType(0);
4073   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4074
4075   unsigned NumElts = VT.getVectorNumElements();
4076   unsigned NumLanes = VT.getSizeInBits()/128;
4077   unsigned NumLaneElts = NumElts/NumLanes;
4078
4079   int Val = 0;
4080   unsigned i;
4081   for (i = 0; i != NumElts; ++i) {
4082     Val = SVOp->getMaskElt(i);
4083     if (Val >= 0)
4084       break;
4085   }
4086   if (Val >= (int)NumElts)
4087     Val -= NumElts - NumLaneElts;
4088
4089   assert(Val - i > 0 && "PALIGNR imm should be positive");
4090   return (Val - i) * EltSize;
4091 }
4092
4093 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4094 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4095 /// instructions.
4096 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4097   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4098     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4099
4100   uint64_t Index =
4101     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4102
4103   EVT VecVT = N->getOperand(0).getValueType();
4104   EVT ElVT = VecVT.getVectorElementType();
4105
4106   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4107   return Index / NumElemsPerChunk;
4108 }
4109
4110 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4111 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4112 /// instructions.
4113 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4114   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4115     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4116
4117   uint64_t Index =
4118     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4119
4120   EVT VecVT = N->getValueType(0);
4121   EVT ElVT = VecVT.getVectorElementType();
4122
4123   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4124   return Index / NumElemsPerChunk;
4125 }
4126
4127 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4128 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4129 /// Handles 256-bit.
4130 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4131   EVT VT = N->getValueType(0);
4132
4133   unsigned NumElts = VT.getVectorNumElements();
4134
4135   assert((VT.is256BitVector() && NumElts == 4) &&
4136          "Unsupported vector type for VPERMQ/VPERMPD");
4137
4138   unsigned Mask = 0;
4139   for (unsigned i = 0; i != NumElts; ++i) {
4140     int Elt = N->getMaskElt(i);
4141     if (Elt < 0)
4142       continue;
4143     Mask |= Elt << (i*2);
4144   }
4145
4146   return Mask;
4147 }
4148 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4149 /// constant +0.0.
4150 bool X86::isZeroNode(SDValue Elt) {
4151   return ((isa<ConstantSDNode>(Elt) &&
4152            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4153           (isa<ConstantFPSDNode>(Elt) &&
4154            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4155 }
4156
4157 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4158 /// their permute mask.
4159 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4160                                     SelectionDAG &DAG) {
4161   EVT VT = SVOp->getValueType(0);
4162   unsigned NumElems = VT.getVectorNumElements();
4163   SmallVector<int, 8> MaskVec;
4164
4165   for (unsigned i = 0; i != NumElems; ++i) {
4166     int Idx = SVOp->getMaskElt(i);
4167     if (Idx >= 0) {
4168       if (Idx < (int)NumElems)
4169         Idx += NumElems;
4170       else
4171         Idx -= NumElems;
4172     }
4173     MaskVec.push_back(Idx);
4174   }
4175   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4176                               SVOp->getOperand(0), &MaskVec[0]);
4177 }
4178
4179 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4180 /// match movhlps. The lower half elements should come from upper half of
4181 /// V1 (and in order), and the upper half elements should come from the upper
4182 /// half of V2 (and in order).
4183 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4184   if (!VT.is128BitVector())
4185     return false;
4186   if (VT.getVectorNumElements() != 4)
4187     return false;
4188   for (unsigned i = 0, e = 2; i != e; ++i)
4189     if (!isUndefOrEqual(Mask[i], i+2))
4190       return false;
4191   for (unsigned i = 2; i != 4; ++i)
4192     if (!isUndefOrEqual(Mask[i], i+4))
4193       return false;
4194   return true;
4195 }
4196
4197 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4198 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4199 /// required.
4200 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4201   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4202     return false;
4203   N = N->getOperand(0).getNode();
4204   if (!ISD::isNON_EXTLoad(N))
4205     return false;
4206   if (LD)
4207     *LD = cast<LoadSDNode>(N);
4208   return true;
4209 }
4210
4211 // Test whether the given value is a vector value which will be legalized
4212 // into a load.
4213 static bool WillBeConstantPoolLoad(SDNode *N) {
4214   if (N->getOpcode() != ISD::BUILD_VECTOR)
4215     return false;
4216
4217   // Check for any non-constant elements.
4218   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4219     switch (N->getOperand(i).getNode()->getOpcode()) {
4220     case ISD::UNDEF:
4221     case ISD::ConstantFP:
4222     case ISD::Constant:
4223       break;
4224     default:
4225       return false;
4226     }
4227
4228   // Vectors of all-zeros and all-ones are materialized with special
4229   // instructions rather than being loaded.
4230   return !ISD::isBuildVectorAllZeros(N) &&
4231          !ISD::isBuildVectorAllOnes(N);
4232 }
4233
4234 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4235 /// match movlp{s|d}. The lower half elements should come from lower half of
4236 /// V1 (and in order), and the upper half elements should come from the upper
4237 /// half of V2 (and in order). And since V1 will become the source of the
4238 /// MOVLP, it must be either a vector load or a scalar load to vector.
4239 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4240                                ArrayRef<int> Mask, EVT VT) {
4241   if (!VT.is128BitVector())
4242     return false;
4243
4244   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4245     return false;
4246   // Is V2 is a vector load, don't do this transformation. We will try to use
4247   // load folding shufps op.
4248   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4249     return false;
4250
4251   unsigned NumElems = VT.getVectorNumElements();
4252
4253   if (NumElems != 2 && NumElems != 4)
4254     return false;
4255   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4256     if (!isUndefOrEqual(Mask[i], i))
4257       return false;
4258   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4259     if (!isUndefOrEqual(Mask[i], i+NumElems))
4260       return false;
4261   return true;
4262 }
4263
4264 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4265 /// all the same.
4266 static bool isSplatVector(SDNode *N) {
4267   if (N->getOpcode() != ISD::BUILD_VECTOR)
4268     return false;
4269
4270   SDValue SplatValue = N->getOperand(0);
4271   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4272     if (N->getOperand(i) != SplatValue)
4273       return false;
4274   return true;
4275 }
4276
4277 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4278 /// to an zero vector.
4279 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4280 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4281   SDValue V1 = N->getOperand(0);
4282   SDValue V2 = N->getOperand(1);
4283   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4284   for (unsigned i = 0; i != NumElems; ++i) {
4285     int Idx = N->getMaskElt(i);
4286     if (Idx >= (int)NumElems) {
4287       unsigned Opc = V2.getOpcode();
4288       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4289         continue;
4290       if (Opc != ISD::BUILD_VECTOR ||
4291           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4292         return false;
4293     } else if (Idx >= 0) {
4294       unsigned Opc = V1.getOpcode();
4295       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4296         continue;
4297       if (Opc != ISD::BUILD_VECTOR ||
4298           !X86::isZeroNode(V1.getOperand(Idx)))
4299         return false;
4300     }
4301   }
4302   return true;
4303 }
4304
4305 /// getZeroVector - Returns a vector of specified type with all zero elements.
4306 ///
4307 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4308                              SelectionDAG &DAG, DebugLoc dl) {
4309   assert(VT.isVector() && "Expected a vector type");
4310   unsigned Size = VT.getSizeInBits();
4311
4312   // Always build SSE zero vectors as <4 x i32> bitcasted
4313   // to their dest type. This ensures they get CSE'd.
4314   SDValue Vec;
4315   if (Size == 128) {  // SSE
4316     if (Subtarget->hasSSE2()) {  // SSE2
4317       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4318       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319     } else { // SSE1
4320       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4321       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4322     }
4323   } else if (Size == 256) { // AVX
4324     if (Subtarget->hasAVX2()) { // AVX2
4325       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4326       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4328     } else {
4329       // 256-bit logic and arithmetic instructions in AVX are all
4330       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4331       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4332       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4333       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4334     }
4335   } else
4336     llvm_unreachable("Unexpected vector type");
4337
4338   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4339 }
4340
4341 /// getOnesVector - Returns a vector of specified type with all bits set.
4342 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4343 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4344 /// Then bitcast to their original type, ensuring they get CSE'd.
4345 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4346                              DebugLoc dl) {
4347   assert(VT.isVector() && "Expected a vector type");
4348   unsigned Size = VT.getSizeInBits();
4349
4350   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4351   SDValue Vec;
4352   if (Size == 256) {
4353     if (HasAVX2) { // AVX2
4354       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4355       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4356     } else { // AVX
4357       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4358       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4359     }
4360   } else if (Size == 128) {
4361     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4362   } else
4363     llvm_unreachable("Unexpected vector type");
4364
4365   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4366 }
4367
4368 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4369 /// that point to V2 points to its first element.
4370 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4371   for (unsigned i = 0; i != NumElems; ++i) {
4372     if (Mask[i] > (int)NumElems) {
4373       Mask[i] = NumElems;
4374     }
4375   }
4376 }
4377
4378 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4379 /// operation of specified width.
4380 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4381                        SDValue V2) {
4382   unsigned NumElems = VT.getVectorNumElements();
4383   SmallVector<int, 8> Mask;
4384   Mask.push_back(NumElems);
4385   for (unsigned i = 1; i != NumElems; ++i)
4386     Mask.push_back(i);
4387   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4388 }
4389
4390 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4391 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4392                           SDValue V2) {
4393   unsigned NumElems = VT.getVectorNumElements();
4394   SmallVector<int, 8> Mask;
4395   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4396     Mask.push_back(i);
4397     Mask.push_back(i + NumElems);
4398   }
4399   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4400 }
4401
4402 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4403 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4404                           SDValue V2) {
4405   unsigned NumElems = VT.getVectorNumElements();
4406   SmallVector<int, 8> Mask;
4407   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4408     Mask.push_back(i + Half);
4409     Mask.push_back(i + NumElems + Half);
4410   }
4411   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4412 }
4413
4414 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4415 // a generic shuffle instruction because the target has no such instructions.
4416 // Generate shuffles which repeat i16 and i8 several times until they can be
4417 // represented by v4f32 and then be manipulated by target suported shuffles.
4418 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4419   EVT VT = V.getValueType();
4420   int NumElems = VT.getVectorNumElements();
4421   DebugLoc dl = V.getDebugLoc();
4422
4423   while (NumElems > 4) {
4424     if (EltNo < NumElems/2) {
4425       V = getUnpackl(DAG, dl, VT, V, V);
4426     } else {
4427       V = getUnpackh(DAG, dl, VT, V, V);
4428       EltNo -= NumElems/2;
4429     }
4430     NumElems >>= 1;
4431   }
4432   return V;
4433 }
4434
4435 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4436 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4437   EVT VT = V.getValueType();
4438   DebugLoc dl = V.getDebugLoc();
4439   unsigned Size = VT.getSizeInBits();
4440
4441   if (Size == 128) {
4442     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4443     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4444     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4445                              &SplatMask[0]);
4446   } else if (Size == 256) {
4447     // To use VPERMILPS to splat scalars, the second half of indicies must
4448     // refer to the higher part, which is a duplication of the lower one,
4449     // because VPERMILPS can only handle in-lane permutations.
4450     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4451                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4452
4453     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4454     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4455                              &SplatMask[0]);
4456   } else
4457     llvm_unreachable("Vector size not supported");
4458
4459   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4460 }
4461
4462 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4463 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4464   EVT SrcVT = SV->getValueType(0);
4465   SDValue V1 = SV->getOperand(0);
4466   DebugLoc dl = SV->getDebugLoc();
4467
4468   int EltNo = SV->getSplatIndex();
4469   int NumElems = SrcVT.getVectorNumElements();
4470   unsigned Size = SrcVT.getSizeInBits();
4471
4472   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4473           "Unknown how to promote splat for type");
4474
4475   // Extract the 128-bit part containing the splat element and update
4476   // the splat element index when it refers to the higher register.
4477   if (Size == 256) {
4478     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4479     if (EltNo >= NumElems/2)
4480       EltNo -= NumElems/2;
4481   }
4482
4483   // All i16 and i8 vector types can't be used directly by a generic shuffle
4484   // instruction because the target has no such instruction. Generate shuffles
4485   // which repeat i16 and i8 several times until they fit in i32, and then can
4486   // be manipulated by target suported shuffles.
4487   EVT EltVT = SrcVT.getVectorElementType();
4488   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4489     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4490
4491   // Recreate the 256-bit vector and place the same 128-bit vector
4492   // into the low and high part. This is necessary because we want
4493   // to use VPERM* to shuffle the vectors
4494   if (Size == 256) {
4495     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4496   }
4497
4498   return getLegalSplat(DAG, V1, EltNo);
4499 }
4500
4501 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4502 /// vector of zero or undef vector.  This produces a shuffle where the low
4503 /// element of V2 is swizzled into the zero/undef vector, landing at element
4504 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4505 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4506                                            bool IsZero,
4507                                            const X86Subtarget *Subtarget,
4508                                            SelectionDAG &DAG) {
4509   EVT VT = V2.getValueType();
4510   SDValue V1 = IsZero
4511     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4512   unsigned NumElems = VT.getVectorNumElements();
4513   SmallVector<int, 16> MaskVec;
4514   for (unsigned i = 0; i != NumElems; ++i)
4515     // If this is the insertion idx, put the low elt of V2 here.
4516     MaskVec.push_back(i == Idx ? NumElems : i);
4517   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4518 }
4519
4520 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4521 /// target specific opcode. Returns true if the Mask could be calculated.
4522 /// Sets IsUnary to true if only uses one source.
4523 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4524                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4525   unsigned NumElems = VT.getVectorNumElements();
4526   SDValue ImmN;
4527
4528   IsUnary = false;
4529   switch(N->getOpcode()) {
4530   case X86ISD::SHUFP:
4531     ImmN = N->getOperand(N->getNumOperands()-1);
4532     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4533     break;
4534   case X86ISD::UNPCKH:
4535     DecodeUNPCKHMask(VT, Mask);
4536     break;
4537   case X86ISD::UNPCKL:
4538     DecodeUNPCKLMask(VT, Mask);
4539     break;
4540   case X86ISD::MOVHLPS:
4541     DecodeMOVHLPSMask(NumElems, Mask);
4542     break;
4543   case X86ISD::MOVLHPS:
4544     DecodeMOVLHPSMask(NumElems, Mask);
4545     break;
4546   case X86ISD::PSHUFD:
4547   case X86ISD::VPERMILP:
4548     ImmN = N->getOperand(N->getNumOperands()-1);
4549     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4550     IsUnary = true;
4551     break;
4552   case X86ISD::PSHUFHW:
4553     ImmN = N->getOperand(N->getNumOperands()-1);
4554     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4555     IsUnary = true;
4556     break;
4557   case X86ISD::PSHUFLW:
4558     ImmN = N->getOperand(N->getNumOperands()-1);
4559     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4560     IsUnary = true;
4561     break;
4562   case X86ISD::VPERMI:
4563     ImmN = N->getOperand(N->getNumOperands()-1);
4564     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565     IsUnary = true;
4566     break;
4567   case X86ISD::MOVSS:
4568   case X86ISD::MOVSD: {
4569     // The index 0 always comes from the first element of the second source,
4570     // this is why MOVSS and MOVSD are used in the first place. The other
4571     // elements come from the other positions of the first source vector
4572     Mask.push_back(NumElems);
4573     for (unsigned i = 1; i != NumElems; ++i) {
4574       Mask.push_back(i);
4575     }
4576     break;
4577   }
4578   case X86ISD::VPERM2X128:
4579     ImmN = N->getOperand(N->getNumOperands()-1);
4580     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581     if (Mask.empty()) return false;
4582     break;
4583   case X86ISD::MOVDDUP:
4584   case X86ISD::MOVLHPD:
4585   case X86ISD::MOVLPD:
4586   case X86ISD::MOVLPS:
4587   case X86ISD::MOVSHDUP:
4588   case X86ISD::MOVSLDUP:
4589   case X86ISD::PALIGN:
4590     // Not yet implemented
4591     return false;
4592   default: llvm_unreachable("unknown target shuffle node");
4593   }
4594
4595   return true;
4596 }
4597
4598 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4599 /// element of the result of the vector shuffle.
4600 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4601                                    unsigned Depth) {
4602   if (Depth == 6)
4603     return SDValue();  // Limit search depth.
4604
4605   SDValue V = SDValue(N, 0);
4606   EVT VT = V.getValueType();
4607   unsigned Opcode = V.getOpcode();
4608
4609   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4610   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4611     int Elt = SV->getMaskElt(Index);
4612
4613     if (Elt < 0)
4614       return DAG.getUNDEF(VT.getVectorElementType());
4615
4616     unsigned NumElems = VT.getVectorNumElements();
4617     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4618                                          : SV->getOperand(1);
4619     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4620   }
4621
4622   // Recurse into target specific vector shuffles to find scalars.
4623   if (isTargetShuffle(Opcode)) {
4624     MVT ShufVT = V.getValueType().getSimpleVT();
4625     unsigned NumElems = ShufVT.getVectorNumElements();
4626     SmallVector<int, 16> ShuffleMask;
4627     SDValue ImmN;
4628     bool IsUnary;
4629
4630     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4631       return SDValue();
4632
4633     int Elt = ShuffleMask[Index];
4634     if (Elt < 0)
4635       return DAG.getUNDEF(ShufVT.getVectorElementType());
4636
4637     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4638                                          : N->getOperand(1);
4639     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4640                                Depth+1);
4641   }
4642
4643   // Actual nodes that may contain scalar elements
4644   if (Opcode == ISD::BITCAST) {
4645     V = V.getOperand(0);
4646     EVT SrcVT = V.getValueType();
4647     unsigned NumElems = VT.getVectorNumElements();
4648
4649     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4650       return SDValue();
4651   }
4652
4653   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4654     return (Index == 0) ? V.getOperand(0)
4655                         : DAG.getUNDEF(VT.getVectorElementType());
4656
4657   if (V.getOpcode() == ISD::BUILD_VECTOR)
4658     return V.getOperand(Index);
4659
4660   return SDValue();
4661 }
4662
4663 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4664 /// shuffle operation which come from a consecutively from a zero. The
4665 /// search can start in two different directions, from left or right.
4666 static
4667 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4668                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4669   unsigned i;
4670   for (i = 0; i != NumElems; ++i) {
4671     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4672     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4673     if (!(Elt.getNode() &&
4674          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4675       break;
4676   }
4677
4678   return i;
4679 }
4680
4681 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4682 /// correspond consecutively to elements from one of the vector operands,
4683 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4684 static
4685 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4686                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4687                               unsigned NumElems, unsigned &OpNum) {
4688   bool SeenV1 = false;
4689   bool SeenV2 = false;
4690
4691   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4692     int Idx = SVOp->getMaskElt(i);
4693     // Ignore undef indicies
4694     if (Idx < 0)
4695       continue;
4696
4697     if (Idx < (int)NumElems)
4698       SeenV1 = true;
4699     else
4700       SeenV2 = true;
4701
4702     // Only accept consecutive elements from the same vector
4703     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4704       return false;
4705   }
4706
4707   OpNum = SeenV1 ? 0 : 1;
4708   return true;
4709 }
4710
4711 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4712 /// logical left shift of a vector.
4713 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4714                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4715   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4716   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4717               false /* check zeros from right */, DAG);
4718   unsigned OpSrc;
4719
4720   if (!NumZeros)
4721     return false;
4722
4723   // Considering the elements in the mask that are not consecutive zeros,
4724   // check if they consecutively come from only one of the source vectors.
4725   //
4726   //               V1 = {X, A, B, C}     0
4727   //                         \  \  \    /
4728   //   vector_shuffle V1, V2 <1, 2, 3, X>
4729   //
4730   if (!isShuffleMaskConsecutive(SVOp,
4731             0,                   // Mask Start Index
4732             NumElems-NumZeros,   // Mask End Index(exclusive)
4733             NumZeros,            // Where to start looking in the src vector
4734             NumElems,            // Number of elements in vector
4735             OpSrc))              // Which source operand ?
4736     return false;
4737
4738   isLeft = false;
4739   ShAmt = NumZeros;
4740   ShVal = SVOp->getOperand(OpSrc);
4741   return true;
4742 }
4743
4744 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4745 /// logical left shift of a vector.
4746 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4747                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4748   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4749   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4750               true /* check zeros from left */, DAG);
4751   unsigned OpSrc;
4752
4753   if (!NumZeros)
4754     return false;
4755
4756   // Considering the elements in the mask that are not consecutive zeros,
4757   // check if they consecutively come from only one of the source vectors.
4758   //
4759   //                           0    { A, B, X, X } = V2
4760   //                          / \    /  /
4761   //   vector_shuffle V1, V2 <X, X, 4, 5>
4762   //
4763   if (!isShuffleMaskConsecutive(SVOp,
4764             NumZeros,     // Mask Start Index
4765             NumElems,     // Mask End Index(exclusive)
4766             0,            // Where to start looking in the src vector
4767             NumElems,     // Number of elements in vector
4768             OpSrc))       // Which source operand ?
4769     return false;
4770
4771   isLeft = true;
4772   ShAmt = NumZeros;
4773   ShVal = SVOp->getOperand(OpSrc);
4774   return true;
4775 }
4776
4777 /// isVectorShift - Returns true if the shuffle can be implemented as a
4778 /// logical left or right shift of a vector.
4779 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4780                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4781   // Although the logic below support any bitwidth size, there are no
4782   // shift instructions which handle more than 128-bit vectors.
4783   if (!SVOp->getValueType(0).is128BitVector())
4784     return false;
4785
4786   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4787       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4788     return true;
4789
4790   return false;
4791 }
4792
4793 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4794 ///
4795 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4796                                        unsigned NumNonZero, unsigned NumZero,
4797                                        SelectionDAG &DAG,
4798                                        const X86Subtarget* Subtarget,
4799                                        const TargetLowering &TLI) {
4800   if (NumNonZero > 8)
4801     return SDValue();
4802
4803   DebugLoc dl = Op.getDebugLoc();
4804   SDValue V(0, 0);
4805   bool First = true;
4806   for (unsigned i = 0; i < 16; ++i) {
4807     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4808     if (ThisIsNonZero && First) {
4809       if (NumZero)
4810         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4811       else
4812         V = DAG.getUNDEF(MVT::v8i16);
4813       First = false;
4814     }
4815
4816     if ((i & 1) != 0) {
4817       SDValue ThisElt(0, 0), LastElt(0, 0);
4818       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4819       if (LastIsNonZero) {
4820         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4821                               MVT::i16, Op.getOperand(i-1));
4822       }
4823       if (ThisIsNonZero) {
4824         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4825         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4826                               ThisElt, DAG.getConstant(8, MVT::i8));
4827         if (LastIsNonZero)
4828           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4829       } else
4830         ThisElt = LastElt;
4831
4832       if (ThisElt.getNode())
4833         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4834                         DAG.getIntPtrConstant(i/2));
4835     }
4836   }
4837
4838   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4839 }
4840
4841 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4842 ///
4843 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4844                                      unsigned NumNonZero, unsigned NumZero,
4845                                      SelectionDAG &DAG,
4846                                      const X86Subtarget* Subtarget,
4847                                      const TargetLowering &TLI) {
4848   if (NumNonZero > 4)
4849     return SDValue();
4850
4851   DebugLoc dl = Op.getDebugLoc();
4852   SDValue V(0, 0);
4853   bool First = true;
4854   for (unsigned i = 0; i < 8; ++i) {
4855     bool isNonZero = (NonZeros & (1 << i)) != 0;
4856     if (isNonZero) {
4857       if (First) {
4858         if (NumZero)
4859           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4860         else
4861           V = DAG.getUNDEF(MVT::v8i16);
4862         First = false;
4863       }
4864       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4865                       MVT::v8i16, V, Op.getOperand(i),
4866                       DAG.getIntPtrConstant(i));
4867     }
4868   }
4869
4870   return V;
4871 }
4872
4873 /// getVShift - Return a vector logical shift node.
4874 ///
4875 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4876                          unsigned NumBits, SelectionDAG &DAG,
4877                          const TargetLowering &TLI, DebugLoc dl) {
4878   assert(VT.is128BitVector() && "Unknown type for VShift");
4879   EVT ShVT = MVT::v2i64;
4880   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4881   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4882   return DAG.getNode(ISD::BITCAST, dl, VT,
4883                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4884                              DAG.getConstant(NumBits,
4885                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4886 }
4887
4888 SDValue
4889 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4890                                           SelectionDAG &DAG) const {
4891
4892   // Check if the scalar load can be widened into a vector load. And if
4893   // the address is "base + cst" see if the cst can be "absorbed" into
4894   // the shuffle mask.
4895   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4896     SDValue Ptr = LD->getBasePtr();
4897     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4898       return SDValue();
4899     EVT PVT = LD->getValueType(0);
4900     if (PVT != MVT::i32 && PVT != MVT::f32)
4901       return SDValue();
4902
4903     int FI = -1;
4904     int64_t Offset = 0;
4905     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4906       FI = FINode->getIndex();
4907       Offset = 0;
4908     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4909                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4910       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4911       Offset = Ptr.getConstantOperandVal(1);
4912       Ptr = Ptr.getOperand(0);
4913     } else {
4914       return SDValue();
4915     }
4916
4917     // FIXME: 256-bit vector instructions don't require a strict alignment,
4918     // improve this code to support it better.
4919     unsigned RequiredAlign = VT.getSizeInBits()/8;
4920     SDValue Chain = LD->getChain();
4921     // Make sure the stack object alignment is at least 16 or 32.
4922     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4923     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4924       if (MFI->isFixedObjectIndex(FI)) {
4925         // Can't change the alignment. FIXME: It's possible to compute
4926         // the exact stack offset and reference FI + adjust offset instead.
4927         // If someone *really* cares about this. That's the way to implement it.
4928         return SDValue();
4929       } else {
4930         MFI->setObjectAlignment(FI, RequiredAlign);
4931       }
4932     }
4933
4934     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4935     // Ptr + (Offset & ~15).
4936     if (Offset < 0)
4937       return SDValue();
4938     if ((Offset % RequiredAlign) & 3)
4939       return SDValue();
4940     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4941     if (StartOffset)
4942       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4943                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4944
4945     int EltNo = (Offset - StartOffset) >> 2;
4946     unsigned NumElems = VT.getVectorNumElements();
4947
4948     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4949     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4950                              LD->getPointerInfo().getWithOffset(StartOffset),
4951                              false, false, false, 0);
4952
4953     SmallVector<int, 8> Mask;
4954     for (unsigned i = 0; i != NumElems; ++i)
4955       Mask.push_back(EltNo);
4956
4957     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4958   }
4959
4960   return SDValue();
4961 }
4962
4963 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4964 /// vector of type 'VT', see if the elements can be replaced by a single large
4965 /// load which has the same value as a build_vector whose operands are 'elts'.
4966 ///
4967 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4968 ///
4969 /// FIXME: we'd also like to handle the case where the last elements are zero
4970 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4971 /// There's even a handy isZeroNode for that purpose.
4972 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4973                                         DebugLoc &DL, SelectionDAG &DAG) {
4974   EVT EltVT = VT.getVectorElementType();
4975   unsigned NumElems = Elts.size();
4976
4977   LoadSDNode *LDBase = NULL;
4978   unsigned LastLoadedElt = -1U;
4979
4980   // For each element in the initializer, see if we've found a load or an undef.
4981   // If we don't find an initial load element, or later load elements are
4982   // non-consecutive, bail out.
4983   for (unsigned i = 0; i < NumElems; ++i) {
4984     SDValue Elt = Elts[i];
4985
4986     if (!Elt.getNode() ||
4987         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4988       return SDValue();
4989     if (!LDBase) {
4990       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4991         return SDValue();
4992       LDBase = cast<LoadSDNode>(Elt.getNode());
4993       LastLoadedElt = i;
4994       continue;
4995     }
4996     if (Elt.getOpcode() == ISD::UNDEF)
4997       continue;
4998
4999     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5000     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5001       return SDValue();
5002     LastLoadedElt = i;
5003   }
5004
5005   // If we have found an entire vector of loads and undefs, then return a large
5006   // load of the entire vector width starting at the base pointer.  If we found
5007   // consecutive loads for the low half, generate a vzext_load node.
5008   if (LastLoadedElt == NumElems - 1) {
5009     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5010       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5011                          LDBase->getPointerInfo(),
5012                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5013                          LDBase->isInvariant(), 0);
5014     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5015                        LDBase->getPointerInfo(),
5016                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5017                        LDBase->isInvariant(), LDBase->getAlignment());
5018   }
5019   if (NumElems == 4 && LastLoadedElt == 1 &&
5020       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5021     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5022     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5023     SDValue ResNode =
5024         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5025                                 LDBase->getPointerInfo(),
5026                                 LDBase->getAlignment(),
5027                                 false/*isVolatile*/, true/*ReadMem*/,
5028                                 false/*WriteMem*/);
5029
5030     // Make sure the newly-created LOAD is in the same position as LDBase in
5031     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5032     // update uses of LDBase's output chain to use the TokenFactor.
5033     if (LDBase->hasAnyUseOfValue(1)) {
5034       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5035                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5036       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5037       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5038                              SDValue(ResNode.getNode(), 1));
5039     }
5040
5041     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5042   }
5043   return SDValue();
5044 }
5045
5046 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5047 /// to generate a splat value for the following cases:
5048 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5049 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5050 /// a scalar load, or a constant.
5051 /// The VBROADCAST node is returned when a pattern is found,
5052 /// or SDValue() otherwise.
5053 SDValue
5054 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5055   if (!Subtarget->hasAVX())
5056     return SDValue();
5057
5058   EVT VT = Op.getValueType();
5059   DebugLoc dl = Op.getDebugLoc();
5060
5061   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5062          "Unsupported vector type for broadcast.");
5063
5064   SDValue Ld;
5065   bool ConstSplatVal;
5066
5067   switch (Op.getOpcode()) {
5068     default:
5069       // Unknown pattern found.
5070       return SDValue();
5071
5072     case ISD::BUILD_VECTOR: {
5073       // The BUILD_VECTOR node must be a splat.
5074       if (!isSplatVector(Op.getNode()))
5075         return SDValue();
5076
5077       Ld = Op.getOperand(0);
5078       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5079                      Ld.getOpcode() == ISD::ConstantFP);
5080
5081       // The suspected load node has several users. Make sure that all
5082       // of its users are from the BUILD_VECTOR node.
5083       // Constants may have multiple users.
5084       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5085         return SDValue();
5086       break;
5087     }
5088
5089     case ISD::VECTOR_SHUFFLE: {
5090       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5091
5092       // Shuffles must have a splat mask where the first element is
5093       // broadcasted.
5094       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5095         return SDValue();
5096
5097       SDValue Sc = Op.getOperand(0);
5098       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5099           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5100
5101         if (!Subtarget->hasAVX2())
5102           return SDValue();
5103
5104         // Use the register form of the broadcast instruction available on AVX2.
5105         if (VT.is256BitVector())
5106           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5107         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5108       }
5109
5110       Ld = Sc.getOperand(0);
5111       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5112                        Ld.getOpcode() == ISD::ConstantFP);
5113
5114       // The scalar_to_vector node and the suspected
5115       // load node must have exactly one user.
5116       // Constants may have multiple users.
5117       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5118         return SDValue();
5119       break;
5120     }
5121   }
5122
5123   bool Is256 = VT.is256BitVector();
5124
5125   // Handle the broadcasting a single constant scalar from the constant pool
5126   // into a vector. On Sandybridge it is still better to load a constant vector
5127   // from the constant pool and not to broadcast it from a scalar.
5128   if (ConstSplatVal && Subtarget->hasAVX2()) {
5129     EVT CVT = Ld.getValueType();
5130     assert(!CVT.isVector() && "Must not broadcast a vector type");
5131     unsigned ScalarSize = CVT.getSizeInBits();
5132
5133     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5134       const Constant *C = 0;
5135       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5136         C = CI->getConstantIntValue();
5137       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5138         C = CF->getConstantFPValue();
5139
5140       assert(C && "Invalid constant type");
5141
5142       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5143       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5144       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5145                        MachinePointerInfo::getConstantPool(),
5146                        false, false, false, Alignment);
5147
5148       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5149     }
5150   }
5151
5152   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5153   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5154
5155   // Handle AVX2 in-register broadcasts.
5156   if (!IsLoad && Subtarget->hasAVX2() &&
5157       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5158     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5159
5160   // The scalar source must be a normal load.
5161   if (!IsLoad)
5162     return SDValue();
5163
5164   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5165     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5166
5167   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5168   // double since there is no vbroadcastsd xmm
5169   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5170     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5171       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5172   }
5173
5174   // Unsupported broadcast.
5175   return SDValue();
5176 }
5177
5178 SDValue
5179 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5180   DebugLoc dl = Op.getDebugLoc();
5181
5182   EVT VT = Op.getValueType();
5183   EVT ExtVT = VT.getVectorElementType();
5184   unsigned NumElems = Op.getNumOperands();
5185
5186   // Vectors containing all zeros can be matched by pxor and xorps later
5187   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5188     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5189     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5190     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5191       return Op;
5192
5193     return getZeroVector(VT, Subtarget, DAG, dl);
5194   }
5195
5196   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5197   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5198   // vpcmpeqd on 256-bit vectors.
5199   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5200     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5201       return Op;
5202
5203     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5204   }
5205
5206   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5207   if (Broadcast.getNode())
5208     return Broadcast;
5209
5210   unsigned EVTBits = ExtVT.getSizeInBits();
5211
5212   unsigned NumZero  = 0;
5213   unsigned NumNonZero = 0;
5214   unsigned NonZeros = 0;
5215   bool IsAllConstants = true;
5216   SmallSet<SDValue, 8> Values;
5217   for (unsigned i = 0; i < NumElems; ++i) {
5218     SDValue Elt = Op.getOperand(i);
5219     if (Elt.getOpcode() == ISD::UNDEF)
5220       continue;
5221     Values.insert(Elt);
5222     if (Elt.getOpcode() != ISD::Constant &&
5223         Elt.getOpcode() != ISD::ConstantFP)
5224       IsAllConstants = false;
5225     if (X86::isZeroNode(Elt))
5226       NumZero++;
5227     else {
5228       NonZeros |= (1 << i);
5229       NumNonZero++;
5230     }
5231   }
5232
5233   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5234   if (NumNonZero == 0)
5235     return DAG.getUNDEF(VT);
5236
5237   // Special case for single non-zero, non-undef, element.
5238   if (NumNonZero == 1) {
5239     unsigned Idx = CountTrailingZeros_32(NonZeros);
5240     SDValue Item = Op.getOperand(Idx);
5241
5242     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5243     // the value are obviously zero, truncate the value to i32 and do the
5244     // insertion that way.  Only do this if the value is non-constant or if the
5245     // value is a constant being inserted into element 0.  It is cheaper to do
5246     // a constant pool load than it is to do a movd + shuffle.
5247     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5248         (!IsAllConstants || Idx == 0)) {
5249       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5250         // Handle SSE only.
5251         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5252         EVT VecVT = MVT::v4i32;
5253         unsigned VecElts = 4;
5254
5255         // Truncate the value (which may itself be a constant) to i32, and
5256         // convert it to a vector with movd (S2V+shuffle to zero extend).
5257         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5258         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5259         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5260
5261         // Now we have our 32-bit value zero extended in the low element of
5262         // a vector.  If Idx != 0, swizzle it into place.
5263         if (Idx != 0) {
5264           SmallVector<int, 4> Mask;
5265           Mask.push_back(Idx);
5266           for (unsigned i = 1; i != VecElts; ++i)
5267             Mask.push_back(i);
5268           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5269                                       &Mask[0]);
5270         }
5271         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5272       }
5273     }
5274
5275     // If we have a constant or non-constant insertion into the low element of
5276     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5277     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5278     // depending on what the source datatype is.
5279     if (Idx == 0) {
5280       if (NumZero == 0)
5281         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5282
5283       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5284           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5285         if (VT.is256BitVector()) {
5286           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5287           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5288                              Item, DAG.getIntPtrConstant(0));
5289         }
5290         assert(VT.is128BitVector() && "Expected an SSE value type!");
5291         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5292         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5293         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5294       }
5295
5296       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5297         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5298         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5299         if (VT.is256BitVector()) {
5300           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5301           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5302         } else {
5303           assert(VT.is128BitVector() && "Expected an SSE value type!");
5304           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5305         }
5306         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5307       }
5308     }
5309
5310     // Is it a vector logical left shift?
5311     if (NumElems == 2 && Idx == 1 &&
5312         X86::isZeroNode(Op.getOperand(0)) &&
5313         !X86::isZeroNode(Op.getOperand(1))) {
5314       unsigned NumBits = VT.getSizeInBits();
5315       return getVShift(true, VT,
5316                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5317                                    VT, Op.getOperand(1)),
5318                        NumBits/2, DAG, *this, dl);
5319     }
5320
5321     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5322       return SDValue();
5323
5324     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5325     // is a non-constant being inserted into an element other than the low one,
5326     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5327     // movd/movss) to move this into the low element, then shuffle it into
5328     // place.
5329     if (EVTBits == 32) {
5330       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5331
5332       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5333       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5334       SmallVector<int, 8> MaskVec;
5335       for (unsigned i = 0; i != NumElems; ++i)
5336         MaskVec.push_back(i == Idx ? 0 : 1);
5337       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5338     }
5339   }
5340
5341   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5342   if (Values.size() == 1) {
5343     if (EVTBits == 32) {
5344       // Instead of a shuffle like this:
5345       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5346       // Check if it's possible to issue this instead.
5347       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5348       unsigned Idx = CountTrailingZeros_32(NonZeros);
5349       SDValue Item = Op.getOperand(Idx);
5350       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5351         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5352     }
5353     return SDValue();
5354   }
5355
5356   // A vector full of immediates; various special cases are already
5357   // handled, so this is best done with a single constant-pool load.
5358   if (IsAllConstants)
5359     return SDValue();
5360
5361   // For AVX-length vectors, build the individual 128-bit pieces and use
5362   // shuffles to put them in place.
5363   if (VT.is256BitVector()) {
5364     SmallVector<SDValue, 32> V;
5365     for (unsigned i = 0; i != NumElems; ++i)
5366       V.push_back(Op.getOperand(i));
5367
5368     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5369
5370     // Build both the lower and upper subvector.
5371     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5372     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5373                                 NumElems/2);
5374
5375     // Recreate the wider vector with the lower and upper part.
5376     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5377   }
5378
5379   // Let legalizer expand 2-wide build_vectors.
5380   if (EVTBits == 64) {
5381     if (NumNonZero == 1) {
5382       // One half is zero or undef.
5383       unsigned Idx = CountTrailingZeros_32(NonZeros);
5384       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5385                                  Op.getOperand(Idx));
5386       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5387     }
5388     return SDValue();
5389   }
5390
5391   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5392   if (EVTBits == 8 && NumElems == 16) {
5393     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5394                                         Subtarget, *this);
5395     if (V.getNode()) return V;
5396   }
5397
5398   if (EVTBits == 16 && NumElems == 8) {
5399     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5400                                       Subtarget, *this);
5401     if (V.getNode()) return V;
5402   }
5403
5404   // If element VT is == 32 bits, turn it into a number of shuffles.
5405   SmallVector<SDValue, 8> V(NumElems);
5406   if (NumElems == 4 && NumZero > 0) {
5407     for (unsigned i = 0; i < 4; ++i) {
5408       bool isZero = !(NonZeros & (1 << i));
5409       if (isZero)
5410         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5411       else
5412         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5413     }
5414
5415     for (unsigned i = 0; i < 2; ++i) {
5416       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5417         default: break;
5418         case 0:
5419           V[i] = V[i*2];  // Must be a zero vector.
5420           break;
5421         case 1:
5422           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5423           break;
5424         case 2:
5425           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5426           break;
5427         case 3:
5428           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5429           break;
5430       }
5431     }
5432
5433     bool Reverse1 = (NonZeros & 0x3) == 2;
5434     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5435     int MaskVec[] = {
5436       Reverse1 ? 1 : 0,
5437       Reverse1 ? 0 : 1,
5438       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5439       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5440     };
5441     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5442   }
5443
5444   if (Values.size() > 1 && VT.is128BitVector()) {
5445     // Check for a build vector of consecutive loads.
5446     for (unsigned i = 0; i < NumElems; ++i)
5447       V[i] = Op.getOperand(i);
5448
5449     // Check for elements which are consecutive loads.
5450     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5451     if (LD.getNode())
5452       return LD;
5453
5454     // For SSE 4.1, use insertps to put the high elements into the low element.
5455     if (getSubtarget()->hasSSE41()) {
5456       SDValue Result;
5457       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5458         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5459       else
5460         Result = DAG.getUNDEF(VT);
5461
5462       for (unsigned i = 1; i < NumElems; ++i) {
5463         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5464         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5465                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5466       }
5467       return Result;
5468     }
5469
5470     // Otherwise, expand into a number of unpckl*, start by extending each of
5471     // our (non-undef) elements to the full vector width with the element in the
5472     // bottom slot of the vector (which generates no code for SSE).
5473     for (unsigned i = 0; i < NumElems; ++i) {
5474       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5475         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5476       else
5477         V[i] = DAG.getUNDEF(VT);
5478     }
5479
5480     // Next, we iteratively mix elements, e.g. for v4f32:
5481     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5482     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5483     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5484     unsigned EltStride = NumElems >> 1;
5485     while (EltStride != 0) {
5486       for (unsigned i = 0; i < EltStride; ++i) {
5487         // If V[i+EltStride] is undef and this is the first round of mixing,
5488         // then it is safe to just drop this shuffle: V[i] is already in the
5489         // right place, the one element (since it's the first round) being
5490         // inserted as undef can be dropped.  This isn't safe for successive
5491         // rounds because they will permute elements within both vectors.
5492         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5493             EltStride == NumElems/2)
5494           continue;
5495
5496         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5497       }
5498       EltStride >>= 1;
5499     }
5500     return V[0];
5501   }
5502   return SDValue();
5503 }
5504
5505 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5506 // to create 256-bit vectors from two other 128-bit ones.
5507 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5508   DebugLoc dl = Op.getDebugLoc();
5509   EVT ResVT = Op.getValueType();
5510
5511   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5512
5513   SDValue V1 = Op.getOperand(0);
5514   SDValue V2 = Op.getOperand(1);
5515   unsigned NumElems = ResVT.getVectorNumElements();
5516
5517   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5518 }
5519
5520 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5521   assert(Op.getNumOperands() == 2);
5522
5523   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5524   // from two other 128-bit ones.
5525   return LowerAVXCONCAT_VECTORS(Op, DAG);
5526 }
5527
5528 // Try to lower a shuffle node into a simple blend instruction.
5529 static SDValue
5530 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5531                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5532   SDValue V1 = SVOp->getOperand(0);
5533   SDValue V2 = SVOp->getOperand(1);
5534   DebugLoc dl = SVOp->getDebugLoc();
5535   MVT VT = SVOp->getValueType(0).getSimpleVT();
5536   unsigned NumElems = VT.getVectorNumElements();
5537
5538   if (!Subtarget->hasSSE41())
5539     return SDValue();
5540
5541   unsigned ISDNo = 0;
5542   MVT OpTy;
5543
5544   switch (VT.SimpleTy) {
5545   default: return SDValue();
5546   case MVT::v8i16:
5547     ISDNo = X86ISD::BLENDPW;
5548     OpTy = MVT::v8i16;
5549     break;
5550   case MVT::v4i32:
5551   case MVT::v4f32:
5552     ISDNo = X86ISD::BLENDPS;
5553     OpTy = MVT::v4f32;
5554     break;
5555   case MVT::v2i64:
5556   case MVT::v2f64:
5557     ISDNo = X86ISD::BLENDPD;
5558     OpTy = MVT::v2f64;
5559     break;
5560   case MVT::v8i32:
5561   case MVT::v8f32:
5562     if (!Subtarget->hasAVX())
5563       return SDValue();
5564     ISDNo = X86ISD::BLENDPS;
5565     OpTy = MVT::v8f32;
5566     break;
5567   case MVT::v4i64:
5568   case MVT::v4f64:
5569     if (!Subtarget->hasAVX())
5570       return SDValue();
5571     ISDNo = X86ISD::BLENDPD;
5572     OpTy = MVT::v4f64;
5573     break;
5574   }
5575   assert(ISDNo && "Invalid Op Number");
5576
5577   unsigned MaskVals = 0;
5578
5579   for (unsigned i = 0; i != NumElems; ++i) {
5580     int EltIdx = SVOp->getMaskElt(i);
5581     if (EltIdx == (int)i || EltIdx < 0)
5582       MaskVals |= (1<<i);
5583     else if (EltIdx == (int)(i + NumElems))
5584       continue; // Bit is set to zero;
5585     else
5586       return SDValue();
5587   }
5588
5589   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5590   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5591   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5592                              DAG.getConstant(MaskVals, MVT::i32));
5593   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5594 }
5595
5596 // v8i16 shuffles - Prefer shuffles in the following order:
5597 // 1. [all]   pshuflw, pshufhw, optional move
5598 // 2. [ssse3] 1 x pshufb
5599 // 3. [ssse3] 2 x pshufb + 1 x por
5600 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5601 static SDValue
5602 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5603                          SelectionDAG &DAG) {
5604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5605   SDValue V1 = SVOp->getOperand(0);
5606   SDValue V2 = SVOp->getOperand(1);
5607   DebugLoc dl = SVOp->getDebugLoc();
5608   SmallVector<int, 8> MaskVals;
5609
5610   // Determine if more than 1 of the words in each of the low and high quadwords
5611   // of the result come from the same quadword of one of the two inputs.  Undef
5612   // mask values count as coming from any quadword, for better codegen.
5613   unsigned LoQuad[] = { 0, 0, 0, 0 };
5614   unsigned HiQuad[] = { 0, 0, 0, 0 };
5615   std::bitset<4> InputQuads;
5616   for (unsigned i = 0; i < 8; ++i) {
5617     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5618     int EltIdx = SVOp->getMaskElt(i);
5619     MaskVals.push_back(EltIdx);
5620     if (EltIdx < 0) {
5621       ++Quad[0];
5622       ++Quad[1];
5623       ++Quad[2];
5624       ++Quad[3];
5625       continue;
5626     }
5627     ++Quad[EltIdx / 4];
5628     InputQuads.set(EltIdx / 4);
5629   }
5630
5631   int BestLoQuad = -1;
5632   unsigned MaxQuad = 1;
5633   for (unsigned i = 0; i < 4; ++i) {
5634     if (LoQuad[i] > MaxQuad) {
5635       BestLoQuad = i;
5636       MaxQuad = LoQuad[i];
5637     }
5638   }
5639
5640   int BestHiQuad = -1;
5641   MaxQuad = 1;
5642   for (unsigned i = 0; i < 4; ++i) {
5643     if (HiQuad[i] > MaxQuad) {
5644       BestHiQuad = i;
5645       MaxQuad = HiQuad[i];
5646     }
5647   }
5648
5649   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5650   // of the two input vectors, shuffle them into one input vector so only a
5651   // single pshufb instruction is necessary. If There are more than 2 input
5652   // quads, disable the next transformation since it does not help SSSE3.
5653   bool V1Used = InputQuads[0] || InputQuads[1];
5654   bool V2Used = InputQuads[2] || InputQuads[3];
5655   if (Subtarget->hasSSSE3()) {
5656     if (InputQuads.count() == 2 && V1Used && V2Used) {
5657       BestLoQuad = InputQuads[0] ? 0 : 1;
5658       BestHiQuad = InputQuads[2] ? 2 : 3;
5659     }
5660     if (InputQuads.count() > 2) {
5661       BestLoQuad = -1;
5662       BestHiQuad = -1;
5663     }
5664   }
5665
5666   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5667   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5668   // words from all 4 input quadwords.
5669   SDValue NewV;
5670   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5671     int MaskV[] = {
5672       BestLoQuad < 0 ? 0 : BestLoQuad,
5673       BestHiQuad < 0 ? 1 : BestHiQuad
5674     };
5675     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5676                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5677                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5678     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5679
5680     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5681     // source words for the shuffle, to aid later transformations.
5682     bool AllWordsInNewV = true;
5683     bool InOrder[2] = { true, true };
5684     for (unsigned i = 0; i != 8; ++i) {
5685       int idx = MaskVals[i];
5686       if (idx != (int)i)
5687         InOrder[i/4] = false;
5688       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5689         continue;
5690       AllWordsInNewV = false;
5691       break;
5692     }
5693
5694     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5695     if (AllWordsInNewV) {
5696       for (int i = 0; i != 8; ++i) {
5697         int idx = MaskVals[i];
5698         if (idx < 0)
5699           continue;
5700         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5701         if ((idx != i) && idx < 4)
5702           pshufhw = false;
5703         if ((idx != i) && idx > 3)
5704           pshuflw = false;
5705       }
5706       V1 = NewV;
5707       V2Used = false;
5708       BestLoQuad = 0;
5709       BestHiQuad = 1;
5710     }
5711
5712     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5713     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5714     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5715       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5716       unsigned TargetMask = 0;
5717       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5718                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5719       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5720       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5721                              getShufflePSHUFLWImmediate(SVOp);
5722       V1 = NewV.getOperand(0);
5723       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5724     }
5725   }
5726
5727   // If we have SSSE3, and all words of the result are from 1 input vector,
5728   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5729   // is present, fall back to case 4.
5730   if (Subtarget->hasSSSE3()) {
5731     SmallVector<SDValue,16> pshufbMask;
5732
5733     // If we have elements from both input vectors, set the high bit of the
5734     // shuffle mask element to zero out elements that come from V2 in the V1
5735     // mask, and elements that come from V1 in the V2 mask, so that the two
5736     // results can be OR'd together.
5737     bool TwoInputs = V1Used && V2Used;
5738     for (unsigned i = 0; i != 8; ++i) {
5739       int EltIdx = MaskVals[i] * 2;
5740       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5741       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5742       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5743       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5744     }
5745     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5746     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5747                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5748                                  MVT::v16i8, &pshufbMask[0], 16));
5749     if (!TwoInputs)
5750       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5751
5752     // Calculate the shuffle mask for the second input, shuffle it, and
5753     // OR it with the first shuffled input.
5754     pshufbMask.clear();
5755     for (unsigned i = 0; i != 8; ++i) {
5756       int EltIdx = MaskVals[i] * 2;
5757       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5758       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5759       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5760       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5761     }
5762     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5763     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5764                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5765                                  MVT::v16i8, &pshufbMask[0], 16));
5766     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5767     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5768   }
5769
5770   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5771   // and update MaskVals with new element order.
5772   std::bitset<8> InOrder;
5773   if (BestLoQuad >= 0) {
5774     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5775     for (int i = 0; i != 4; ++i) {
5776       int idx = MaskVals[i];
5777       if (idx < 0) {
5778         InOrder.set(i);
5779       } else if ((idx / 4) == BestLoQuad) {
5780         MaskV[i] = idx & 3;
5781         InOrder.set(i);
5782       }
5783     }
5784     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5785                                 &MaskV[0]);
5786
5787     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5788       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5789       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5790                                   NewV.getOperand(0),
5791                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5792     }
5793   }
5794
5795   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5796   // and update MaskVals with the new element order.
5797   if (BestHiQuad >= 0) {
5798     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5799     for (unsigned i = 4; i != 8; ++i) {
5800       int idx = MaskVals[i];
5801       if (idx < 0) {
5802         InOrder.set(i);
5803       } else if ((idx / 4) == BestHiQuad) {
5804         MaskV[i] = (idx & 3) + 4;
5805         InOrder.set(i);
5806       }
5807     }
5808     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5809                                 &MaskV[0]);
5810
5811     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5812       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5813       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5814                                   NewV.getOperand(0),
5815                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5816     }
5817   }
5818
5819   // In case BestHi & BestLo were both -1, which means each quadword has a word
5820   // from each of the four input quadwords, calculate the InOrder bitvector now
5821   // before falling through to the insert/extract cleanup.
5822   if (BestLoQuad == -1 && BestHiQuad == -1) {
5823     NewV = V1;
5824     for (int i = 0; i != 8; ++i)
5825       if (MaskVals[i] < 0 || MaskVals[i] == i)
5826         InOrder.set(i);
5827   }
5828
5829   // The other elements are put in the right place using pextrw and pinsrw.
5830   for (unsigned i = 0; i != 8; ++i) {
5831     if (InOrder[i])
5832       continue;
5833     int EltIdx = MaskVals[i];
5834     if (EltIdx < 0)
5835       continue;
5836     SDValue ExtOp = (EltIdx < 8) ?
5837       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5838                   DAG.getIntPtrConstant(EltIdx)) :
5839       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5840                   DAG.getIntPtrConstant(EltIdx - 8));
5841     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5842                        DAG.getIntPtrConstant(i));
5843   }
5844   return NewV;
5845 }
5846
5847 // v16i8 shuffles - Prefer shuffles in the following order:
5848 // 1. [ssse3] 1 x pshufb
5849 // 2. [ssse3] 2 x pshufb + 1 x por
5850 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5851 static
5852 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5853                                  SelectionDAG &DAG,
5854                                  const X86TargetLowering &TLI) {
5855   SDValue V1 = SVOp->getOperand(0);
5856   SDValue V2 = SVOp->getOperand(1);
5857   DebugLoc dl = SVOp->getDebugLoc();
5858   ArrayRef<int> MaskVals = SVOp->getMask();
5859
5860   // If we have SSSE3, case 1 is generated when all result bytes come from
5861   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5862   // present, fall back to case 3.
5863
5864   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5865   if (TLI.getSubtarget()->hasSSSE3()) {
5866     SmallVector<SDValue,16> pshufbMask;
5867
5868     // If all result elements are from one input vector, then only translate
5869     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5870     //
5871     // Otherwise, we have elements from both input vectors, and must zero out
5872     // elements that come from V2 in the first mask, and V1 in the second mask
5873     // so that we can OR them together.
5874     for (unsigned i = 0; i != 16; ++i) {
5875       int EltIdx = MaskVals[i];
5876       if (EltIdx < 0 || EltIdx >= 16)
5877         EltIdx = 0x80;
5878       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5879     }
5880     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5881                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5882                                  MVT::v16i8, &pshufbMask[0], 16));
5883
5884     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5885     // the 2nd operand if it's undefined or zero.
5886     if (V2.getOpcode() == ISD::UNDEF ||
5887         ISD::isBuildVectorAllZeros(V2.getNode()))
5888       return V1;
5889
5890     // Calculate the shuffle mask for the second input, shuffle it, and
5891     // OR it with the first shuffled input.
5892     pshufbMask.clear();
5893     for (unsigned i = 0; i != 16; ++i) {
5894       int EltIdx = MaskVals[i];
5895       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5896       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5897     }
5898     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5899                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5900                                  MVT::v16i8, &pshufbMask[0], 16));
5901     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5902   }
5903
5904   // No SSSE3 - Calculate in place words and then fix all out of place words
5905   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5906   // the 16 different words that comprise the two doublequadword input vectors.
5907   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5908   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5909   SDValue NewV = V1;
5910   for (int i = 0; i != 8; ++i) {
5911     int Elt0 = MaskVals[i*2];
5912     int Elt1 = MaskVals[i*2+1];
5913
5914     // This word of the result is all undef, skip it.
5915     if (Elt0 < 0 && Elt1 < 0)
5916       continue;
5917
5918     // This word of the result is already in the correct place, skip it.
5919     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5920       continue;
5921
5922     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5923     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5924     SDValue InsElt;
5925
5926     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5927     // using a single extract together, load it and store it.
5928     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5929       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5930                            DAG.getIntPtrConstant(Elt1 / 2));
5931       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5932                         DAG.getIntPtrConstant(i));
5933       continue;
5934     }
5935
5936     // If Elt1 is defined, extract it from the appropriate source.  If the
5937     // source byte is not also odd, shift the extracted word left 8 bits
5938     // otherwise clear the bottom 8 bits if we need to do an or.
5939     if (Elt1 >= 0) {
5940       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5941                            DAG.getIntPtrConstant(Elt1 / 2));
5942       if ((Elt1 & 1) == 0)
5943         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5944                              DAG.getConstant(8,
5945                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5946       else if (Elt0 >= 0)
5947         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5948                              DAG.getConstant(0xFF00, MVT::i16));
5949     }
5950     // If Elt0 is defined, extract it from the appropriate source.  If the
5951     // source byte is not also even, shift the extracted word right 8 bits. If
5952     // Elt1 was also defined, OR the extracted values together before
5953     // inserting them in the result.
5954     if (Elt0 >= 0) {
5955       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5956                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5957       if ((Elt0 & 1) != 0)
5958         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5959                               DAG.getConstant(8,
5960                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5961       else if (Elt1 >= 0)
5962         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5963                              DAG.getConstant(0x00FF, MVT::i16));
5964       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5965                          : InsElt0;
5966     }
5967     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5968                        DAG.getIntPtrConstant(i));
5969   }
5970   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5971 }
5972
5973 // v32i8 shuffles - Translate to VPSHUFB if possible.
5974 static
5975 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
5976                                  const X86Subtarget *Subtarget,
5977                                  SelectionDAG &DAG) {
5978   EVT VT = SVOp->getValueType(0);
5979   SDValue V1 = SVOp->getOperand(0);
5980   SDValue V2 = SVOp->getOperand(1);
5981   DebugLoc dl = SVOp->getDebugLoc();
5982   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
5983
5984   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5985   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
5986   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
5987
5988   // VPSHUFB may be generated if
5989   // (1) one of input vector is undefined or zeroinitializer.
5990   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
5991   // And (2) the mask indexes don't cross the 128-bit lane.
5992   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
5993       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
5994     return SDValue();
5995
5996   if (V1IsAllZero && !V2IsAllZero) {
5997     CommuteVectorShuffleMask(MaskVals, 32);
5998     V1 = V2;
5999   }
6000   SmallVector<SDValue, 32> pshufbMask;
6001   for (unsigned i = 0; i != 32; i++) {
6002     int EltIdx = MaskVals[i];
6003     if (EltIdx < 0 || EltIdx >= 32)
6004       EltIdx = 0x80;
6005     else {
6006       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6007         // Cross lane is not allowed.
6008         return SDValue();
6009       EltIdx &= 0xf;
6010     }
6011     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6012   }
6013   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6014                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6015                                   MVT::v32i8, &pshufbMask[0], 32));
6016 }
6017
6018 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6019 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6020 /// done when every pair / quad of shuffle mask elements point to elements in
6021 /// the right sequence. e.g.
6022 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6023 static
6024 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6025                                  SelectionDAG &DAG, DebugLoc dl) {
6026   MVT VT = SVOp->getValueType(0).getSimpleVT();
6027   unsigned NumElems = VT.getVectorNumElements();
6028   MVT NewVT;
6029   unsigned Scale;
6030   switch (VT.SimpleTy) {
6031   default: llvm_unreachable("Unexpected!");
6032   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6033   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6034   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6035   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6036   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6037   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6038   }
6039
6040   SmallVector<int, 8> MaskVec;
6041   for (unsigned i = 0; i != NumElems; i += Scale) {
6042     int StartIdx = -1;
6043     for (unsigned j = 0; j != Scale; ++j) {
6044       int EltIdx = SVOp->getMaskElt(i+j);
6045       if (EltIdx < 0)
6046         continue;
6047       if (StartIdx < 0)
6048         StartIdx = (EltIdx / Scale);
6049       if (EltIdx != (int)(StartIdx*Scale + j))
6050         return SDValue();
6051     }
6052     MaskVec.push_back(StartIdx);
6053   }
6054
6055   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6056   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6057   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6058 }
6059
6060 /// getVZextMovL - Return a zero-extending vector move low node.
6061 ///
6062 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6063                             SDValue SrcOp, SelectionDAG &DAG,
6064                             const X86Subtarget *Subtarget, DebugLoc dl) {
6065   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6066     LoadSDNode *LD = NULL;
6067     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6068       LD = dyn_cast<LoadSDNode>(SrcOp);
6069     if (!LD) {
6070       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6071       // instead.
6072       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6073       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6074           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6075           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6076           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6077         // PR2108
6078         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6079         return DAG.getNode(ISD::BITCAST, dl, VT,
6080                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6081                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6082                                                    OpVT,
6083                                                    SrcOp.getOperand(0)
6084                                                           .getOperand(0))));
6085       }
6086     }
6087   }
6088
6089   return DAG.getNode(ISD::BITCAST, dl, VT,
6090                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6091                                  DAG.getNode(ISD::BITCAST, dl,
6092                                              OpVT, SrcOp)));
6093 }
6094
6095 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6096 /// which could not be matched by any known target speficic shuffle
6097 static SDValue
6098 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6099
6100   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6101   if (NewOp.getNode())
6102     return NewOp;
6103
6104   EVT VT = SVOp->getValueType(0);
6105
6106   unsigned NumElems = VT.getVectorNumElements();
6107   unsigned NumLaneElems = NumElems / 2;
6108
6109   DebugLoc dl = SVOp->getDebugLoc();
6110   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6111   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6112   SDValue Output[2];
6113
6114   SmallVector<int, 16> Mask;
6115   for (unsigned l = 0; l < 2; ++l) {
6116     // Build a shuffle mask for the output, discovering on the fly which
6117     // input vectors to use as shuffle operands (recorded in InputUsed).
6118     // If building a suitable shuffle vector proves too hard, then bail
6119     // out with UseBuildVector set.
6120     bool UseBuildVector = false;
6121     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6122     unsigned LaneStart = l * NumLaneElems;
6123     for (unsigned i = 0; i != NumLaneElems; ++i) {
6124       // The mask element.  This indexes into the input.
6125       int Idx = SVOp->getMaskElt(i+LaneStart);
6126       if (Idx < 0) {
6127         // the mask element does not index into any input vector.
6128         Mask.push_back(-1);
6129         continue;
6130       }
6131
6132       // The input vector this mask element indexes into.
6133       int Input = Idx / NumLaneElems;
6134
6135       // Turn the index into an offset from the start of the input vector.
6136       Idx -= Input * NumLaneElems;
6137
6138       // Find or create a shuffle vector operand to hold this input.
6139       unsigned OpNo;
6140       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6141         if (InputUsed[OpNo] == Input)
6142           // This input vector is already an operand.
6143           break;
6144         if (InputUsed[OpNo] < 0) {
6145           // Create a new operand for this input vector.
6146           InputUsed[OpNo] = Input;
6147           break;
6148         }
6149       }
6150
6151       if (OpNo >= array_lengthof(InputUsed)) {
6152         // More than two input vectors used!  Give up on trying to create a
6153         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6154         UseBuildVector = true;
6155         break;
6156       }
6157
6158       // Add the mask index for the new shuffle vector.
6159       Mask.push_back(Idx + OpNo * NumLaneElems);
6160     }
6161
6162     if (UseBuildVector) {
6163       SmallVector<SDValue, 16> SVOps;
6164       for (unsigned i = 0; i != NumLaneElems; ++i) {
6165         // The mask element.  This indexes into the input.
6166         int Idx = SVOp->getMaskElt(i+LaneStart);
6167         if (Idx < 0) {
6168           SVOps.push_back(DAG.getUNDEF(EltVT));
6169           continue;
6170         }
6171
6172         // The input vector this mask element indexes into.
6173         int Input = Idx / NumElems;
6174
6175         // Turn the index into an offset from the start of the input vector.
6176         Idx -= Input * NumElems;
6177
6178         // Extract the vector element by hand.
6179         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6180                                     SVOp->getOperand(Input),
6181                                     DAG.getIntPtrConstant(Idx)));
6182       }
6183
6184       // Construct the output using a BUILD_VECTOR.
6185       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6186                               SVOps.size());
6187     } else if (InputUsed[0] < 0) {
6188       // No input vectors were used! The result is undefined.
6189       Output[l] = DAG.getUNDEF(NVT);
6190     } else {
6191       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6192                                         (InputUsed[0] % 2) * NumLaneElems,
6193                                         DAG, dl);
6194       // If only one input was used, use an undefined vector for the other.
6195       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6196         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6197                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6198       // At least one input vector was used. Create a new shuffle vector.
6199       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6200     }
6201
6202     Mask.clear();
6203   }
6204
6205   // Concatenate the result back
6206   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6207 }
6208
6209 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6210 /// 4 elements, and match them with several different shuffle types.
6211 static SDValue
6212 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6213   SDValue V1 = SVOp->getOperand(0);
6214   SDValue V2 = SVOp->getOperand(1);
6215   DebugLoc dl = SVOp->getDebugLoc();
6216   EVT VT = SVOp->getValueType(0);
6217
6218   assert(VT.is128BitVector() && "Unsupported vector size");
6219
6220   std::pair<int, int> Locs[4];
6221   int Mask1[] = { -1, -1, -1, -1 };
6222   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6223
6224   unsigned NumHi = 0;
6225   unsigned NumLo = 0;
6226   for (unsigned i = 0; i != 4; ++i) {
6227     int Idx = PermMask[i];
6228     if (Idx < 0) {
6229       Locs[i] = std::make_pair(-1, -1);
6230     } else {
6231       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6232       if (Idx < 4) {
6233         Locs[i] = std::make_pair(0, NumLo);
6234         Mask1[NumLo] = Idx;
6235         NumLo++;
6236       } else {
6237         Locs[i] = std::make_pair(1, NumHi);
6238         if (2+NumHi < 4)
6239           Mask1[2+NumHi] = Idx;
6240         NumHi++;
6241       }
6242     }
6243   }
6244
6245   if (NumLo <= 2 && NumHi <= 2) {
6246     // If no more than two elements come from either vector. This can be
6247     // implemented with two shuffles. First shuffle gather the elements.
6248     // The second shuffle, which takes the first shuffle as both of its
6249     // vector operands, put the elements into the right order.
6250     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6251
6252     int Mask2[] = { -1, -1, -1, -1 };
6253
6254     for (unsigned i = 0; i != 4; ++i)
6255       if (Locs[i].first != -1) {
6256         unsigned Idx = (i < 2) ? 0 : 4;
6257         Idx += Locs[i].first * 2 + Locs[i].second;
6258         Mask2[i] = Idx;
6259       }
6260
6261     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6262   }
6263
6264   if (NumLo == 3 || NumHi == 3) {
6265     // Otherwise, we must have three elements from one vector, call it X, and
6266     // one element from the other, call it Y.  First, use a shufps to build an
6267     // intermediate vector with the one element from Y and the element from X
6268     // that will be in the same half in the final destination (the indexes don't
6269     // matter). Then, use a shufps to build the final vector, taking the half
6270     // containing the element from Y from the intermediate, and the other half
6271     // from X.
6272     if (NumHi == 3) {
6273       // Normalize it so the 3 elements come from V1.
6274       CommuteVectorShuffleMask(PermMask, 4);
6275       std::swap(V1, V2);
6276     }
6277
6278     // Find the element from V2.
6279     unsigned HiIndex;
6280     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6281       int Val = PermMask[HiIndex];
6282       if (Val < 0)
6283         continue;
6284       if (Val >= 4)
6285         break;
6286     }
6287
6288     Mask1[0] = PermMask[HiIndex];
6289     Mask1[1] = -1;
6290     Mask1[2] = PermMask[HiIndex^1];
6291     Mask1[3] = -1;
6292     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6293
6294     if (HiIndex >= 2) {
6295       Mask1[0] = PermMask[0];
6296       Mask1[1] = PermMask[1];
6297       Mask1[2] = HiIndex & 1 ? 6 : 4;
6298       Mask1[3] = HiIndex & 1 ? 4 : 6;
6299       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6300     }
6301
6302     Mask1[0] = HiIndex & 1 ? 2 : 0;
6303     Mask1[1] = HiIndex & 1 ? 0 : 2;
6304     Mask1[2] = PermMask[2];
6305     Mask1[3] = PermMask[3];
6306     if (Mask1[2] >= 0)
6307       Mask1[2] += 4;
6308     if (Mask1[3] >= 0)
6309       Mask1[3] += 4;
6310     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6311   }
6312
6313   // Break it into (shuffle shuffle_hi, shuffle_lo).
6314   int LoMask[] = { -1, -1, -1, -1 };
6315   int HiMask[] = { -1, -1, -1, -1 };
6316
6317   int *MaskPtr = LoMask;
6318   unsigned MaskIdx = 0;
6319   unsigned LoIdx = 0;
6320   unsigned HiIdx = 2;
6321   for (unsigned i = 0; i != 4; ++i) {
6322     if (i == 2) {
6323       MaskPtr = HiMask;
6324       MaskIdx = 1;
6325       LoIdx = 0;
6326       HiIdx = 2;
6327     }
6328     int Idx = PermMask[i];
6329     if (Idx < 0) {
6330       Locs[i] = std::make_pair(-1, -1);
6331     } else if (Idx < 4) {
6332       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6333       MaskPtr[LoIdx] = Idx;
6334       LoIdx++;
6335     } else {
6336       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6337       MaskPtr[HiIdx] = Idx;
6338       HiIdx++;
6339     }
6340   }
6341
6342   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6343   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6344   int MaskOps[] = { -1, -1, -1, -1 };
6345   for (unsigned i = 0; i != 4; ++i)
6346     if (Locs[i].first != -1)
6347       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6348   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6349 }
6350
6351 static bool MayFoldVectorLoad(SDValue V) {
6352   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6353     V = V.getOperand(0);
6354   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6355     V = V.getOperand(0);
6356   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6357       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6358     // BUILD_VECTOR (load), undef
6359     V = V.getOperand(0);
6360   if (MayFoldLoad(V))
6361     return true;
6362   return false;
6363 }
6364
6365 // FIXME: the version above should always be used. Since there's
6366 // a bug where several vector shuffles can't be folded because the
6367 // DAG is not updated during lowering and a node claims to have two
6368 // uses while it only has one, use this version, and let isel match
6369 // another instruction if the load really happens to have more than
6370 // one use. Remove this version after this bug get fixed.
6371 // rdar://8434668, PR8156
6372 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6373   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6374     V = V.getOperand(0);
6375   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6376     V = V.getOperand(0);
6377   if (ISD::isNormalLoad(V.getNode()))
6378     return true;
6379   return false;
6380 }
6381
6382 static
6383 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6384   EVT VT = Op.getValueType();
6385
6386   // Canonizalize to v2f64.
6387   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6388   return DAG.getNode(ISD::BITCAST, dl, VT,
6389                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6390                                           V1, DAG));
6391 }
6392
6393 static
6394 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6395                         bool HasSSE2) {
6396   SDValue V1 = Op.getOperand(0);
6397   SDValue V2 = Op.getOperand(1);
6398   EVT VT = Op.getValueType();
6399
6400   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6401
6402   if (HasSSE2 && VT == MVT::v2f64)
6403     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6404
6405   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6406   return DAG.getNode(ISD::BITCAST, dl, VT,
6407                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6408                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6409                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6410 }
6411
6412 static
6413 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6414   SDValue V1 = Op.getOperand(0);
6415   SDValue V2 = Op.getOperand(1);
6416   EVT VT = Op.getValueType();
6417
6418   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6419          "unsupported shuffle type");
6420
6421   if (V2.getOpcode() == ISD::UNDEF)
6422     V2 = V1;
6423
6424   // v4i32 or v4f32
6425   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6426 }
6427
6428 static
6429 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6430   SDValue V1 = Op.getOperand(0);
6431   SDValue V2 = Op.getOperand(1);
6432   EVT VT = Op.getValueType();
6433   unsigned NumElems = VT.getVectorNumElements();
6434
6435   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6436   // operand of these instructions is only memory, so check if there's a
6437   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6438   // same masks.
6439   bool CanFoldLoad = false;
6440
6441   // Trivial case, when V2 comes from a load.
6442   if (MayFoldVectorLoad(V2))
6443     CanFoldLoad = true;
6444
6445   // When V1 is a load, it can be folded later into a store in isel, example:
6446   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6447   //    turns into:
6448   //  (MOVLPSmr addr:$src1, VR128:$src2)
6449   // So, recognize this potential and also use MOVLPS or MOVLPD
6450   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6451     CanFoldLoad = true;
6452
6453   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6454   if (CanFoldLoad) {
6455     if (HasSSE2 && NumElems == 2)
6456       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6457
6458     if (NumElems == 4)
6459       // If we don't care about the second element, proceed to use movss.
6460       if (SVOp->getMaskElt(1) != -1)
6461         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6462   }
6463
6464   // movl and movlp will both match v2i64, but v2i64 is never matched by
6465   // movl earlier because we make it strict to avoid messing with the movlp load
6466   // folding logic (see the code above getMOVLP call). Match it here then,
6467   // this is horrible, but will stay like this until we move all shuffle
6468   // matching to x86 specific nodes. Note that for the 1st condition all
6469   // types are matched with movsd.
6470   if (HasSSE2) {
6471     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6472     // as to remove this logic from here, as much as possible
6473     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6474       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6475     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6476   }
6477
6478   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6479
6480   // Invert the operand order and use SHUFPS to match it.
6481   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6482                               getShuffleSHUFImmediate(SVOp), DAG);
6483 }
6484
6485 SDValue
6486 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6488   EVT VT = Op.getValueType();
6489   DebugLoc dl = Op.getDebugLoc();
6490   SDValue V1 = Op.getOperand(0);
6491   SDValue V2 = Op.getOperand(1);
6492
6493   if (isZeroShuffle(SVOp))
6494     return getZeroVector(VT, Subtarget, DAG, dl);
6495
6496   // Handle splat operations
6497   if (SVOp->isSplat()) {
6498     unsigned NumElem = VT.getVectorNumElements();
6499     int Size = VT.getSizeInBits();
6500
6501     // Use vbroadcast whenever the splat comes from a foldable load
6502     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6503     if (Broadcast.getNode())
6504       return Broadcast;
6505
6506     // Handle splats by matching through known shuffle masks
6507     if ((Size == 128 && NumElem <= 4) ||
6508         (Size == 256 && NumElem < 8))
6509       return SDValue();
6510
6511     // All remaning splats are promoted to target supported vector shuffles.
6512     return PromoteSplat(SVOp, DAG);
6513   }
6514
6515   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6516   // do it!
6517   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6518       VT == MVT::v16i16 || VT == MVT::v32i8) {
6519     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6520     if (NewOp.getNode())
6521       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6522   } else if ((VT == MVT::v4i32 ||
6523              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6524     // FIXME: Figure out a cleaner way to do this.
6525     // Try to make use of movq to zero out the top part.
6526     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6527       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6528       if (NewOp.getNode()) {
6529         EVT NewVT = NewOp.getValueType();
6530         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6531                                NewVT, true, false))
6532           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6533                               DAG, Subtarget, dl);
6534       }
6535     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6536       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6537       if (NewOp.getNode()) {
6538         EVT NewVT = NewOp.getValueType();
6539         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6540           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6541                               DAG, Subtarget, dl);
6542       }
6543     }
6544   }
6545   return SDValue();
6546 }
6547
6548 SDValue
6549 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6550   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6551   SDValue V1 = Op.getOperand(0);
6552   SDValue V2 = Op.getOperand(1);
6553   EVT VT = Op.getValueType();
6554   DebugLoc dl = Op.getDebugLoc();
6555   unsigned NumElems = VT.getVectorNumElements();
6556   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6557   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6558   bool V1IsSplat = false;
6559   bool V2IsSplat = false;
6560   bool HasSSE2 = Subtarget->hasSSE2();
6561   bool HasAVX    = Subtarget->hasAVX();
6562   bool HasAVX2   = Subtarget->hasAVX2();
6563   MachineFunction &MF = DAG.getMachineFunction();
6564   bool OptForSize = MF.getFunction()->getFnAttributes().
6565     hasAttribute(Attributes::OptimizeForSize);
6566
6567   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6568
6569   if (V1IsUndef && V2IsUndef)
6570     return DAG.getUNDEF(VT);
6571
6572   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6573
6574   // Vector shuffle lowering takes 3 steps:
6575   //
6576   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6577   //    narrowing and commutation of operands should be handled.
6578   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6579   //    shuffle nodes.
6580   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6581   //    so the shuffle can be broken into other shuffles and the legalizer can
6582   //    try the lowering again.
6583   //
6584   // The general idea is that no vector_shuffle operation should be left to
6585   // be matched during isel, all of them must be converted to a target specific
6586   // node here.
6587
6588   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6589   // narrowing and commutation of operands should be handled. The actual code
6590   // doesn't include all of those, work in progress...
6591   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6592   if (NewOp.getNode())
6593     return NewOp;
6594
6595   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6596
6597   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6598   // unpckh_undef). Only use pshufd if speed is more important than size.
6599   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6600     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6601   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6602     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6603
6604   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6605       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6606     return getMOVDDup(Op, dl, V1, DAG);
6607
6608   if (isMOVHLPS_v_undef_Mask(M, VT))
6609     return getMOVHighToLow(Op, dl, DAG);
6610
6611   // Use to match splats
6612   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6613       (VT == MVT::v2f64 || VT == MVT::v2i64))
6614     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6615
6616   if (isPSHUFDMask(M, VT)) {
6617     // The actual implementation will match the mask in the if above and then
6618     // during isel it can match several different instructions, not only pshufd
6619     // as its name says, sad but true, emulate the behavior for now...
6620     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6621       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6622
6623     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6624
6625     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6626       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6627
6628     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6629       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6630
6631     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6632                                 TargetMask, DAG);
6633   }
6634
6635   // Check if this can be converted into a logical shift.
6636   bool isLeft = false;
6637   unsigned ShAmt = 0;
6638   SDValue ShVal;
6639   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6640   if (isShift && ShVal.hasOneUse()) {
6641     // If the shifted value has multiple uses, it may be cheaper to use
6642     // v_set0 + movlhps or movhlps, etc.
6643     EVT EltVT = VT.getVectorElementType();
6644     ShAmt *= EltVT.getSizeInBits();
6645     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6646   }
6647
6648   if (isMOVLMask(M, VT)) {
6649     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6650       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6651     if (!isMOVLPMask(M, VT)) {
6652       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6653         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6654
6655       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6656         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6657     }
6658   }
6659
6660   // FIXME: fold these into legal mask.
6661   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6662     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6663
6664   if (isMOVHLPSMask(M, VT))
6665     return getMOVHighToLow(Op, dl, DAG);
6666
6667   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6668     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6669
6670   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6671     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6672
6673   if (isMOVLPMask(M, VT))
6674     return getMOVLP(Op, dl, DAG, HasSSE2);
6675
6676   if (ShouldXformToMOVHLPS(M, VT) ||
6677       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6678     return CommuteVectorShuffle(SVOp, DAG);
6679
6680   if (isShift) {
6681     // No better options. Use a vshldq / vsrldq.
6682     EVT EltVT = VT.getVectorElementType();
6683     ShAmt *= EltVT.getSizeInBits();
6684     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6685   }
6686
6687   bool Commuted = false;
6688   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6689   // 1,1,1,1 -> v8i16 though.
6690   V1IsSplat = isSplatVector(V1.getNode());
6691   V2IsSplat = isSplatVector(V2.getNode());
6692
6693   // Canonicalize the splat or undef, if present, to be on the RHS.
6694   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6695     CommuteVectorShuffleMask(M, NumElems);
6696     std::swap(V1, V2);
6697     std::swap(V1IsSplat, V2IsSplat);
6698     Commuted = true;
6699   }
6700
6701   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6702     // Shuffling low element of v1 into undef, just return v1.
6703     if (V2IsUndef)
6704       return V1;
6705     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6706     // the instruction selector will not match, so get a canonical MOVL with
6707     // swapped operands to undo the commute.
6708     return getMOVL(DAG, dl, VT, V2, V1);
6709   }
6710
6711   if (isUNPCKLMask(M, VT, HasAVX2))
6712     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6713
6714   if (isUNPCKHMask(M, VT, HasAVX2))
6715     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6716
6717   if (V2IsSplat) {
6718     // Normalize mask so all entries that point to V2 points to its first
6719     // element then try to match unpck{h|l} again. If match, return a
6720     // new vector_shuffle with the corrected mask.p
6721     SmallVector<int, 8> NewMask(M.begin(), M.end());
6722     NormalizeMask(NewMask, NumElems);
6723     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6724       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6725     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6726       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6727   }
6728
6729   if (Commuted) {
6730     // Commute is back and try unpck* again.
6731     // FIXME: this seems wrong.
6732     CommuteVectorShuffleMask(M, NumElems);
6733     std::swap(V1, V2);
6734     std::swap(V1IsSplat, V2IsSplat);
6735     Commuted = false;
6736
6737     if (isUNPCKLMask(M, VT, HasAVX2))
6738       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6739
6740     if (isUNPCKHMask(M, VT, HasAVX2))
6741       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6742   }
6743
6744   // Normalize the node to match x86 shuffle ops if needed
6745   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6746     return CommuteVectorShuffle(SVOp, DAG);
6747
6748   // The checks below are all present in isShuffleMaskLegal, but they are
6749   // inlined here right now to enable us to directly emit target specific
6750   // nodes, and remove one by one until they don't return Op anymore.
6751
6752   if (isPALIGNRMask(M, VT, Subtarget))
6753     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6754                                 getShufflePALIGNRImmediate(SVOp),
6755                                 DAG);
6756
6757   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6758       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6759     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6760       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6761   }
6762
6763   if (isPSHUFHWMask(M, VT, HasAVX2))
6764     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6765                                 getShufflePSHUFHWImmediate(SVOp),
6766                                 DAG);
6767
6768   if (isPSHUFLWMask(M, VT, HasAVX2))
6769     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6770                                 getShufflePSHUFLWImmediate(SVOp),
6771                                 DAG);
6772
6773   if (isSHUFPMask(M, VT, HasAVX))
6774     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6775                                 getShuffleSHUFImmediate(SVOp), DAG);
6776
6777   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6778     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6779   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6780     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6781
6782   //===--------------------------------------------------------------------===//
6783   // Generate target specific nodes for 128 or 256-bit shuffles only
6784   // supported in the AVX instruction set.
6785   //
6786
6787   // Handle VMOVDDUPY permutations
6788   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6789     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6790
6791   // Handle VPERMILPS/D* permutations
6792   if (isVPERMILPMask(M, VT, HasAVX)) {
6793     if (HasAVX2 && VT == MVT::v8i32)
6794       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6795                                   getShuffleSHUFImmediate(SVOp), DAG);
6796     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6797                                 getShuffleSHUFImmediate(SVOp), DAG);
6798   }
6799
6800   // Handle VPERM2F128/VPERM2I128 permutations
6801   if (isVPERM2X128Mask(M, VT, HasAVX))
6802     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6803                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6804
6805   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6806   if (BlendOp.getNode())
6807     return BlendOp;
6808
6809   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6810     SmallVector<SDValue, 8> permclMask;
6811     for (unsigned i = 0; i != 8; ++i) {
6812       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6813     }
6814     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6815                                &permclMask[0], 8);
6816     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6817     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6818                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6819   }
6820
6821   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6822     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6823                                 getShuffleCLImmediate(SVOp), DAG);
6824
6825
6826   //===--------------------------------------------------------------------===//
6827   // Since no target specific shuffle was selected for this generic one,
6828   // lower it into other known shuffles. FIXME: this isn't true yet, but
6829   // this is the plan.
6830   //
6831
6832   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6833   if (VT == MVT::v8i16) {
6834     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6835     if (NewOp.getNode())
6836       return NewOp;
6837   }
6838
6839   if (VT == MVT::v16i8) {
6840     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6841     if (NewOp.getNode())
6842       return NewOp;
6843   }
6844
6845   if (VT == MVT::v32i8) {
6846     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6847     if (NewOp.getNode())
6848       return NewOp;
6849   }
6850
6851   // Handle all 128-bit wide vectors with 4 elements, and match them with
6852   // several different shuffle types.
6853   if (NumElems == 4 && VT.is128BitVector())
6854     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6855
6856   // Handle general 256-bit shuffles
6857   if (VT.is256BitVector())
6858     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6859
6860   return SDValue();
6861 }
6862
6863 SDValue
6864 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6865                                                 SelectionDAG &DAG) const {
6866   EVT VT = Op.getValueType();
6867   DebugLoc dl = Op.getDebugLoc();
6868
6869   if (!Op.getOperand(0).getValueType().is128BitVector())
6870     return SDValue();
6871
6872   if (VT.getSizeInBits() == 8) {
6873     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6874                                   Op.getOperand(0), Op.getOperand(1));
6875     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6876                                   DAG.getValueType(VT));
6877     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6878   }
6879
6880   if (VT.getSizeInBits() == 16) {
6881     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6882     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6883     if (Idx == 0)
6884       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6885                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6886                                      DAG.getNode(ISD::BITCAST, dl,
6887                                                  MVT::v4i32,
6888                                                  Op.getOperand(0)),
6889                                      Op.getOperand(1)));
6890     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6891                                   Op.getOperand(0), Op.getOperand(1));
6892     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6893                                   DAG.getValueType(VT));
6894     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6895   }
6896
6897   if (VT == MVT::f32) {
6898     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6899     // the result back to FR32 register. It's only worth matching if the
6900     // result has a single use which is a store or a bitcast to i32.  And in
6901     // the case of a store, it's not worth it if the index is a constant 0,
6902     // because a MOVSSmr can be used instead, which is smaller and faster.
6903     if (!Op.hasOneUse())
6904       return SDValue();
6905     SDNode *User = *Op.getNode()->use_begin();
6906     if ((User->getOpcode() != ISD::STORE ||
6907          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6908           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6909         (User->getOpcode() != ISD::BITCAST ||
6910          User->getValueType(0) != MVT::i32))
6911       return SDValue();
6912     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6913                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6914                                               Op.getOperand(0)),
6915                                               Op.getOperand(1));
6916     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6917   }
6918
6919   if (VT == MVT::i32 || VT == MVT::i64) {
6920     // ExtractPS/pextrq works with constant index.
6921     if (isa<ConstantSDNode>(Op.getOperand(1)))
6922       return Op;
6923   }
6924   return SDValue();
6925 }
6926
6927
6928 SDValue
6929 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6930                                            SelectionDAG &DAG) const {
6931   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6932     return SDValue();
6933
6934   SDValue Vec = Op.getOperand(0);
6935   EVT VecVT = Vec.getValueType();
6936
6937   // If this is a 256-bit vector result, first extract the 128-bit vector and
6938   // then extract the element from the 128-bit vector.
6939   if (VecVT.is256BitVector()) {
6940     DebugLoc dl = Op.getNode()->getDebugLoc();
6941     unsigned NumElems = VecVT.getVectorNumElements();
6942     SDValue Idx = Op.getOperand(1);
6943     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6944
6945     // Get the 128-bit vector.
6946     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6947
6948     if (IdxVal >= NumElems/2)
6949       IdxVal -= NumElems/2;
6950     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6951                        DAG.getConstant(IdxVal, MVT::i32));
6952   }
6953
6954   assert(VecVT.is128BitVector() && "Unexpected vector length");
6955
6956   if (Subtarget->hasSSE41()) {
6957     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6958     if (Res.getNode())
6959       return Res;
6960   }
6961
6962   EVT VT = Op.getValueType();
6963   DebugLoc dl = Op.getDebugLoc();
6964   // TODO: handle v16i8.
6965   if (VT.getSizeInBits() == 16) {
6966     SDValue Vec = Op.getOperand(0);
6967     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6968     if (Idx == 0)
6969       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6970                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6971                                      DAG.getNode(ISD::BITCAST, dl,
6972                                                  MVT::v4i32, Vec),
6973                                      Op.getOperand(1)));
6974     // Transform it so it match pextrw which produces a 32-bit result.
6975     EVT EltVT = MVT::i32;
6976     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6977                                   Op.getOperand(0), Op.getOperand(1));
6978     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6979                                   DAG.getValueType(VT));
6980     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6981   }
6982
6983   if (VT.getSizeInBits() == 32) {
6984     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6985     if (Idx == 0)
6986       return Op;
6987
6988     // SHUFPS the element to the lowest double word, then movss.
6989     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6990     EVT VVT = Op.getOperand(0).getValueType();
6991     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6992                                        DAG.getUNDEF(VVT), Mask);
6993     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6994                        DAG.getIntPtrConstant(0));
6995   }
6996
6997   if (VT.getSizeInBits() == 64) {
6998     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6999     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7000     //        to match extract_elt for f64.
7001     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7002     if (Idx == 0)
7003       return Op;
7004
7005     // UNPCKHPD the element to the lowest double word, then movsd.
7006     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7007     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7008     int Mask[2] = { 1, -1 };
7009     EVT VVT = Op.getOperand(0).getValueType();
7010     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7011                                        DAG.getUNDEF(VVT), Mask);
7012     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7013                        DAG.getIntPtrConstant(0));
7014   }
7015
7016   return SDValue();
7017 }
7018
7019 SDValue
7020 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7021                                                SelectionDAG &DAG) const {
7022   EVT VT = Op.getValueType();
7023   EVT EltVT = VT.getVectorElementType();
7024   DebugLoc dl = Op.getDebugLoc();
7025
7026   SDValue N0 = Op.getOperand(0);
7027   SDValue N1 = Op.getOperand(1);
7028   SDValue N2 = Op.getOperand(2);
7029
7030   if (!VT.is128BitVector())
7031     return SDValue();
7032
7033   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7034       isa<ConstantSDNode>(N2)) {
7035     unsigned Opc;
7036     if (VT == MVT::v8i16)
7037       Opc = X86ISD::PINSRW;
7038     else if (VT == MVT::v16i8)
7039       Opc = X86ISD::PINSRB;
7040     else
7041       Opc = X86ISD::PINSRB;
7042
7043     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7044     // argument.
7045     if (N1.getValueType() != MVT::i32)
7046       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7047     if (N2.getValueType() != MVT::i32)
7048       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7049     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7050   }
7051
7052   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7053     // Bits [7:6] of the constant are the source select.  This will always be
7054     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7055     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7056     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7057     // Bits [5:4] of the constant are the destination select.  This is the
7058     //  value of the incoming immediate.
7059     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7060     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7061     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7062     // Create this as a scalar to vector..
7063     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7064     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7065   }
7066
7067   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7068     // PINSR* works with constant index.
7069     return Op;
7070   }
7071   return SDValue();
7072 }
7073
7074 SDValue
7075 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7076   EVT VT = Op.getValueType();
7077   EVT EltVT = VT.getVectorElementType();
7078
7079   DebugLoc dl = Op.getDebugLoc();
7080   SDValue N0 = Op.getOperand(0);
7081   SDValue N1 = Op.getOperand(1);
7082   SDValue N2 = Op.getOperand(2);
7083
7084   // If this is a 256-bit vector result, first extract the 128-bit vector,
7085   // insert the element into the extracted half and then place it back.
7086   if (VT.is256BitVector()) {
7087     if (!isa<ConstantSDNode>(N2))
7088       return SDValue();
7089
7090     // Get the desired 128-bit vector half.
7091     unsigned NumElems = VT.getVectorNumElements();
7092     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7093     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7094
7095     // Insert the element into the desired half.
7096     bool Upper = IdxVal >= NumElems/2;
7097     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7098                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7099
7100     // Insert the changed part back to the 256-bit vector
7101     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7102   }
7103
7104   if (Subtarget->hasSSE41())
7105     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7106
7107   if (EltVT == MVT::i8)
7108     return SDValue();
7109
7110   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7111     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7112     // as its second argument.
7113     if (N1.getValueType() != MVT::i32)
7114       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7115     if (N2.getValueType() != MVT::i32)
7116       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7117     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7118   }
7119   return SDValue();
7120 }
7121
7122 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7123   LLVMContext *Context = DAG.getContext();
7124   DebugLoc dl = Op.getDebugLoc();
7125   EVT OpVT = Op.getValueType();
7126
7127   // If this is a 256-bit vector result, first insert into a 128-bit
7128   // vector and then insert into the 256-bit vector.
7129   if (!OpVT.is128BitVector()) {
7130     // Insert into a 128-bit vector.
7131     EVT VT128 = EVT::getVectorVT(*Context,
7132                                  OpVT.getVectorElementType(),
7133                                  OpVT.getVectorNumElements() / 2);
7134
7135     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7136
7137     // Insert the 128-bit vector.
7138     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7139   }
7140
7141   if (OpVT == MVT::v1i64 &&
7142       Op.getOperand(0).getValueType() == MVT::i64)
7143     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7144
7145   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7146   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7147   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7148                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7149 }
7150
7151 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7152 // a simple subregister reference or explicit instructions to grab
7153 // upper bits of a vector.
7154 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7155                                       SelectionDAG &DAG) {
7156   if (Subtarget->hasAVX()) {
7157     DebugLoc dl = Op.getNode()->getDebugLoc();
7158     SDValue Vec = Op.getNode()->getOperand(0);
7159     SDValue Idx = Op.getNode()->getOperand(1);
7160
7161     if (Op.getNode()->getValueType(0).is128BitVector() &&
7162         Vec.getNode()->getValueType(0).is256BitVector() &&
7163         isa<ConstantSDNode>(Idx)) {
7164       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7165       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7166     }
7167   }
7168   return SDValue();
7169 }
7170
7171 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7172 // simple superregister reference or explicit instructions to insert
7173 // the upper bits of a vector.
7174 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7175                                      SelectionDAG &DAG) {
7176   if (Subtarget->hasAVX()) {
7177     DebugLoc dl = Op.getNode()->getDebugLoc();
7178     SDValue Vec = Op.getNode()->getOperand(0);
7179     SDValue SubVec = Op.getNode()->getOperand(1);
7180     SDValue Idx = Op.getNode()->getOperand(2);
7181
7182     if (Op.getNode()->getValueType(0).is256BitVector() &&
7183         SubVec.getNode()->getValueType(0).is128BitVector() &&
7184         isa<ConstantSDNode>(Idx)) {
7185       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7186       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7187     }
7188   }
7189   return SDValue();
7190 }
7191
7192 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7193 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7194 // one of the above mentioned nodes. It has to be wrapped because otherwise
7195 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7196 // be used to form addressing mode. These wrapped nodes will be selected
7197 // into MOV32ri.
7198 SDValue
7199 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7200   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7201
7202   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7203   // global base reg.
7204   unsigned char OpFlag = 0;
7205   unsigned WrapperKind = X86ISD::Wrapper;
7206   CodeModel::Model M = getTargetMachine().getCodeModel();
7207
7208   if (Subtarget->isPICStyleRIPRel() &&
7209       (M == CodeModel::Small || M == CodeModel::Kernel))
7210     WrapperKind = X86ISD::WrapperRIP;
7211   else if (Subtarget->isPICStyleGOT())
7212     OpFlag = X86II::MO_GOTOFF;
7213   else if (Subtarget->isPICStyleStubPIC())
7214     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7215
7216   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7217                                              CP->getAlignment(),
7218                                              CP->getOffset(), OpFlag);
7219   DebugLoc DL = CP->getDebugLoc();
7220   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7221   // With PIC, the address is actually $g + Offset.
7222   if (OpFlag) {
7223     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7224                          DAG.getNode(X86ISD::GlobalBaseReg,
7225                                      DebugLoc(), getPointerTy()),
7226                          Result);
7227   }
7228
7229   return Result;
7230 }
7231
7232 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7233   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7234
7235   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7236   // global base reg.
7237   unsigned char OpFlag = 0;
7238   unsigned WrapperKind = X86ISD::Wrapper;
7239   CodeModel::Model M = getTargetMachine().getCodeModel();
7240
7241   if (Subtarget->isPICStyleRIPRel() &&
7242       (M == CodeModel::Small || M == CodeModel::Kernel))
7243     WrapperKind = X86ISD::WrapperRIP;
7244   else if (Subtarget->isPICStyleGOT())
7245     OpFlag = X86II::MO_GOTOFF;
7246   else if (Subtarget->isPICStyleStubPIC())
7247     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7248
7249   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7250                                           OpFlag);
7251   DebugLoc DL = JT->getDebugLoc();
7252   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7253
7254   // With PIC, the address is actually $g + Offset.
7255   if (OpFlag)
7256     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7257                          DAG.getNode(X86ISD::GlobalBaseReg,
7258                                      DebugLoc(), getPointerTy()),
7259                          Result);
7260
7261   return Result;
7262 }
7263
7264 SDValue
7265 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7266   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7267
7268   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7269   // global base reg.
7270   unsigned char OpFlag = 0;
7271   unsigned WrapperKind = X86ISD::Wrapper;
7272   CodeModel::Model M = getTargetMachine().getCodeModel();
7273
7274   if (Subtarget->isPICStyleRIPRel() &&
7275       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7276     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7277       OpFlag = X86II::MO_GOTPCREL;
7278     WrapperKind = X86ISD::WrapperRIP;
7279   } else if (Subtarget->isPICStyleGOT()) {
7280     OpFlag = X86II::MO_GOT;
7281   } else if (Subtarget->isPICStyleStubPIC()) {
7282     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7283   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7284     OpFlag = X86II::MO_DARWIN_NONLAZY;
7285   }
7286
7287   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7288
7289   DebugLoc DL = Op.getDebugLoc();
7290   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7291
7292
7293   // With PIC, the address is actually $g + Offset.
7294   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7295       !Subtarget->is64Bit()) {
7296     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7297                          DAG.getNode(X86ISD::GlobalBaseReg,
7298                                      DebugLoc(), getPointerTy()),
7299                          Result);
7300   }
7301
7302   // For symbols that require a load from a stub to get the address, emit the
7303   // load.
7304   if (isGlobalStubReference(OpFlag))
7305     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7306                          MachinePointerInfo::getGOT(), false, false, false, 0);
7307
7308   return Result;
7309 }
7310
7311 SDValue
7312 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7313   // Create the TargetBlockAddressAddress node.
7314   unsigned char OpFlags =
7315     Subtarget->ClassifyBlockAddressReference();
7316   CodeModel::Model M = getTargetMachine().getCodeModel();
7317   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7318   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7319   DebugLoc dl = Op.getDebugLoc();
7320   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7321                                              OpFlags);
7322
7323   if (Subtarget->isPICStyleRIPRel() &&
7324       (M == CodeModel::Small || M == CodeModel::Kernel))
7325     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7326   else
7327     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7328
7329   // With PIC, the address is actually $g + Offset.
7330   if (isGlobalRelativeToPICBase(OpFlags)) {
7331     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7332                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7333                          Result);
7334   }
7335
7336   return Result;
7337 }
7338
7339 SDValue
7340 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7341                                       int64_t Offset,
7342                                       SelectionDAG &DAG) const {
7343   // Create the TargetGlobalAddress node, folding in the constant
7344   // offset if it is legal.
7345   unsigned char OpFlags =
7346     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7347   CodeModel::Model M = getTargetMachine().getCodeModel();
7348   SDValue Result;
7349   if (OpFlags == X86II::MO_NO_FLAG &&
7350       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7351     // A direct static reference to a global.
7352     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7353     Offset = 0;
7354   } else {
7355     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7356   }
7357
7358   if (Subtarget->isPICStyleRIPRel() &&
7359       (M == CodeModel::Small || M == CodeModel::Kernel))
7360     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7361   else
7362     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7363
7364   // With PIC, the address is actually $g + Offset.
7365   if (isGlobalRelativeToPICBase(OpFlags)) {
7366     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7367                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7368                          Result);
7369   }
7370
7371   // For globals that require a load from a stub to get the address, emit the
7372   // load.
7373   if (isGlobalStubReference(OpFlags))
7374     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7375                          MachinePointerInfo::getGOT(), false, false, false, 0);
7376
7377   // If there was a non-zero offset that we didn't fold, create an explicit
7378   // addition for it.
7379   if (Offset != 0)
7380     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7381                          DAG.getConstant(Offset, getPointerTy()));
7382
7383   return Result;
7384 }
7385
7386 SDValue
7387 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7388   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7389   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7390   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7391 }
7392
7393 static SDValue
7394 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7395            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7396            unsigned char OperandFlags, bool LocalDynamic = false) {
7397   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7398   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7399   DebugLoc dl = GA->getDebugLoc();
7400   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7401                                            GA->getValueType(0),
7402                                            GA->getOffset(),
7403                                            OperandFlags);
7404
7405   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7406                                            : X86ISD::TLSADDR;
7407
7408   if (InFlag) {
7409     SDValue Ops[] = { Chain,  TGA, *InFlag };
7410     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7411   } else {
7412     SDValue Ops[]  = { Chain, TGA };
7413     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7414   }
7415
7416   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7417   MFI->setAdjustsStack(true);
7418
7419   SDValue Flag = Chain.getValue(1);
7420   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7421 }
7422
7423 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7424 static SDValue
7425 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7426                                 const EVT PtrVT) {
7427   SDValue InFlag;
7428   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7429   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7430                                    DAG.getNode(X86ISD::GlobalBaseReg,
7431                                                DebugLoc(), PtrVT), InFlag);
7432   InFlag = Chain.getValue(1);
7433
7434   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7435 }
7436
7437 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7438 static SDValue
7439 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7440                                 const EVT PtrVT) {
7441   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7442                     X86::RAX, X86II::MO_TLSGD);
7443 }
7444
7445 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7446                                            SelectionDAG &DAG,
7447                                            const EVT PtrVT,
7448                                            bool is64Bit) {
7449   DebugLoc dl = GA->getDebugLoc();
7450
7451   // Get the start address of the TLS block for this module.
7452   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7453       .getInfo<X86MachineFunctionInfo>();
7454   MFI->incNumLocalDynamicTLSAccesses();
7455
7456   SDValue Base;
7457   if (is64Bit) {
7458     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7459                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7460   } else {
7461     SDValue InFlag;
7462     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7463         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7464     InFlag = Chain.getValue(1);
7465     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7466                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7467   }
7468
7469   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7470   // of Base.
7471
7472   // Build x@dtpoff.
7473   unsigned char OperandFlags = X86II::MO_DTPOFF;
7474   unsigned WrapperKind = X86ISD::Wrapper;
7475   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7476                                            GA->getValueType(0),
7477                                            GA->getOffset(), OperandFlags);
7478   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7479
7480   // Add x@dtpoff with the base.
7481   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7482 }
7483
7484 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7485 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7486                                    const EVT PtrVT, TLSModel::Model model,
7487                                    bool is64Bit, bool isPIC) {
7488   DebugLoc dl = GA->getDebugLoc();
7489
7490   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7491   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7492                                                          is64Bit ? 257 : 256));
7493
7494   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7495                                       DAG.getIntPtrConstant(0),
7496                                       MachinePointerInfo(Ptr),
7497                                       false, false, false, 0);
7498
7499   unsigned char OperandFlags = 0;
7500   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7501   // initialexec.
7502   unsigned WrapperKind = X86ISD::Wrapper;
7503   if (model == TLSModel::LocalExec) {
7504     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7505   } else if (model == TLSModel::InitialExec) {
7506     if (is64Bit) {
7507       OperandFlags = X86II::MO_GOTTPOFF;
7508       WrapperKind = X86ISD::WrapperRIP;
7509     } else {
7510       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7511     }
7512   } else {
7513     llvm_unreachable("Unexpected model");
7514   }
7515
7516   // emit "addl x@ntpoff,%eax" (local exec)
7517   // or "addl x@indntpoff,%eax" (initial exec)
7518   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7519   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7520                                            GA->getValueType(0),
7521                                            GA->getOffset(), OperandFlags);
7522   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7523
7524   if (model == TLSModel::InitialExec) {
7525     if (isPIC && !is64Bit) {
7526       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7527                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7528                            Offset);
7529     }
7530
7531     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7532                          MachinePointerInfo::getGOT(), false, false, false,
7533                          0);
7534   }
7535
7536   // The address of the thread local variable is the add of the thread
7537   // pointer with the offset of the variable.
7538   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7539 }
7540
7541 SDValue
7542 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7543
7544   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7545   const GlobalValue *GV = GA->getGlobal();
7546
7547   if (Subtarget->isTargetELF()) {
7548     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7549
7550     switch (model) {
7551       case TLSModel::GeneralDynamic:
7552         if (Subtarget->is64Bit())
7553           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7554         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7555       case TLSModel::LocalDynamic:
7556         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7557                                            Subtarget->is64Bit());
7558       case TLSModel::InitialExec:
7559       case TLSModel::LocalExec:
7560         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7561                                    Subtarget->is64Bit(),
7562                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7563     }
7564     llvm_unreachable("Unknown TLS model.");
7565   }
7566
7567   if (Subtarget->isTargetDarwin()) {
7568     // Darwin only has one model of TLS.  Lower to that.
7569     unsigned char OpFlag = 0;
7570     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7571                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7572
7573     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7574     // global base reg.
7575     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7576                   !Subtarget->is64Bit();
7577     if (PIC32)
7578       OpFlag = X86II::MO_TLVP_PIC_BASE;
7579     else
7580       OpFlag = X86II::MO_TLVP;
7581     DebugLoc DL = Op.getDebugLoc();
7582     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7583                                                 GA->getValueType(0),
7584                                                 GA->getOffset(), OpFlag);
7585     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7586
7587     // With PIC32, the address is actually $g + Offset.
7588     if (PIC32)
7589       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7590                            DAG.getNode(X86ISD::GlobalBaseReg,
7591                                        DebugLoc(), getPointerTy()),
7592                            Offset);
7593
7594     // Lowering the machine isd will make sure everything is in the right
7595     // location.
7596     SDValue Chain = DAG.getEntryNode();
7597     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7598     SDValue Args[] = { Chain, Offset };
7599     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7600
7601     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7602     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7603     MFI->setAdjustsStack(true);
7604
7605     // And our return value (tls address) is in the standard call return value
7606     // location.
7607     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7608     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7609                               Chain.getValue(1));
7610   }
7611
7612   if (Subtarget->isTargetWindows()) {
7613     // Just use the implicit TLS architecture
7614     // Need to generate someting similar to:
7615     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7616     //                                  ; from TEB
7617     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7618     //   mov     rcx, qword [rdx+rcx*8]
7619     //   mov     eax, .tls$:tlsvar
7620     //   [rax+rcx] contains the address
7621     // Windows 64bit: gs:0x58
7622     // Windows 32bit: fs:__tls_array
7623
7624     // If GV is an alias then use the aliasee for determining
7625     // thread-localness.
7626     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7627       GV = GA->resolveAliasedGlobal(false);
7628     DebugLoc dl = GA->getDebugLoc();
7629     SDValue Chain = DAG.getEntryNode();
7630
7631     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7632     // %gs:0x58 (64-bit).
7633     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7634                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7635                                                              256)
7636                                         : Type::getInt32PtrTy(*DAG.getContext(),
7637                                                               257));
7638
7639     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7640                                         Subtarget->is64Bit()
7641                                         ? DAG.getIntPtrConstant(0x58)
7642                                         : DAG.getExternalSymbol("_tls_array",
7643                                                                 getPointerTy()),
7644                                         MachinePointerInfo(Ptr),
7645                                         false, false, false, 0);
7646
7647     // Load the _tls_index variable
7648     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7649     if (Subtarget->is64Bit())
7650       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7651                            IDX, MachinePointerInfo(), MVT::i32,
7652                            false, false, 0);
7653     else
7654       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7655                         false, false, false, 0);
7656
7657     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7658                                     getPointerTy());
7659     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7660
7661     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7662     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7663                       false, false, false, 0);
7664
7665     // Get the offset of start of .tls section
7666     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7667                                              GA->getValueType(0),
7668                                              GA->getOffset(), X86II::MO_SECREL);
7669     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7670
7671     // The address of the thread local variable is the add of the thread
7672     // pointer with the offset of the variable.
7673     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7674   }
7675
7676   llvm_unreachable("TLS not implemented for this target.");
7677 }
7678
7679
7680 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7681 /// and take a 2 x i32 value to shift plus a shift amount.
7682 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7683   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7684   EVT VT = Op.getValueType();
7685   unsigned VTBits = VT.getSizeInBits();
7686   DebugLoc dl = Op.getDebugLoc();
7687   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7688   SDValue ShOpLo = Op.getOperand(0);
7689   SDValue ShOpHi = Op.getOperand(1);
7690   SDValue ShAmt  = Op.getOperand(2);
7691   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7692                                      DAG.getConstant(VTBits - 1, MVT::i8))
7693                        : DAG.getConstant(0, VT);
7694
7695   SDValue Tmp2, Tmp3;
7696   if (Op.getOpcode() == ISD::SHL_PARTS) {
7697     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7698     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7699   } else {
7700     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7701     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7702   }
7703
7704   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7705                                 DAG.getConstant(VTBits, MVT::i8));
7706   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7707                              AndNode, DAG.getConstant(0, MVT::i8));
7708
7709   SDValue Hi, Lo;
7710   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7711   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7712   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7713
7714   if (Op.getOpcode() == ISD::SHL_PARTS) {
7715     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7716     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7717   } else {
7718     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7719     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7720   }
7721
7722   SDValue Ops[2] = { Lo, Hi };
7723   return DAG.getMergeValues(Ops, 2, dl);
7724 }
7725
7726 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7727                                            SelectionDAG &DAG) const {
7728   EVT SrcVT = Op.getOperand(0).getValueType();
7729
7730   if (SrcVT.isVector())
7731     return SDValue();
7732
7733   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7734          "Unknown SINT_TO_FP to lower!");
7735
7736   // These are really Legal; return the operand so the caller accepts it as
7737   // Legal.
7738   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7739     return Op;
7740   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7741       Subtarget->is64Bit()) {
7742     return Op;
7743   }
7744
7745   DebugLoc dl = Op.getDebugLoc();
7746   unsigned Size = SrcVT.getSizeInBits()/8;
7747   MachineFunction &MF = DAG.getMachineFunction();
7748   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7749   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7750   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7751                                StackSlot,
7752                                MachinePointerInfo::getFixedStack(SSFI),
7753                                false, false, 0);
7754   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7755 }
7756
7757 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7758                                      SDValue StackSlot,
7759                                      SelectionDAG &DAG) const {
7760   // Build the FILD
7761   DebugLoc DL = Op.getDebugLoc();
7762   SDVTList Tys;
7763   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7764   if (useSSE)
7765     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7766   else
7767     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7768
7769   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7770
7771   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7772   MachineMemOperand *MMO;
7773   if (FI) {
7774     int SSFI = FI->getIndex();
7775     MMO =
7776       DAG.getMachineFunction()
7777       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7778                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7779   } else {
7780     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7781     StackSlot = StackSlot.getOperand(1);
7782   }
7783   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7784   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7785                                            X86ISD::FILD, DL,
7786                                            Tys, Ops, array_lengthof(Ops),
7787                                            SrcVT, MMO);
7788
7789   if (useSSE) {
7790     Chain = Result.getValue(1);
7791     SDValue InFlag = Result.getValue(2);
7792
7793     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7794     // shouldn't be necessary except that RFP cannot be live across
7795     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7796     MachineFunction &MF = DAG.getMachineFunction();
7797     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7798     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7799     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7800     Tys = DAG.getVTList(MVT::Other);
7801     SDValue Ops[] = {
7802       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7803     };
7804     MachineMemOperand *MMO =
7805       DAG.getMachineFunction()
7806       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7807                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7808
7809     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7810                                     Ops, array_lengthof(Ops),
7811                                     Op.getValueType(), MMO);
7812     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7813                          MachinePointerInfo::getFixedStack(SSFI),
7814                          false, false, false, 0);
7815   }
7816
7817   return Result;
7818 }
7819
7820 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7821 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7822                                                SelectionDAG &DAG) const {
7823   // This algorithm is not obvious. Here it is what we're trying to output:
7824   /*
7825      movq       %rax,  %xmm0
7826      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7827      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7828      #ifdef __SSE3__
7829        haddpd   %xmm0, %xmm0
7830      #else
7831        pshufd   $0x4e, %xmm0, %xmm1
7832        addpd    %xmm1, %xmm0
7833      #endif
7834   */
7835
7836   DebugLoc dl = Op.getDebugLoc();
7837   LLVMContext *Context = DAG.getContext();
7838
7839   // Build some magic constants.
7840   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7841   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7842   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7843
7844   SmallVector<Constant*,2> CV1;
7845   CV1.push_back(
7846         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7847   CV1.push_back(
7848         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7849   Constant *C1 = ConstantVector::get(CV1);
7850   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7851
7852   // Load the 64-bit value into an XMM register.
7853   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7854                             Op.getOperand(0));
7855   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7856                               MachinePointerInfo::getConstantPool(),
7857                               false, false, false, 16);
7858   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7859                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7860                               CLod0);
7861
7862   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7863                               MachinePointerInfo::getConstantPool(),
7864                               false, false, false, 16);
7865   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7866   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7867   SDValue Result;
7868
7869   if (Subtarget->hasSSE3()) {
7870     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7871     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7872   } else {
7873     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7874     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7875                                            S2F, 0x4E, DAG);
7876     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7877                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7878                          Sub);
7879   }
7880
7881   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7882                      DAG.getIntPtrConstant(0));
7883 }
7884
7885 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7886 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7887                                                SelectionDAG &DAG) const {
7888   DebugLoc dl = Op.getDebugLoc();
7889   // FP constant to bias correct the final result.
7890   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7891                                    MVT::f64);
7892
7893   // Load the 32-bit value into an XMM register.
7894   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7895                              Op.getOperand(0));
7896
7897   // Zero out the upper parts of the register.
7898   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7899
7900   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7901                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7902                      DAG.getIntPtrConstant(0));
7903
7904   // Or the load with the bias.
7905   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7906                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7907                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7908                                                    MVT::v2f64, Load)),
7909                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7910                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7911                                                    MVT::v2f64, Bias)));
7912   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7913                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7914                    DAG.getIntPtrConstant(0));
7915
7916   // Subtract the bias.
7917   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7918
7919   // Handle final rounding.
7920   EVT DestVT = Op.getValueType();
7921
7922   if (DestVT.bitsLT(MVT::f64))
7923     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7924                        DAG.getIntPtrConstant(0));
7925   if (DestVT.bitsGT(MVT::f64))
7926     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7927
7928   // Handle final rounding.
7929   return Sub;
7930 }
7931
7932 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7933                                            SelectionDAG &DAG) const {
7934   SDValue N0 = Op.getOperand(0);
7935   DebugLoc dl = Op.getDebugLoc();
7936
7937   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7938   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7939   // the optimization here.
7940   if (DAG.SignBitIsZero(N0))
7941     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7942
7943   EVT SrcVT = N0.getValueType();
7944   EVT DstVT = Op.getValueType();
7945   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7946     return LowerUINT_TO_FP_i64(Op, DAG);
7947   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7948     return LowerUINT_TO_FP_i32(Op, DAG);
7949   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7950     return SDValue();
7951
7952   // Make a 64-bit buffer, and use it to build an FILD.
7953   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7954   if (SrcVT == MVT::i32) {
7955     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7956     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7957                                      getPointerTy(), StackSlot, WordOff);
7958     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7959                                   StackSlot, MachinePointerInfo(),
7960                                   false, false, 0);
7961     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7962                                   OffsetSlot, MachinePointerInfo(),
7963                                   false, false, 0);
7964     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7965     return Fild;
7966   }
7967
7968   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7969   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7970                                StackSlot, MachinePointerInfo(),
7971                                false, false, 0);
7972   // For i64 source, we need to add the appropriate power of 2 if the input
7973   // was negative.  This is the same as the optimization in
7974   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7975   // we must be careful to do the computation in x87 extended precision, not
7976   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7977   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7978   MachineMemOperand *MMO =
7979     DAG.getMachineFunction()
7980     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7981                           MachineMemOperand::MOLoad, 8, 8);
7982
7983   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7984   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7985   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7986                                          MVT::i64, MMO);
7987
7988   APInt FF(32, 0x5F800000ULL);
7989
7990   // Check whether the sign bit is set.
7991   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7992                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7993                                  ISD::SETLT);
7994
7995   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7996   SDValue FudgePtr = DAG.getConstantPool(
7997                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7998                                          getPointerTy());
7999
8000   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8001   SDValue Zero = DAG.getIntPtrConstant(0);
8002   SDValue Four = DAG.getIntPtrConstant(4);
8003   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8004                                Zero, Four);
8005   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8006
8007   // Load the value out, extending it from f32 to f80.
8008   // FIXME: Avoid the extend by constructing the right constant pool?
8009   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8010                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8011                                  MVT::f32, false, false, 4);
8012   // Extend everything to 80 bits to force it to be done on x87.
8013   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8014   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8015 }
8016
8017 std::pair<SDValue,SDValue> X86TargetLowering::
8018 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8019   DebugLoc DL = Op.getDebugLoc();
8020
8021   EVT DstTy = Op.getValueType();
8022
8023   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8024     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8025     DstTy = MVT::i64;
8026   }
8027
8028   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8029          DstTy.getSimpleVT() >= MVT::i16 &&
8030          "Unknown FP_TO_INT to lower!");
8031
8032   // These are really Legal.
8033   if (DstTy == MVT::i32 &&
8034       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8035     return std::make_pair(SDValue(), SDValue());
8036   if (Subtarget->is64Bit() &&
8037       DstTy == MVT::i64 &&
8038       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8039     return std::make_pair(SDValue(), SDValue());
8040
8041   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8042   // stack slot, or into the FTOL runtime function.
8043   MachineFunction &MF = DAG.getMachineFunction();
8044   unsigned MemSize = DstTy.getSizeInBits()/8;
8045   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8046   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8047
8048   unsigned Opc;
8049   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8050     Opc = X86ISD::WIN_FTOL;
8051   else
8052     switch (DstTy.getSimpleVT().SimpleTy) {
8053     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8054     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8055     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8056     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8057     }
8058
8059   SDValue Chain = DAG.getEntryNode();
8060   SDValue Value = Op.getOperand(0);
8061   EVT TheVT = Op.getOperand(0).getValueType();
8062   // FIXME This causes a redundant load/store if the SSE-class value is already
8063   // in memory, such as if it is on the callstack.
8064   if (isScalarFPTypeInSSEReg(TheVT)) {
8065     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8066     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8067                          MachinePointerInfo::getFixedStack(SSFI),
8068                          false, false, 0);
8069     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8070     SDValue Ops[] = {
8071       Chain, StackSlot, DAG.getValueType(TheVT)
8072     };
8073
8074     MachineMemOperand *MMO =
8075       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8076                               MachineMemOperand::MOLoad, MemSize, MemSize);
8077     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8078                                     DstTy, MMO);
8079     Chain = Value.getValue(1);
8080     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8081     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8082   }
8083
8084   MachineMemOperand *MMO =
8085     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8086                             MachineMemOperand::MOStore, MemSize, MemSize);
8087
8088   if (Opc != X86ISD::WIN_FTOL) {
8089     // Build the FP_TO_INT*_IN_MEM
8090     SDValue Ops[] = { Chain, Value, StackSlot };
8091     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8092                                            Ops, 3, DstTy, MMO);
8093     return std::make_pair(FIST, StackSlot);
8094   } else {
8095     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8096       DAG.getVTList(MVT::Other, MVT::Glue),
8097       Chain, Value);
8098     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8099       MVT::i32, ftol.getValue(1));
8100     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8101       MVT::i32, eax.getValue(2));
8102     SDValue Ops[] = { eax, edx };
8103     SDValue pair = IsReplace
8104       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8105       : DAG.getMergeValues(Ops, 2, DL);
8106     return std::make_pair(pair, SDValue());
8107   }
8108 }
8109
8110 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8111   DebugLoc DL = Op.getDebugLoc();
8112   EVT VT = Op.getValueType();
8113   EVT SVT = Op.getOperand(0).getValueType();
8114
8115   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8116       VT.getVectorNumElements() != SVT.getVectorNumElements())
8117     return SDValue();
8118
8119   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8120
8121   unsigned NumElems = VT.getVectorNumElements();
8122   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8123                              NumElems * 2);
8124
8125   SDValue In = Op.getOperand(0);
8126   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8127   // Prepare truncation shuffle mask
8128   for (unsigned i = 0; i != NumElems; ++i)
8129     MaskVec[i] = i * 2;
8130   SDValue V = DAG.getVectorShuffle(NVT, DL,
8131                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8132                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8133   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8134                      DAG.getIntPtrConstant(0));
8135 }
8136
8137 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8138                                            SelectionDAG &DAG) const {
8139   if (Op.getValueType().isVector()) {
8140     if (Op.getValueType() == MVT::v8i16)
8141       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8142                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8143                                      MVT::v8i32, Op.getOperand(0)));
8144     return SDValue();
8145   }
8146
8147   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8148     /*IsSigned=*/ true, /*IsReplace=*/ false);
8149   SDValue FIST = Vals.first, StackSlot = Vals.second;
8150   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8151   if (FIST.getNode() == 0) return Op;
8152
8153   if (StackSlot.getNode())
8154     // Load the result.
8155     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8156                        FIST, StackSlot, MachinePointerInfo(),
8157                        false, false, false, 0);
8158
8159   // The node is the result.
8160   return FIST;
8161 }
8162
8163 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8164                                            SelectionDAG &DAG) const {
8165   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8166     /*IsSigned=*/ false, /*IsReplace=*/ false);
8167   SDValue FIST = Vals.first, StackSlot = Vals.second;
8168   assert(FIST.getNode() && "Unexpected failure");
8169
8170   if (StackSlot.getNode())
8171     // Load the result.
8172     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8173                        FIST, StackSlot, MachinePointerInfo(),
8174                        false, false, false, 0);
8175
8176   // The node is the result.
8177   return FIST;
8178 }
8179
8180 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8181                                           SelectionDAG &DAG) const {
8182   DebugLoc DL = Op.getDebugLoc();
8183   EVT VT = Op.getValueType();
8184   SDValue In = Op.getOperand(0);
8185   EVT SVT = In.getValueType();
8186
8187   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8188
8189   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8190                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8191                                  In, DAG.getUNDEF(SVT)));
8192 }
8193
8194 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8195   LLVMContext *Context = DAG.getContext();
8196   DebugLoc dl = Op.getDebugLoc();
8197   EVT VT = Op.getValueType();
8198   EVT EltVT = VT;
8199   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8200   if (VT.isVector()) {
8201     EltVT = VT.getVectorElementType();
8202     NumElts = VT.getVectorNumElements();
8203   }
8204   Constant *C;
8205   if (EltVT == MVT::f64)
8206     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8207   else
8208     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8209   C = ConstantVector::getSplat(NumElts, C);
8210   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8211   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8212   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8213                              MachinePointerInfo::getConstantPool(),
8214                              false, false, false, Alignment);
8215   if (VT.isVector()) {
8216     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8217     return DAG.getNode(ISD::BITCAST, dl, VT,
8218                        DAG.getNode(ISD::AND, dl, ANDVT,
8219                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8220                                                Op.getOperand(0)),
8221                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8222   }
8223   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8224 }
8225
8226 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8227   LLVMContext *Context = DAG.getContext();
8228   DebugLoc dl = Op.getDebugLoc();
8229   EVT VT = Op.getValueType();
8230   EVT EltVT = VT;
8231   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8232   if (VT.isVector()) {
8233     EltVT = VT.getVectorElementType();
8234     NumElts = VT.getVectorNumElements();
8235   }
8236   Constant *C;
8237   if (EltVT == MVT::f64)
8238     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8239   else
8240     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8241   C = ConstantVector::getSplat(NumElts, C);
8242   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8243   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8244   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8245                              MachinePointerInfo::getConstantPool(),
8246                              false, false, false, Alignment);
8247   if (VT.isVector()) {
8248     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8249     return DAG.getNode(ISD::BITCAST, dl, VT,
8250                        DAG.getNode(ISD::XOR, dl, XORVT,
8251                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8252                                                Op.getOperand(0)),
8253                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8254   }
8255
8256   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8257 }
8258
8259 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8260   LLVMContext *Context = DAG.getContext();
8261   SDValue Op0 = Op.getOperand(0);
8262   SDValue Op1 = Op.getOperand(1);
8263   DebugLoc dl = Op.getDebugLoc();
8264   EVT VT = Op.getValueType();
8265   EVT SrcVT = Op1.getValueType();
8266
8267   // If second operand is smaller, extend it first.
8268   if (SrcVT.bitsLT(VT)) {
8269     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8270     SrcVT = VT;
8271   }
8272   // And if it is bigger, shrink it first.
8273   if (SrcVT.bitsGT(VT)) {
8274     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8275     SrcVT = VT;
8276   }
8277
8278   // At this point the operands and the result should have the same
8279   // type, and that won't be f80 since that is not custom lowered.
8280
8281   // First get the sign bit of second operand.
8282   SmallVector<Constant*,4> CV;
8283   if (SrcVT == MVT::f64) {
8284     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8285     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8286   } else {
8287     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8288     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8289     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8290     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8291   }
8292   Constant *C = ConstantVector::get(CV);
8293   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8294   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8295                               MachinePointerInfo::getConstantPool(),
8296                               false, false, false, 16);
8297   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8298
8299   // Shift sign bit right or left if the two operands have different types.
8300   if (SrcVT.bitsGT(VT)) {
8301     // Op0 is MVT::f32, Op1 is MVT::f64.
8302     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8303     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8304                           DAG.getConstant(32, MVT::i32));
8305     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8306     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8307                           DAG.getIntPtrConstant(0));
8308   }
8309
8310   // Clear first operand sign bit.
8311   CV.clear();
8312   if (VT == MVT::f64) {
8313     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8314     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8315   } else {
8316     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8317     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8318     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8319     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8320   }
8321   C = ConstantVector::get(CV);
8322   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8323   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8324                               MachinePointerInfo::getConstantPool(),
8325                               false, false, false, 16);
8326   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8327
8328   // Or the value with the sign bit.
8329   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8330 }
8331
8332 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8333   SDValue N0 = Op.getOperand(0);
8334   DebugLoc dl = Op.getDebugLoc();
8335   EVT VT = Op.getValueType();
8336
8337   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8338   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8339                                   DAG.getConstant(1, VT));
8340   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8341 }
8342
8343 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8344 //
8345 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8346   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8347
8348   if (!Subtarget->hasSSE41())
8349     return SDValue();
8350
8351   if (!Op->hasOneUse())
8352     return SDValue();
8353
8354   SDNode *N = Op.getNode();
8355   DebugLoc DL = N->getDebugLoc();
8356
8357   SmallVector<SDValue, 8> Opnds;
8358   DenseMap<SDValue, unsigned> VecInMap;
8359   EVT VT = MVT::Other;
8360
8361   // Recognize a special case where a vector is casted into wide integer to
8362   // test all 0s.
8363   Opnds.push_back(N->getOperand(0));
8364   Opnds.push_back(N->getOperand(1));
8365
8366   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8367     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8368     // BFS traverse all OR'd operands.
8369     if (I->getOpcode() == ISD::OR) {
8370       Opnds.push_back(I->getOperand(0));
8371       Opnds.push_back(I->getOperand(1));
8372       // Re-evaluate the number of nodes to be traversed.
8373       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8374       continue;
8375     }
8376
8377     // Quit if a non-EXTRACT_VECTOR_ELT
8378     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8379       return SDValue();
8380
8381     // Quit if without a constant index.
8382     SDValue Idx = I->getOperand(1);
8383     if (!isa<ConstantSDNode>(Idx))
8384       return SDValue();
8385
8386     SDValue ExtractedFromVec = I->getOperand(0);
8387     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8388     if (M == VecInMap.end()) {
8389       VT = ExtractedFromVec.getValueType();
8390       // Quit if not 128/256-bit vector.
8391       if (!VT.is128BitVector() && !VT.is256BitVector())
8392         return SDValue();
8393       // Quit if not the same type.
8394       if (VecInMap.begin() != VecInMap.end() &&
8395           VT != VecInMap.begin()->first.getValueType())
8396         return SDValue();
8397       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8398     }
8399     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8400   }
8401
8402   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8403          "Not extracted from 128-/256-bit vector.");
8404
8405   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8406   SmallVector<SDValue, 8> VecIns;
8407
8408   for (DenseMap<SDValue, unsigned>::const_iterator
8409         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8410     // Quit if not all elements are used.
8411     if (I->second != FullMask)
8412       return SDValue();
8413     VecIns.push_back(I->first);
8414   }
8415
8416   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8417
8418   // Cast all vectors into TestVT for PTEST.
8419   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8420     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8421
8422   // If more than one full vectors are evaluated, OR them first before PTEST.
8423   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8424     // Each iteration will OR 2 nodes and append the result until there is only
8425     // 1 node left, i.e. the final OR'd value of all vectors.
8426     SDValue LHS = VecIns[Slot];
8427     SDValue RHS = VecIns[Slot + 1];
8428     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8429   }
8430
8431   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8432                      VecIns.back(), VecIns.back());
8433 }
8434
8435 /// Emit nodes that will be selected as "test Op0,Op0", or something
8436 /// equivalent.
8437 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8438                                     SelectionDAG &DAG) const {
8439   DebugLoc dl = Op.getDebugLoc();
8440
8441   // CF and OF aren't always set the way we want. Determine which
8442   // of these we need.
8443   bool NeedCF = false;
8444   bool NeedOF = false;
8445   switch (X86CC) {
8446   default: break;
8447   case X86::COND_A: case X86::COND_AE:
8448   case X86::COND_B: case X86::COND_BE:
8449     NeedCF = true;
8450     break;
8451   case X86::COND_G: case X86::COND_GE:
8452   case X86::COND_L: case X86::COND_LE:
8453   case X86::COND_O: case X86::COND_NO:
8454     NeedOF = true;
8455     break;
8456   }
8457
8458   // See if we can use the EFLAGS value from the operand instead of
8459   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8460   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8461   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8462     // Emit a CMP with 0, which is the TEST pattern.
8463     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8464                        DAG.getConstant(0, Op.getValueType()));
8465
8466   unsigned Opcode = 0;
8467   unsigned NumOperands = 0;
8468
8469   // Truncate operations may prevent the merge of the SETCC instruction
8470   // and the arithmetic intruction before it. Attempt to truncate the operands
8471   // of the arithmetic instruction and use a reduced bit-width instruction.
8472   bool NeedTruncation = false;
8473   SDValue ArithOp = Op;
8474   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8475     SDValue Arith = Op->getOperand(0);
8476     // Both the trunc and the arithmetic op need to have one user each.
8477     if (Arith->hasOneUse())
8478       switch (Arith.getOpcode()) {
8479         default: break;
8480         case ISD::ADD:
8481         case ISD::SUB:
8482         case ISD::AND:
8483         case ISD::OR:
8484         case ISD::XOR: {
8485           NeedTruncation = true;
8486           ArithOp = Arith;
8487         }
8488       }
8489   }
8490
8491   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8492   // which may be the result of a CAST.  We use the variable 'Op', which is the
8493   // non-casted variable when we check for possible users.
8494   switch (ArithOp.getOpcode()) {
8495   case ISD::ADD:
8496     // Due to an isel shortcoming, be conservative if this add is likely to be
8497     // selected as part of a load-modify-store instruction. When the root node
8498     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8499     // uses of other nodes in the match, such as the ADD in this case. This
8500     // leads to the ADD being left around and reselected, with the result being
8501     // two adds in the output.  Alas, even if none our users are stores, that
8502     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8503     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8504     // climbing the DAG back to the root, and it doesn't seem to be worth the
8505     // effort.
8506     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8507          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8508       if (UI->getOpcode() != ISD::CopyToReg &&
8509           UI->getOpcode() != ISD::SETCC &&
8510           UI->getOpcode() != ISD::STORE)
8511         goto default_case;
8512
8513     if (ConstantSDNode *C =
8514         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8515       // An add of one will be selected as an INC.
8516       if (C->getAPIntValue() == 1) {
8517         Opcode = X86ISD::INC;
8518         NumOperands = 1;
8519         break;
8520       }
8521
8522       // An add of negative one (subtract of one) will be selected as a DEC.
8523       if (C->getAPIntValue().isAllOnesValue()) {
8524         Opcode = X86ISD::DEC;
8525         NumOperands = 1;
8526         break;
8527       }
8528     }
8529
8530     // Otherwise use a regular EFLAGS-setting add.
8531     Opcode = X86ISD::ADD;
8532     NumOperands = 2;
8533     break;
8534   case ISD::AND: {
8535     // If the primary and result isn't used, don't bother using X86ISD::AND,
8536     // because a TEST instruction will be better.
8537     bool NonFlagUse = false;
8538     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8539            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8540       SDNode *User = *UI;
8541       unsigned UOpNo = UI.getOperandNo();
8542       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8543         // Look pass truncate.
8544         UOpNo = User->use_begin().getOperandNo();
8545         User = *User->use_begin();
8546       }
8547
8548       if (User->getOpcode() != ISD::BRCOND &&
8549           User->getOpcode() != ISD::SETCC &&
8550           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8551         NonFlagUse = true;
8552         break;
8553       }
8554     }
8555
8556     if (!NonFlagUse)
8557       break;
8558   }
8559     // FALL THROUGH
8560   case ISD::SUB:
8561   case ISD::OR:
8562   case ISD::XOR:
8563     // Due to the ISEL shortcoming noted above, be conservative if this op is
8564     // likely to be selected as part of a load-modify-store instruction.
8565     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8566            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8567       if (UI->getOpcode() == ISD::STORE)
8568         goto default_case;
8569
8570     // Otherwise use a regular EFLAGS-setting instruction.
8571     switch (ArithOp.getOpcode()) {
8572     default: llvm_unreachable("unexpected operator!");
8573     case ISD::SUB: Opcode = X86ISD::SUB; break;
8574     case ISD::XOR: Opcode = X86ISD::XOR; break;
8575     case ISD::AND: Opcode = X86ISD::AND; break;
8576     case ISD::OR: {
8577       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8578         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8579         if (EFLAGS.getNode())
8580           return EFLAGS;
8581       }
8582       Opcode = X86ISD::OR;
8583       break;
8584     }
8585     }
8586
8587     NumOperands = 2;
8588     break;
8589   case X86ISD::ADD:
8590   case X86ISD::SUB:
8591   case X86ISD::INC:
8592   case X86ISD::DEC:
8593   case X86ISD::OR:
8594   case X86ISD::XOR:
8595   case X86ISD::AND:
8596     return SDValue(Op.getNode(), 1);
8597   default:
8598   default_case:
8599     break;
8600   }
8601
8602   // If we found that truncation is beneficial, perform the truncation and
8603   // update 'Op'.
8604   if (NeedTruncation) {
8605     EVT VT = Op.getValueType();
8606     SDValue WideVal = Op->getOperand(0);
8607     EVT WideVT = WideVal.getValueType();
8608     unsigned ConvertedOp = 0;
8609     // Use a target machine opcode to prevent further DAGCombine
8610     // optimizations that may separate the arithmetic operations
8611     // from the setcc node.
8612     switch (WideVal.getOpcode()) {
8613       default: break;
8614       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8615       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8616       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8617       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8618       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8619     }
8620
8621     if (ConvertedOp) {
8622       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8623       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8624         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8625         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8626         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8627       }
8628     }
8629   }
8630
8631   if (Opcode == 0)
8632     // Emit a CMP with 0, which is the TEST pattern.
8633     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8634                        DAG.getConstant(0, Op.getValueType()));
8635
8636   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8637   SmallVector<SDValue, 4> Ops;
8638   for (unsigned i = 0; i != NumOperands; ++i)
8639     Ops.push_back(Op.getOperand(i));
8640
8641   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8642   DAG.ReplaceAllUsesWith(Op, New);
8643   return SDValue(New.getNode(), 1);
8644 }
8645
8646 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8647 /// equivalent.
8648 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8649                                    SelectionDAG &DAG) const {
8650   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8651     if (C->getAPIntValue() == 0)
8652       return EmitTest(Op0, X86CC, DAG);
8653
8654   DebugLoc dl = Op0.getDebugLoc();
8655   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8656        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8657     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8658     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8659     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8660                               Op0, Op1);
8661     return SDValue(Sub.getNode(), 1);
8662   }
8663   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8664 }
8665
8666 /// Convert a comparison if required by the subtarget.
8667 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8668                                                  SelectionDAG &DAG) const {
8669   // If the subtarget does not support the FUCOMI instruction, floating-point
8670   // comparisons have to be converted.
8671   if (Subtarget->hasCMov() ||
8672       Cmp.getOpcode() != X86ISD::CMP ||
8673       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8674       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8675     return Cmp;
8676
8677   // The instruction selector will select an FUCOM instruction instead of
8678   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8679   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8680   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8681   DebugLoc dl = Cmp.getDebugLoc();
8682   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8683   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8684   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8685                             DAG.getConstant(8, MVT::i8));
8686   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8687   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8688 }
8689
8690 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8691 /// if it's possible.
8692 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8693                                      DebugLoc dl, SelectionDAG &DAG) const {
8694   SDValue Op0 = And.getOperand(0);
8695   SDValue Op1 = And.getOperand(1);
8696   if (Op0.getOpcode() == ISD::TRUNCATE)
8697     Op0 = Op0.getOperand(0);
8698   if (Op1.getOpcode() == ISD::TRUNCATE)
8699     Op1 = Op1.getOperand(0);
8700
8701   SDValue LHS, RHS;
8702   if (Op1.getOpcode() == ISD::SHL)
8703     std::swap(Op0, Op1);
8704   if (Op0.getOpcode() == ISD::SHL) {
8705     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8706       if (And00C->getZExtValue() == 1) {
8707         // If we looked past a truncate, check that it's only truncating away
8708         // known zeros.
8709         unsigned BitWidth = Op0.getValueSizeInBits();
8710         unsigned AndBitWidth = And.getValueSizeInBits();
8711         if (BitWidth > AndBitWidth) {
8712           APInt Zeros, Ones;
8713           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8714           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8715             return SDValue();
8716         }
8717         LHS = Op1;
8718         RHS = Op0.getOperand(1);
8719       }
8720   } else if (Op1.getOpcode() == ISD::Constant) {
8721     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8722     uint64_t AndRHSVal = AndRHS->getZExtValue();
8723     SDValue AndLHS = Op0;
8724
8725     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8726       LHS = AndLHS.getOperand(0);
8727       RHS = AndLHS.getOperand(1);
8728     }
8729
8730     // Use BT if the immediate can't be encoded in a TEST instruction.
8731     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8732       LHS = AndLHS;
8733       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8734     }
8735   }
8736
8737   if (LHS.getNode()) {
8738     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8739     // instruction.  Since the shift amount is in-range-or-undefined, we know
8740     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8741     // the encoding for the i16 version is larger than the i32 version.
8742     // Also promote i16 to i32 for performance / code size reason.
8743     if (LHS.getValueType() == MVT::i8 ||
8744         LHS.getValueType() == MVT::i16)
8745       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8746
8747     // If the operand types disagree, extend the shift amount to match.  Since
8748     // BT ignores high bits (like shifts) we can use anyextend.
8749     if (LHS.getValueType() != RHS.getValueType())
8750       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8751
8752     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8753     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8754     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8755                        DAG.getConstant(Cond, MVT::i8), BT);
8756   }
8757
8758   return SDValue();
8759 }
8760
8761 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8762
8763   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8764
8765   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8766   SDValue Op0 = Op.getOperand(0);
8767   SDValue Op1 = Op.getOperand(1);
8768   DebugLoc dl = Op.getDebugLoc();
8769   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8770
8771   // Optimize to BT if possible.
8772   // Lower (X & (1 << N)) == 0 to BT(X, N).
8773   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8774   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8775   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8776       Op1.getOpcode() == ISD::Constant &&
8777       cast<ConstantSDNode>(Op1)->isNullValue() &&
8778       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8779     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8780     if (NewSetCC.getNode())
8781       return NewSetCC;
8782   }
8783
8784   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8785   // these.
8786   if (Op1.getOpcode() == ISD::Constant &&
8787       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8788        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8789       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8790
8791     // If the input is a setcc, then reuse the input setcc or use a new one with
8792     // the inverted condition.
8793     if (Op0.getOpcode() == X86ISD::SETCC) {
8794       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8795       bool Invert = (CC == ISD::SETNE) ^
8796         cast<ConstantSDNode>(Op1)->isNullValue();
8797       if (!Invert) return Op0;
8798
8799       CCode = X86::GetOppositeBranchCondition(CCode);
8800       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8801                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8802     }
8803   }
8804
8805   bool isFP = Op1.getValueType().isFloatingPoint();
8806   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8807   if (X86CC == X86::COND_INVALID)
8808     return SDValue();
8809
8810   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8811   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8812   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8813                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8814 }
8815
8816 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8817 // ones, and then concatenate the result back.
8818 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8819   EVT VT = Op.getValueType();
8820
8821   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8822          "Unsupported value type for operation");
8823
8824   unsigned NumElems = VT.getVectorNumElements();
8825   DebugLoc dl = Op.getDebugLoc();
8826   SDValue CC = Op.getOperand(2);
8827
8828   // Extract the LHS vectors
8829   SDValue LHS = Op.getOperand(0);
8830   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8831   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8832
8833   // Extract the RHS vectors
8834   SDValue RHS = Op.getOperand(1);
8835   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8836   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8837
8838   // Issue the operation on the smaller types and concatenate the result back
8839   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8840   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8841   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8842                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8843                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8844 }
8845
8846
8847 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8848   SDValue Cond;
8849   SDValue Op0 = Op.getOperand(0);
8850   SDValue Op1 = Op.getOperand(1);
8851   SDValue CC = Op.getOperand(2);
8852   EVT VT = Op.getValueType();
8853   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8854   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8855   DebugLoc dl = Op.getDebugLoc();
8856
8857   if (isFP) {
8858 #ifndef NDEBUG
8859     EVT EltVT = Op0.getValueType().getVectorElementType();
8860     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8861 #endif
8862
8863     unsigned SSECC;
8864     bool Swap = false;
8865
8866     // SSE Condition code mapping:
8867     //  0 - EQ
8868     //  1 - LT
8869     //  2 - LE
8870     //  3 - UNORD
8871     //  4 - NEQ
8872     //  5 - NLT
8873     //  6 - NLE
8874     //  7 - ORD
8875     switch (SetCCOpcode) {
8876     default: llvm_unreachable("Unexpected SETCC condition");
8877     case ISD::SETOEQ:
8878     case ISD::SETEQ:  SSECC = 0; break;
8879     case ISD::SETOGT:
8880     case ISD::SETGT: Swap = true; // Fallthrough
8881     case ISD::SETLT:
8882     case ISD::SETOLT: SSECC = 1; break;
8883     case ISD::SETOGE:
8884     case ISD::SETGE: Swap = true; // Fallthrough
8885     case ISD::SETLE:
8886     case ISD::SETOLE: SSECC = 2; break;
8887     case ISD::SETUO:  SSECC = 3; break;
8888     case ISD::SETUNE:
8889     case ISD::SETNE:  SSECC = 4; break;
8890     case ISD::SETULE: Swap = true; // Fallthrough
8891     case ISD::SETUGE: SSECC = 5; break;
8892     case ISD::SETULT: Swap = true; // Fallthrough
8893     case ISD::SETUGT: SSECC = 6; break;
8894     case ISD::SETO:   SSECC = 7; break;
8895     case ISD::SETUEQ:
8896     case ISD::SETONE: SSECC = 8; break;
8897     }
8898     if (Swap)
8899       std::swap(Op0, Op1);
8900
8901     // In the two special cases we can't handle, emit two comparisons.
8902     if (SSECC == 8) {
8903       unsigned CC0, CC1;
8904       unsigned CombineOpc;
8905       if (SetCCOpcode == ISD::SETUEQ) {
8906         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8907       } else {
8908         assert(SetCCOpcode == ISD::SETONE);
8909         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8910       }
8911
8912       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8913                                  DAG.getConstant(CC0, MVT::i8));
8914       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8915                                  DAG.getConstant(CC1, MVT::i8));
8916       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8917     }
8918     // Handle all other FP comparisons here.
8919     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8920                        DAG.getConstant(SSECC, MVT::i8));
8921   }
8922
8923   // Break 256-bit integer vector compare into smaller ones.
8924   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8925     return Lower256IntVSETCC(Op, DAG);
8926
8927   // We are handling one of the integer comparisons here.  Since SSE only has
8928   // GT and EQ comparisons for integer, swapping operands and multiple
8929   // operations may be required for some comparisons.
8930   unsigned Opc;
8931   bool Swap = false, Invert = false, FlipSigns = false;
8932
8933   switch (SetCCOpcode) {
8934   default: llvm_unreachable("Unexpected SETCC condition");
8935   case ISD::SETNE:  Invert = true;
8936   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8937   case ISD::SETLT:  Swap = true;
8938   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8939   case ISD::SETGE:  Swap = true;
8940   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8941   case ISD::SETULT: Swap = true;
8942   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8943   case ISD::SETUGE: Swap = true;
8944   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8945   }
8946   if (Swap)
8947     std::swap(Op0, Op1);
8948
8949   // Check that the operation in question is available (most are plain SSE2,
8950   // but PCMPGTQ and PCMPEQQ have different requirements).
8951   if (VT == MVT::v2i64) {
8952     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8953       return SDValue();
8954     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8955       return SDValue();
8956   }
8957
8958   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8959   // bits of the inputs before performing those operations.
8960   if (FlipSigns) {
8961     EVT EltVT = VT.getVectorElementType();
8962     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8963                                       EltVT);
8964     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8965     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8966                                     SignBits.size());
8967     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8968     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8969   }
8970
8971   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8972
8973   // If the logical-not of the result is required, perform that now.
8974   if (Invert)
8975     Result = DAG.getNOT(dl, Result, VT);
8976
8977   return Result;
8978 }
8979
8980 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8981 static bool isX86LogicalCmp(SDValue Op) {
8982   unsigned Opc = Op.getNode()->getOpcode();
8983   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8984       Opc == X86ISD::SAHF)
8985     return true;
8986   if (Op.getResNo() == 1 &&
8987       (Opc == X86ISD::ADD ||
8988        Opc == X86ISD::SUB ||
8989        Opc == X86ISD::ADC ||
8990        Opc == X86ISD::SBB ||
8991        Opc == X86ISD::SMUL ||
8992        Opc == X86ISD::UMUL ||
8993        Opc == X86ISD::INC ||
8994        Opc == X86ISD::DEC ||
8995        Opc == X86ISD::OR ||
8996        Opc == X86ISD::XOR ||
8997        Opc == X86ISD::AND))
8998     return true;
8999
9000   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9001     return true;
9002
9003   return false;
9004 }
9005
9006 static bool isZero(SDValue V) {
9007   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9008   return C && C->isNullValue();
9009 }
9010
9011 static bool isAllOnes(SDValue V) {
9012   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9013   return C && C->isAllOnesValue();
9014 }
9015
9016 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9017   if (V.getOpcode() != ISD::TRUNCATE)
9018     return false;
9019
9020   SDValue VOp0 = V.getOperand(0);
9021   unsigned InBits = VOp0.getValueSizeInBits();
9022   unsigned Bits = V.getValueSizeInBits();
9023   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9024 }
9025
9026 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9027   bool addTest = true;
9028   SDValue Cond  = Op.getOperand(0);
9029   SDValue Op1 = Op.getOperand(1);
9030   SDValue Op2 = Op.getOperand(2);
9031   DebugLoc DL = Op.getDebugLoc();
9032   SDValue CC;
9033
9034   if (Cond.getOpcode() == ISD::SETCC) {
9035     SDValue NewCond = LowerSETCC(Cond, DAG);
9036     if (NewCond.getNode())
9037       Cond = NewCond;
9038   }
9039
9040   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9041   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9042   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9043   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9044   if (Cond.getOpcode() == X86ISD::SETCC &&
9045       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9046       isZero(Cond.getOperand(1).getOperand(1))) {
9047     SDValue Cmp = Cond.getOperand(1);
9048
9049     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9050
9051     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9052         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9053       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9054
9055       SDValue CmpOp0 = Cmp.getOperand(0);
9056       // Apply further optimizations for special cases
9057       // (select (x != 0), -1, 0) -> neg & sbb
9058       // (select (x == 0), 0, -1) -> neg & sbb
9059       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9060         if (YC->isNullValue() &&
9061             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9062           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9063           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9064                                     DAG.getConstant(0, CmpOp0.getValueType()),
9065                                     CmpOp0);
9066           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9067                                     DAG.getConstant(X86::COND_B, MVT::i8),
9068                                     SDValue(Neg.getNode(), 1));
9069           return Res;
9070         }
9071
9072       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9073                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9074       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9075
9076       SDValue Res =   // Res = 0 or -1.
9077         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9078                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9079
9080       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9081         Res = DAG.getNOT(DL, Res, Res.getValueType());
9082
9083       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9084       if (N2C == 0 || !N2C->isNullValue())
9085         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9086       return Res;
9087     }
9088   }
9089
9090   // Look past (and (setcc_carry (cmp ...)), 1).
9091   if (Cond.getOpcode() == ISD::AND &&
9092       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9093     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9094     if (C && C->getAPIntValue() == 1)
9095       Cond = Cond.getOperand(0);
9096   }
9097
9098   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9099   // setting operand in place of the X86ISD::SETCC.
9100   unsigned CondOpcode = Cond.getOpcode();
9101   if (CondOpcode == X86ISD::SETCC ||
9102       CondOpcode == X86ISD::SETCC_CARRY) {
9103     CC = Cond.getOperand(0);
9104
9105     SDValue Cmp = Cond.getOperand(1);
9106     unsigned Opc = Cmp.getOpcode();
9107     EVT VT = Op.getValueType();
9108
9109     bool IllegalFPCMov = false;
9110     if (VT.isFloatingPoint() && !VT.isVector() &&
9111         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9112       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9113
9114     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9115         Opc == X86ISD::BT) { // FIXME
9116       Cond = Cmp;
9117       addTest = false;
9118     }
9119   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9120              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9121              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9122               Cond.getOperand(0).getValueType() != MVT::i8)) {
9123     SDValue LHS = Cond.getOperand(0);
9124     SDValue RHS = Cond.getOperand(1);
9125     unsigned X86Opcode;
9126     unsigned X86Cond;
9127     SDVTList VTs;
9128     switch (CondOpcode) {
9129     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9130     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9131     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9132     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9133     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9134     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9135     default: llvm_unreachable("unexpected overflowing operator");
9136     }
9137     if (CondOpcode == ISD::UMULO)
9138       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9139                           MVT::i32);
9140     else
9141       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9142
9143     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9144
9145     if (CondOpcode == ISD::UMULO)
9146       Cond = X86Op.getValue(2);
9147     else
9148       Cond = X86Op.getValue(1);
9149
9150     CC = DAG.getConstant(X86Cond, MVT::i8);
9151     addTest = false;
9152   }
9153
9154   if (addTest) {
9155     // Look pass the truncate if the high bits are known zero.
9156     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9157         Cond = Cond.getOperand(0);
9158
9159     // We know the result of AND is compared against zero. Try to match
9160     // it to BT.
9161     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9162       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9163       if (NewSetCC.getNode()) {
9164         CC = NewSetCC.getOperand(0);
9165         Cond = NewSetCC.getOperand(1);
9166         addTest = false;
9167       }
9168     }
9169   }
9170
9171   if (addTest) {
9172     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9173     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9174   }
9175
9176   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9177   // a <  b ?  0 : -1 -> RES = setcc_carry
9178   // a >= b ? -1 :  0 -> RES = setcc_carry
9179   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9180   if (Cond.getOpcode() == X86ISD::SUB) {
9181     Cond = ConvertCmpIfNecessary(Cond, DAG);
9182     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9183
9184     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9185         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9186       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9187                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9188       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9189         return DAG.getNOT(DL, Res, Res.getValueType());
9190       return Res;
9191     }
9192   }
9193
9194   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9195   // widen the cmov and push the truncate through. This avoids introducing a new
9196   // branch during isel and doesn't add any extensions.
9197   if (Op.getValueType() == MVT::i8 &&
9198       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9199     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9200     if (T1.getValueType() == T2.getValueType() &&
9201         // Blacklist CopyFromReg to avoid partial register stalls.
9202         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9203       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9204       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9205       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9206     }
9207   }
9208
9209   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9210   // condition is true.
9211   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9212   SDValue Ops[] = { Op2, Op1, CC, Cond };
9213   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9214 }
9215
9216 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9217 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9218 // from the AND / OR.
9219 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9220   Opc = Op.getOpcode();
9221   if (Opc != ISD::OR && Opc != ISD::AND)
9222     return false;
9223   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9224           Op.getOperand(0).hasOneUse() &&
9225           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9226           Op.getOperand(1).hasOneUse());
9227 }
9228
9229 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9230 // 1 and that the SETCC node has a single use.
9231 static bool isXor1OfSetCC(SDValue Op) {
9232   if (Op.getOpcode() != ISD::XOR)
9233     return false;
9234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9235   if (N1C && N1C->getAPIntValue() == 1) {
9236     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9237       Op.getOperand(0).hasOneUse();
9238   }
9239   return false;
9240 }
9241
9242 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9243   bool addTest = true;
9244   SDValue Chain = Op.getOperand(0);
9245   SDValue Cond  = Op.getOperand(1);
9246   SDValue Dest  = Op.getOperand(2);
9247   DebugLoc dl = Op.getDebugLoc();
9248   SDValue CC;
9249   bool Inverted = false;
9250
9251   if (Cond.getOpcode() == ISD::SETCC) {
9252     // Check for setcc([su]{add,sub,mul}o == 0).
9253     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9254         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9255         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9256         Cond.getOperand(0).getResNo() == 1 &&
9257         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9258          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9259          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9260          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9261          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9262          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9263       Inverted = true;
9264       Cond = Cond.getOperand(0);
9265     } else {
9266       SDValue NewCond = LowerSETCC(Cond, DAG);
9267       if (NewCond.getNode())
9268         Cond = NewCond;
9269     }
9270   }
9271 #if 0
9272   // FIXME: LowerXALUO doesn't handle these!!
9273   else if (Cond.getOpcode() == X86ISD::ADD  ||
9274            Cond.getOpcode() == X86ISD::SUB  ||
9275            Cond.getOpcode() == X86ISD::SMUL ||
9276            Cond.getOpcode() == X86ISD::UMUL)
9277     Cond = LowerXALUO(Cond, DAG);
9278 #endif
9279
9280   // Look pass (and (setcc_carry (cmp ...)), 1).
9281   if (Cond.getOpcode() == ISD::AND &&
9282       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9283     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9284     if (C && C->getAPIntValue() == 1)
9285       Cond = Cond.getOperand(0);
9286   }
9287
9288   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9289   // setting operand in place of the X86ISD::SETCC.
9290   unsigned CondOpcode = Cond.getOpcode();
9291   if (CondOpcode == X86ISD::SETCC ||
9292       CondOpcode == X86ISD::SETCC_CARRY) {
9293     CC = Cond.getOperand(0);
9294
9295     SDValue Cmp = Cond.getOperand(1);
9296     unsigned Opc = Cmp.getOpcode();
9297     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9298     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9299       Cond = Cmp;
9300       addTest = false;
9301     } else {
9302       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9303       default: break;
9304       case X86::COND_O:
9305       case X86::COND_B:
9306         // These can only come from an arithmetic instruction with overflow,
9307         // e.g. SADDO, UADDO.
9308         Cond = Cond.getNode()->getOperand(1);
9309         addTest = false;
9310         break;
9311       }
9312     }
9313   }
9314   CondOpcode = Cond.getOpcode();
9315   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9316       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9317       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9318        Cond.getOperand(0).getValueType() != MVT::i8)) {
9319     SDValue LHS = Cond.getOperand(0);
9320     SDValue RHS = Cond.getOperand(1);
9321     unsigned X86Opcode;
9322     unsigned X86Cond;
9323     SDVTList VTs;
9324     switch (CondOpcode) {
9325     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9326     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9327     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9328     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9329     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9330     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9331     default: llvm_unreachable("unexpected overflowing operator");
9332     }
9333     if (Inverted)
9334       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9335     if (CondOpcode == ISD::UMULO)
9336       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9337                           MVT::i32);
9338     else
9339       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9340
9341     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9342
9343     if (CondOpcode == ISD::UMULO)
9344       Cond = X86Op.getValue(2);
9345     else
9346       Cond = X86Op.getValue(1);
9347
9348     CC = DAG.getConstant(X86Cond, MVT::i8);
9349     addTest = false;
9350   } else {
9351     unsigned CondOpc;
9352     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9353       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9354       if (CondOpc == ISD::OR) {
9355         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9356         // two branches instead of an explicit OR instruction with a
9357         // separate test.
9358         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9359             isX86LogicalCmp(Cmp)) {
9360           CC = Cond.getOperand(0).getOperand(0);
9361           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9362                               Chain, Dest, CC, Cmp);
9363           CC = Cond.getOperand(1).getOperand(0);
9364           Cond = Cmp;
9365           addTest = false;
9366         }
9367       } else { // ISD::AND
9368         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9369         // two branches instead of an explicit AND instruction with a
9370         // separate test. However, we only do this if this block doesn't
9371         // have a fall-through edge, because this requires an explicit
9372         // jmp when the condition is false.
9373         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9374             isX86LogicalCmp(Cmp) &&
9375             Op.getNode()->hasOneUse()) {
9376           X86::CondCode CCode =
9377             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9378           CCode = X86::GetOppositeBranchCondition(CCode);
9379           CC = DAG.getConstant(CCode, MVT::i8);
9380           SDNode *User = *Op.getNode()->use_begin();
9381           // Look for an unconditional branch following this conditional branch.
9382           // We need this because we need to reverse the successors in order
9383           // to implement FCMP_OEQ.
9384           if (User->getOpcode() == ISD::BR) {
9385             SDValue FalseBB = User->getOperand(1);
9386             SDNode *NewBR =
9387               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9388             assert(NewBR == User);
9389             (void)NewBR;
9390             Dest = FalseBB;
9391
9392             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9393                                 Chain, Dest, CC, Cmp);
9394             X86::CondCode CCode =
9395               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9396             CCode = X86::GetOppositeBranchCondition(CCode);
9397             CC = DAG.getConstant(CCode, MVT::i8);
9398             Cond = Cmp;
9399             addTest = false;
9400           }
9401         }
9402       }
9403     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9404       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9405       // It should be transformed during dag combiner except when the condition
9406       // is set by a arithmetics with overflow node.
9407       X86::CondCode CCode =
9408         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9409       CCode = X86::GetOppositeBranchCondition(CCode);
9410       CC = DAG.getConstant(CCode, MVT::i8);
9411       Cond = Cond.getOperand(0).getOperand(1);
9412       addTest = false;
9413     } else if (Cond.getOpcode() == ISD::SETCC &&
9414                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9415       // For FCMP_OEQ, we can emit
9416       // two branches instead of an explicit AND instruction with a
9417       // separate test. However, we only do this if this block doesn't
9418       // have a fall-through edge, because this requires an explicit
9419       // jmp when the condition is false.
9420       if (Op.getNode()->hasOneUse()) {
9421         SDNode *User = *Op.getNode()->use_begin();
9422         // Look for an unconditional branch following this conditional branch.
9423         // We need this because we need to reverse the successors in order
9424         // to implement FCMP_OEQ.
9425         if (User->getOpcode() == ISD::BR) {
9426           SDValue FalseBB = User->getOperand(1);
9427           SDNode *NewBR =
9428             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9429           assert(NewBR == User);
9430           (void)NewBR;
9431           Dest = FalseBB;
9432
9433           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9434                                     Cond.getOperand(0), Cond.getOperand(1));
9435           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9436           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9437           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9438                               Chain, Dest, CC, Cmp);
9439           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9440           Cond = Cmp;
9441           addTest = false;
9442         }
9443       }
9444     } else if (Cond.getOpcode() == ISD::SETCC &&
9445                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9446       // For FCMP_UNE, we can emit
9447       // two branches instead of an explicit AND instruction with a
9448       // separate test. However, we only do this if this block doesn't
9449       // have a fall-through edge, because this requires an explicit
9450       // jmp when the condition is false.
9451       if (Op.getNode()->hasOneUse()) {
9452         SDNode *User = *Op.getNode()->use_begin();
9453         // Look for an unconditional branch following this conditional branch.
9454         // We need this because we need to reverse the successors in order
9455         // to implement FCMP_UNE.
9456         if (User->getOpcode() == ISD::BR) {
9457           SDValue FalseBB = User->getOperand(1);
9458           SDNode *NewBR =
9459             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9460           assert(NewBR == User);
9461           (void)NewBR;
9462
9463           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9464                                     Cond.getOperand(0), Cond.getOperand(1));
9465           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9466           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9467           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9468                               Chain, Dest, CC, Cmp);
9469           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9470           Cond = Cmp;
9471           addTest = false;
9472           Dest = FalseBB;
9473         }
9474       }
9475     }
9476   }
9477
9478   if (addTest) {
9479     // Look pass the truncate if the high bits are known zero.
9480     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9481         Cond = Cond.getOperand(0);
9482
9483     // We know the result of AND is compared against zero. Try to match
9484     // it to BT.
9485     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9486       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9487       if (NewSetCC.getNode()) {
9488         CC = NewSetCC.getOperand(0);
9489         Cond = NewSetCC.getOperand(1);
9490         addTest = false;
9491       }
9492     }
9493   }
9494
9495   if (addTest) {
9496     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9497     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9498   }
9499   Cond = ConvertCmpIfNecessary(Cond, DAG);
9500   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9501                      Chain, Dest, CC, Cond);
9502 }
9503
9504
9505 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9506 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9507 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9508 // that the guard pages used by the OS virtual memory manager are allocated in
9509 // correct sequence.
9510 SDValue
9511 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9512                                            SelectionDAG &DAG) const {
9513   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9514           getTargetMachine().Options.EnableSegmentedStacks) &&
9515          "This should be used only on Windows targets or when segmented stacks "
9516          "are being used");
9517   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9518   DebugLoc dl = Op.getDebugLoc();
9519
9520   // Get the inputs.
9521   SDValue Chain = Op.getOperand(0);
9522   SDValue Size  = Op.getOperand(1);
9523   // FIXME: Ensure alignment here
9524
9525   bool Is64Bit = Subtarget->is64Bit();
9526   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9527
9528   if (getTargetMachine().Options.EnableSegmentedStacks) {
9529     MachineFunction &MF = DAG.getMachineFunction();
9530     MachineRegisterInfo &MRI = MF.getRegInfo();
9531
9532     if (Is64Bit) {
9533       // The 64 bit implementation of segmented stacks needs to clobber both r10
9534       // r11. This makes it impossible to use it along with nested parameters.
9535       const Function *F = MF.getFunction();
9536
9537       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9538            I != E; ++I)
9539         if (I->hasNestAttr())
9540           report_fatal_error("Cannot use segmented stacks with functions that "
9541                              "have nested arguments.");
9542     }
9543
9544     const TargetRegisterClass *AddrRegClass =
9545       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9546     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9547     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9548     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9549                                 DAG.getRegister(Vreg, SPTy));
9550     SDValue Ops1[2] = { Value, Chain };
9551     return DAG.getMergeValues(Ops1, 2, dl);
9552   } else {
9553     SDValue Flag;
9554     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9555
9556     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9557     Flag = Chain.getValue(1);
9558     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9559
9560     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9561     Flag = Chain.getValue(1);
9562
9563     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9564
9565     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9566     return DAG.getMergeValues(Ops1, 2, dl);
9567   }
9568 }
9569
9570 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9571   MachineFunction &MF = DAG.getMachineFunction();
9572   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9573
9574   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9575   DebugLoc DL = Op.getDebugLoc();
9576
9577   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9578     // vastart just stores the address of the VarArgsFrameIndex slot into the
9579     // memory location argument.
9580     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9581                                    getPointerTy());
9582     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9583                         MachinePointerInfo(SV), false, false, 0);
9584   }
9585
9586   // __va_list_tag:
9587   //   gp_offset         (0 - 6 * 8)
9588   //   fp_offset         (48 - 48 + 8 * 16)
9589   //   overflow_arg_area (point to parameters coming in memory).
9590   //   reg_save_area
9591   SmallVector<SDValue, 8> MemOps;
9592   SDValue FIN = Op.getOperand(1);
9593   // Store gp_offset
9594   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9595                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9596                                                MVT::i32),
9597                                FIN, MachinePointerInfo(SV), false, false, 0);
9598   MemOps.push_back(Store);
9599
9600   // Store fp_offset
9601   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9602                     FIN, DAG.getIntPtrConstant(4));
9603   Store = DAG.getStore(Op.getOperand(0), DL,
9604                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9605                                        MVT::i32),
9606                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9607   MemOps.push_back(Store);
9608
9609   // Store ptr to overflow_arg_area
9610   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9611                     FIN, DAG.getIntPtrConstant(4));
9612   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9613                                     getPointerTy());
9614   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9615                        MachinePointerInfo(SV, 8),
9616                        false, false, 0);
9617   MemOps.push_back(Store);
9618
9619   // Store ptr to reg_save_area.
9620   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9621                     FIN, DAG.getIntPtrConstant(8));
9622   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9623                                     getPointerTy());
9624   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9625                        MachinePointerInfo(SV, 16), false, false, 0);
9626   MemOps.push_back(Store);
9627   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9628                      &MemOps[0], MemOps.size());
9629 }
9630
9631 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9632   assert(Subtarget->is64Bit() &&
9633          "LowerVAARG only handles 64-bit va_arg!");
9634   assert((Subtarget->isTargetLinux() ||
9635           Subtarget->isTargetDarwin()) &&
9636           "Unhandled target in LowerVAARG");
9637   assert(Op.getNode()->getNumOperands() == 4);
9638   SDValue Chain = Op.getOperand(0);
9639   SDValue SrcPtr = Op.getOperand(1);
9640   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9641   unsigned Align = Op.getConstantOperandVal(3);
9642   DebugLoc dl = Op.getDebugLoc();
9643
9644   EVT ArgVT = Op.getNode()->getValueType(0);
9645   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9646   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9647   uint8_t ArgMode;
9648
9649   // Decide which area this value should be read from.
9650   // TODO: Implement the AMD64 ABI in its entirety. This simple
9651   // selection mechanism works only for the basic types.
9652   if (ArgVT == MVT::f80) {
9653     llvm_unreachable("va_arg for f80 not yet implemented");
9654   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9655     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9656   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9657     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9658   } else {
9659     llvm_unreachable("Unhandled argument type in LowerVAARG");
9660   }
9661
9662   if (ArgMode == 2) {
9663     // Sanity Check: Make sure using fp_offset makes sense.
9664     assert(!getTargetMachine().Options.UseSoftFloat &&
9665            !(DAG.getMachineFunction()
9666                 .getFunction()->getFnAttributes()
9667                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9668            Subtarget->hasSSE1());
9669   }
9670
9671   // Insert VAARG_64 node into the DAG
9672   // VAARG_64 returns two values: Variable Argument Address, Chain
9673   SmallVector<SDValue, 11> InstOps;
9674   InstOps.push_back(Chain);
9675   InstOps.push_back(SrcPtr);
9676   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9677   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9678   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9679   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9680   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9681                                           VTs, &InstOps[0], InstOps.size(),
9682                                           MVT::i64,
9683                                           MachinePointerInfo(SV),
9684                                           /*Align=*/0,
9685                                           /*Volatile=*/false,
9686                                           /*ReadMem=*/true,
9687                                           /*WriteMem=*/true);
9688   Chain = VAARG.getValue(1);
9689
9690   // Load the next argument and return it
9691   return DAG.getLoad(ArgVT, dl,
9692                      Chain,
9693                      VAARG,
9694                      MachinePointerInfo(),
9695                      false, false, false, 0);
9696 }
9697
9698 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9699                            SelectionDAG &DAG) {
9700   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9701   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9702   SDValue Chain = Op.getOperand(0);
9703   SDValue DstPtr = Op.getOperand(1);
9704   SDValue SrcPtr = Op.getOperand(2);
9705   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9706   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9707   DebugLoc DL = Op.getDebugLoc();
9708
9709   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9710                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9711                        false,
9712                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9713 }
9714
9715 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9716 // may or may not be a constant. Takes immediate version of shift as input.
9717 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9718                                    SDValue SrcOp, SDValue ShAmt,
9719                                    SelectionDAG &DAG) {
9720   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9721
9722   if (isa<ConstantSDNode>(ShAmt)) {
9723     // Constant may be a TargetConstant. Use a regular constant.
9724     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9725     switch (Opc) {
9726       default: llvm_unreachable("Unknown target vector shift node");
9727       case X86ISD::VSHLI:
9728       case X86ISD::VSRLI:
9729       case X86ISD::VSRAI:
9730         return DAG.getNode(Opc, dl, VT, SrcOp,
9731                            DAG.getConstant(ShiftAmt, MVT::i32));
9732     }
9733   }
9734
9735   // Change opcode to non-immediate version
9736   switch (Opc) {
9737     default: llvm_unreachable("Unknown target vector shift node");
9738     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9739     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9740     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9741   }
9742
9743   // Need to build a vector containing shift amount
9744   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9745   SDValue ShOps[4];
9746   ShOps[0] = ShAmt;
9747   ShOps[1] = DAG.getConstant(0, MVT::i32);
9748   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9749   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9750
9751   // The return type has to be a 128-bit type with the same element
9752   // type as the input type.
9753   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9754   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9755
9756   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9757   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9758 }
9759
9760 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9761   DebugLoc dl = Op.getDebugLoc();
9762   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9763   switch (IntNo) {
9764   default: return SDValue();    // Don't custom lower most intrinsics.
9765   // Comparison intrinsics.
9766   case Intrinsic::x86_sse_comieq_ss:
9767   case Intrinsic::x86_sse_comilt_ss:
9768   case Intrinsic::x86_sse_comile_ss:
9769   case Intrinsic::x86_sse_comigt_ss:
9770   case Intrinsic::x86_sse_comige_ss:
9771   case Intrinsic::x86_sse_comineq_ss:
9772   case Intrinsic::x86_sse_ucomieq_ss:
9773   case Intrinsic::x86_sse_ucomilt_ss:
9774   case Intrinsic::x86_sse_ucomile_ss:
9775   case Intrinsic::x86_sse_ucomigt_ss:
9776   case Intrinsic::x86_sse_ucomige_ss:
9777   case Intrinsic::x86_sse_ucomineq_ss:
9778   case Intrinsic::x86_sse2_comieq_sd:
9779   case Intrinsic::x86_sse2_comilt_sd:
9780   case Intrinsic::x86_sse2_comile_sd:
9781   case Intrinsic::x86_sse2_comigt_sd:
9782   case Intrinsic::x86_sse2_comige_sd:
9783   case Intrinsic::x86_sse2_comineq_sd:
9784   case Intrinsic::x86_sse2_ucomieq_sd:
9785   case Intrinsic::x86_sse2_ucomilt_sd:
9786   case Intrinsic::x86_sse2_ucomile_sd:
9787   case Intrinsic::x86_sse2_ucomigt_sd:
9788   case Intrinsic::x86_sse2_ucomige_sd:
9789   case Intrinsic::x86_sse2_ucomineq_sd: {
9790     unsigned Opc;
9791     ISD::CondCode CC;
9792     switch (IntNo) {
9793     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9794     case Intrinsic::x86_sse_comieq_ss:
9795     case Intrinsic::x86_sse2_comieq_sd:
9796       Opc = X86ISD::COMI;
9797       CC = ISD::SETEQ;
9798       break;
9799     case Intrinsic::x86_sse_comilt_ss:
9800     case Intrinsic::x86_sse2_comilt_sd:
9801       Opc = X86ISD::COMI;
9802       CC = ISD::SETLT;
9803       break;
9804     case Intrinsic::x86_sse_comile_ss:
9805     case Intrinsic::x86_sse2_comile_sd:
9806       Opc = X86ISD::COMI;
9807       CC = ISD::SETLE;
9808       break;
9809     case Intrinsic::x86_sse_comigt_ss:
9810     case Intrinsic::x86_sse2_comigt_sd:
9811       Opc = X86ISD::COMI;
9812       CC = ISD::SETGT;
9813       break;
9814     case Intrinsic::x86_sse_comige_ss:
9815     case Intrinsic::x86_sse2_comige_sd:
9816       Opc = X86ISD::COMI;
9817       CC = ISD::SETGE;
9818       break;
9819     case Intrinsic::x86_sse_comineq_ss:
9820     case Intrinsic::x86_sse2_comineq_sd:
9821       Opc = X86ISD::COMI;
9822       CC = ISD::SETNE;
9823       break;
9824     case Intrinsic::x86_sse_ucomieq_ss:
9825     case Intrinsic::x86_sse2_ucomieq_sd:
9826       Opc = X86ISD::UCOMI;
9827       CC = ISD::SETEQ;
9828       break;
9829     case Intrinsic::x86_sse_ucomilt_ss:
9830     case Intrinsic::x86_sse2_ucomilt_sd:
9831       Opc = X86ISD::UCOMI;
9832       CC = ISD::SETLT;
9833       break;
9834     case Intrinsic::x86_sse_ucomile_ss:
9835     case Intrinsic::x86_sse2_ucomile_sd:
9836       Opc = X86ISD::UCOMI;
9837       CC = ISD::SETLE;
9838       break;
9839     case Intrinsic::x86_sse_ucomigt_ss:
9840     case Intrinsic::x86_sse2_ucomigt_sd:
9841       Opc = X86ISD::UCOMI;
9842       CC = ISD::SETGT;
9843       break;
9844     case Intrinsic::x86_sse_ucomige_ss:
9845     case Intrinsic::x86_sse2_ucomige_sd:
9846       Opc = X86ISD::UCOMI;
9847       CC = ISD::SETGE;
9848       break;
9849     case Intrinsic::x86_sse_ucomineq_ss:
9850     case Intrinsic::x86_sse2_ucomineq_sd:
9851       Opc = X86ISD::UCOMI;
9852       CC = ISD::SETNE;
9853       break;
9854     }
9855
9856     SDValue LHS = Op.getOperand(1);
9857     SDValue RHS = Op.getOperand(2);
9858     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9859     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9860     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9861     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9862                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9863     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9864   }
9865
9866   // Arithmetic intrinsics.
9867   case Intrinsic::x86_sse2_pmulu_dq:
9868   case Intrinsic::x86_avx2_pmulu_dq:
9869     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9870                        Op.getOperand(1), Op.getOperand(2));
9871
9872   // SSE3/AVX horizontal add/sub intrinsics
9873   case Intrinsic::x86_sse3_hadd_ps:
9874   case Intrinsic::x86_sse3_hadd_pd:
9875   case Intrinsic::x86_avx_hadd_ps_256:
9876   case Intrinsic::x86_avx_hadd_pd_256:
9877   case Intrinsic::x86_sse3_hsub_ps:
9878   case Intrinsic::x86_sse3_hsub_pd:
9879   case Intrinsic::x86_avx_hsub_ps_256:
9880   case Intrinsic::x86_avx_hsub_pd_256:
9881   case Intrinsic::x86_ssse3_phadd_w_128:
9882   case Intrinsic::x86_ssse3_phadd_d_128:
9883   case Intrinsic::x86_avx2_phadd_w:
9884   case Intrinsic::x86_avx2_phadd_d:
9885   case Intrinsic::x86_ssse3_phsub_w_128:
9886   case Intrinsic::x86_ssse3_phsub_d_128:
9887   case Intrinsic::x86_avx2_phsub_w:
9888   case Intrinsic::x86_avx2_phsub_d: {
9889     unsigned Opcode;
9890     switch (IntNo) {
9891     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9892     case Intrinsic::x86_sse3_hadd_ps:
9893     case Intrinsic::x86_sse3_hadd_pd:
9894     case Intrinsic::x86_avx_hadd_ps_256:
9895     case Intrinsic::x86_avx_hadd_pd_256:
9896       Opcode = X86ISD::FHADD;
9897       break;
9898     case Intrinsic::x86_sse3_hsub_ps:
9899     case Intrinsic::x86_sse3_hsub_pd:
9900     case Intrinsic::x86_avx_hsub_ps_256:
9901     case Intrinsic::x86_avx_hsub_pd_256:
9902       Opcode = X86ISD::FHSUB;
9903       break;
9904     case Intrinsic::x86_ssse3_phadd_w_128:
9905     case Intrinsic::x86_ssse3_phadd_d_128:
9906     case Intrinsic::x86_avx2_phadd_w:
9907     case Intrinsic::x86_avx2_phadd_d:
9908       Opcode = X86ISD::HADD;
9909       break;
9910     case Intrinsic::x86_ssse3_phsub_w_128:
9911     case Intrinsic::x86_ssse3_phsub_d_128:
9912     case Intrinsic::x86_avx2_phsub_w:
9913     case Intrinsic::x86_avx2_phsub_d:
9914       Opcode = X86ISD::HSUB;
9915       break;
9916     }
9917     return DAG.getNode(Opcode, dl, Op.getValueType(),
9918                        Op.getOperand(1), Op.getOperand(2));
9919   }
9920
9921   // AVX2 variable shift intrinsics
9922   case Intrinsic::x86_avx2_psllv_d:
9923   case Intrinsic::x86_avx2_psllv_q:
9924   case Intrinsic::x86_avx2_psllv_d_256:
9925   case Intrinsic::x86_avx2_psllv_q_256:
9926   case Intrinsic::x86_avx2_psrlv_d:
9927   case Intrinsic::x86_avx2_psrlv_q:
9928   case Intrinsic::x86_avx2_psrlv_d_256:
9929   case Intrinsic::x86_avx2_psrlv_q_256:
9930   case Intrinsic::x86_avx2_psrav_d:
9931   case Intrinsic::x86_avx2_psrav_d_256: {
9932     unsigned Opcode;
9933     switch (IntNo) {
9934     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9935     case Intrinsic::x86_avx2_psllv_d:
9936     case Intrinsic::x86_avx2_psllv_q:
9937     case Intrinsic::x86_avx2_psllv_d_256:
9938     case Intrinsic::x86_avx2_psllv_q_256:
9939       Opcode = ISD::SHL;
9940       break;
9941     case Intrinsic::x86_avx2_psrlv_d:
9942     case Intrinsic::x86_avx2_psrlv_q:
9943     case Intrinsic::x86_avx2_psrlv_d_256:
9944     case Intrinsic::x86_avx2_psrlv_q_256:
9945       Opcode = ISD::SRL;
9946       break;
9947     case Intrinsic::x86_avx2_psrav_d:
9948     case Intrinsic::x86_avx2_psrav_d_256:
9949       Opcode = ISD::SRA;
9950       break;
9951     }
9952     return DAG.getNode(Opcode, dl, Op.getValueType(),
9953                        Op.getOperand(1), Op.getOperand(2));
9954   }
9955
9956   case Intrinsic::x86_ssse3_pshuf_b_128:
9957   case Intrinsic::x86_avx2_pshuf_b:
9958     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9959                        Op.getOperand(1), Op.getOperand(2));
9960
9961   case Intrinsic::x86_ssse3_psign_b_128:
9962   case Intrinsic::x86_ssse3_psign_w_128:
9963   case Intrinsic::x86_ssse3_psign_d_128:
9964   case Intrinsic::x86_avx2_psign_b:
9965   case Intrinsic::x86_avx2_psign_w:
9966   case Intrinsic::x86_avx2_psign_d:
9967     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9968                        Op.getOperand(1), Op.getOperand(2));
9969
9970   case Intrinsic::x86_sse41_insertps:
9971     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9972                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9973
9974   case Intrinsic::x86_avx_vperm2f128_ps_256:
9975   case Intrinsic::x86_avx_vperm2f128_pd_256:
9976   case Intrinsic::x86_avx_vperm2f128_si_256:
9977   case Intrinsic::x86_avx2_vperm2i128:
9978     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9979                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9980
9981   case Intrinsic::x86_avx2_permd:
9982   case Intrinsic::x86_avx2_permps:
9983     // Operands intentionally swapped. Mask is last operand to intrinsic,
9984     // but second operand for node/intruction.
9985     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9986                        Op.getOperand(2), Op.getOperand(1));
9987
9988   // ptest and testp intrinsics. The intrinsic these come from are designed to
9989   // return an integer value, not just an instruction so lower it to the ptest
9990   // or testp pattern and a setcc for the result.
9991   case Intrinsic::x86_sse41_ptestz:
9992   case Intrinsic::x86_sse41_ptestc:
9993   case Intrinsic::x86_sse41_ptestnzc:
9994   case Intrinsic::x86_avx_ptestz_256:
9995   case Intrinsic::x86_avx_ptestc_256:
9996   case Intrinsic::x86_avx_ptestnzc_256:
9997   case Intrinsic::x86_avx_vtestz_ps:
9998   case Intrinsic::x86_avx_vtestc_ps:
9999   case Intrinsic::x86_avx_vtestnzc_ps:
10000   case Intrinsic::x86_avx_vtestz_pd:
10001   case Intrinsic::x86_avx_vtestc_pd:
10002   case Intrinsic::x86_avx_vtestnzc_pd:
10003   case Intrinsic::x86_avx_vtestz_ps_256:
10004   case Intrinsic::x86_avx_vtestc_ps_256:
10005   case Intrinsic::x86_avx_vtestnzc_ps_256:
10006   case Intrinsic::x86_avx_vtestz_pd_256:
10007   case Intrinsic::x86_avx_vtestc_pd_256:
10008   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10009     bool IsTestPacked = false;
10010     unsigned X86CC;
10011     switch (IntNo) {
10012     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10013     case Intrinsic::x86_avx_vtestz_ps:
10014     case Intrinsic::x86_avx_vtestz_pd:
10015     case Intrinsic::x86_avx_vtestz_ps_256:
10016     case Intrinsic::x86_avx_vtestz_pd_256:
10017       IsTestPacked = true; // Fallthrough
10018     case Intrinsic::x86_sse41_ptestz:
10019     case Intrinsic::x86_avx_ptestz_256:
10020       // ZF = 1
10021       X86CC = X86::COND_E;
10022       break;
10023     case Intrinsic::x86_avx_vtestc_ps:
10024     case Intrinsic::x86_avx_vtestc_pd:
10025     case Intrinsic::x86_avx_vtestc_ps_256:
10026     case Intrinsic::x86_avx_vtestc_pd_256:
10027       IsTestPacked = true; // Fallthrough
10028     case Intrinsic::x86_sse41_ptestc:
10029     case Intrinsic::x86_avx_ptestc_256:
10030       // CF = 1
10031       X86CC = X86::COND_B;
10032       break;
10033     case Intrinsic::x86_avx_vtestnzc_ps:
10034     case Intrinsic::x86_avx_vtestnzc_pd:
10035     case Intrinsic::x86_avx_vtestnzc_ps_256:
10036     case Intrinsic::x86_avx_vtestnzc_pd_256:
10037       IsTestPacked = true; // Fallthrough
10038     case Intrinsic::x86_sse41_ptestnzc:
10039     case Intrinsic::x86_avx_ptestnzc_256:
10040       // ZF and CF = 0
10041       X86CC = X86::COND_A;
10042       break;
10043     }
10044
10045     SDValue LHS = Op.getOperand(1);
10046     SDValue RHS = Op.getOperand(2);
10047     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10048     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10049     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10050     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10051     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10052   }
10053
10054   // SSE/AVX shift intrinsics
10055   case Intrinsic::x86_sse2_psll_w:
10056   case Intrinsic::x86_sse2_psll_d:
10057   case Intrinsic::x86_sse2_psll_q:
10058   case Intrinsic::x86_avx2_psll_w:
10059   case Intrinsic::x86_avx2_psll_d:
10060   case Intrinsic::x86_avx2_psll_q:
10061   case Intrinsic::x86_sse2_psrl_w:
10062   case Intrinsic::x86_sse2_psrl_d:
10063   case Intrinsic::x86_sse2_psrl_q:
10064   case Intrinsic::x86_avx2_psrl_w:
10065   case Intrinsic::x86_avx2_psrl_d:
10066   case Intrinsic::x86_avx2_psrl_q:
10067   case Intrinsic::x86_sse2_psra_w:
10068   case Intrinsic::x86_sse2_psra_d:
10069   case Intrinsic::x86_avx2_psra_w:
10070   case Intrinsic::x86_avx2_psra_d: {
10071     unsigned Opcode;
10072     switch (IntNo) {
10073     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10074     case Intrinsic::x86_sse2_psll_w:
10075     case Intrinsic::x86_sse2_psll_d:
10076     case Intrinsic::x86_sse2_psll_q:
10077     case Intrinsic::x86_avx2_psll_w:
10078     case Intrinsic::x86_avx2_psll_d:
10079     case Intrinsic::x86_avx2_psll_q:
10080       Opcode = X86ISD::VSHL;
10081       break;
10082     case Intrinsic::x86_sse2_psrl_w:
10083     case Intrinsic::x86_sse2_psrl_d:
10084     case Intrinsic::x86_sse2_psrl_q:
10085     case Intrinsic::x86_avx2_psrl_w:
10086     case Intrinsic::x86_avx2_psrl_d:
10087     case Intrinsic::x86_avx2_psrl_q:
10088       Opcode = X86ISD::VSRL;
10089       break;
10090     case Intrinsic::x86_sse2_psra_w:
10091     case Intrinsic::x86_sse2_psra_d:
10092     case Intrinsic::x86_avx2_psra_w:
10093     case Intrinsic::x86_avx2_psra_d:
10094       Opcode = X86ISD::VSRA;
10095       break;
10096     }
10097     return DAG.getNode(Opcode, dl, Op.getValueType(),
10098                        Op.getOperand(1), Op.getOperand(2));
10099   }
10100
10101   // SSE/AVX immediate shift intrinsics
10102   case Intrinsic::x86_sse2_pslli_w:
10103   case Intrinsic::x86_sse2_pslli_d:
10104   case Intrinsic::x86_sse2_pslli_q:
10105   case Intrinsic::x86_avx2_pslli_w:
10106   case Intrinsic::x86_avx2_pslli_d:
10107   case Intrinsic::x86_avx2_pslli_q:
10108   case Intrinsic::x86_sse2_psrli_w:
10109   case Intrinsic::x86_sse2_psrli_d:
10110   case Intrinsic::x86_sse2_psrli_q:
10111   case Intrinsic::x86_avx2_psrli_w:
10112   case Intrinsic::x86_avx2_psrli_d:
10113   case Intrinsic::x86_avx2_psrli_q:
10114   case Intrinsic::x86_sse2_psrai_w:
10115   case Intrinsic::x86_sse2_psrai_d:
10116   case Intrinsic::x86_avx2_psrai_w:
10117   case Intrinsic::x86_avx2_psrai_d: {
10118     unsigned Opcode;
10119     switch (IntNo) {
10120     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10121     case Intrinsic::x86_sse2_pslli_w:
10122     case Intrinsic::x86_sse2_pslli_d:
10123     case Intrinsic::x86_sse2_pslli_q:
10124     case Intrinsic::x86_avx2_pslli_w:
10125     case Intrinsic::x86_avx2_pslli_d:
10126     case Intrinsic::x86_avx2_pslli_q:
10127       Opcode = X86ISD::VSHLI;
10128       break;
10129     case Intrinsic::x86_sse2_psrli_w:
10130     case Intrinsic::x86_sse2_psrli_d:
10131     case Intrinsic::x86_sse2_psrli_q:
10132     case Intrinsic::x86_avx2_psrli_w:
10133     case Intrinsic::x86_avx2_psrli_d:
10134     case Intrinsic::x86_avx2_psrli_q:
10135       Opcode = X86ISD::VSRLI;
10136       break;
10137     case Intrinsic::x86_sse2_psrai_w:
10138     case Intrinsic::x86_sse2_psrai_d:
10139     case Intrinsic::x86_avx2_psrai_w:
10140     case Intrinsic::x86_avx2_psrai_d:
10141       Opcode = X86ISD::VSRAI;
10142       break;
10143     }
10144     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10145                                Op.getOperand(1), Op.getOperand(2), DAG);
10146   }
10147
10148   case Intrinsic::x86_sse42_pcmpistria128:
10149   case Intrinsic::x86_sse42_pcmpestria128:
10150   case Intrinsic::x86_sse42_pcmpistric128:
10151   case Intrinsic::x86_sse42_pcmpestric128:
10152   case Intrinsic::x86_sse42_pcmpistrio128:
10153   case Intrinsic::x86_sse42_pcmpestrio128:
10154   case Intrinsic::x86_sse42_pcmpistris128:
10155   case Intrinsic::x86_sse42_pcmpestris128:
10156   case Intrinsic::x86_sse42_pcmpistriz128:
10157   case Intrinsic::x86_sse42_pcmpestriz128: {
10158     unsigned Opcode;
10159     unsigned X86CC;
10160     switch (IntNo) {
10161     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10162     case Intrinsic::x86_sse42_pcmpistria128:
10163       Opcode = X86ISD::PCMPISTRI;
10164       X86CC = X86::COND_A;
10165       break;
10166     case Intrinsic::x86_sse42_pcmpestria128:
10167       Opcode = X86ISD::PCMPESTRI;
10168       X86CC = X86::COND_A;
10169       break;
10170     case Intrinsic::x86_sse42_pcmpistric128:
10171       Opcode = X86ISD::PCMPISTRI;
10172       X86CC = X86::COND_B;
10173       break;
10174     case Intrinsic::x86_sse42_pcmpestric128:
10175       Opcode = X86ISD::PCMPESTRI;
10176       X86CC = X86::COND_B;
10177       break;
10178     case Intrinsic::x86_sse42_pcmpistrio128:
10179       Opcode = X86ISD::PCMPISTRI;
10180       X86CC = X86::COND_O;
10181       break;
10182     case Intrinsic::x86_sse42_pcmpestrio128:
10183       Opcode = X86ISD::PCMPESTRI;
10184       X86CC = X86::COND_O;
10185       break;
10186     case Intrinsic::x86_sse42_pcmpistris128:
10187       Opcode = X86ISD::PCMPISTRI;
10188       X86CC = X86::COND_S;
10189       break;
10190     case Intrinsic::x86_sse42_pcmpestris128:
10191       Opcode = X86ISD::PCMPESTRI;
10192       X86CC = X86::COND_S;
10193       break;
10194     case Intrinsic::x86_sse42_pcmpistriz128:
10195       Opcode = X86ISD::PCMPISTRI;
10196       X86CC = X86::COND_E;
10197       break;
10198     case Intrinsic::x86_sse42_pcmpestriz128:
10199       Opcode = X86ISD::PCMPESTRI;
10200       X86CC = X86::COND_E;
10201       break;
10202     }
10203     SmallVector<SDValue, 5> NewOps;
10204     NewOps.append(Op->op_begin()+1, Op->op_end());
10205     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10206     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10207     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10208                                 DAG.getConstant(X86CC, MVT::i8),
10209                                 SDValue(PCMP.getNode(), 1));
10210     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10211   }
10212
10213   case Intrinsic::x86_sse42_pcmpistri128:
10214   case Intrinsic::x86_sse42_pcmpestri128: {
10215     unsigned Opcode;
10216     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10217       Opcode = X86ISD::PCMPISTRI;
10218     else
10219       Opcode = X86ISD::PCMPESTRI;
10220
10221     SmallVector<SDValue, 5> NewOps;
10222     NewOps.append(Op->op_begin()+1, Op->op_end());
10223     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10224     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10225   }
10226   case Intrinsic::x86_fma_vfmadd_ps:
10227   case Intrinsic::x86_fma_vfmadd_pd:
10228   case Intrinsic::x86_fma_vfmsub_ps:
10229   case Intrinsic::x86_fma_vfmsub_pd:
10230   case Intrinsic::x86_fma_vfnmadd_ps:
10231   case Intrinsic::x86_fma_vfnmadd_pd:
10232   case Intrinsic::x86_fma_vfnmsub_ps:
10233   case Intrinsic::x86_fma_vfnmsub_pd:
10234   case Intrinsic::x86_fma_vfmaddsub_ps:
10235   case Intrinsic::x86_fma_vfmaddsub_pd:
10236   case Intrinsic::x86_fma_vfmsubadd_ps:
10237   case Intrinsic::x86_fma_vfmsubadd_pd:
10238   case Intrinsic::x86_fma_vfmadd_ps_256:
10239   case Intrinsic::x86_fma_vfmadd_pd_256:
10240   case Intrinsic::x86_fma_vfmsub_ps_256:
10241   case Intrinsic::x86_fma_vfmsub_pd_256:
10242   case Intrinsic::x86_fma_vfnmadd_ps_256:
10243   case Intrinsic::x86_fma_vfnmadd_pd_256:
10244   case Intrinsic::x86_fma_vfnmsub_ps_256:
10245   case Intrinsic::x86_fma_vfnmsub_pd_256:
10246   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10247   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10248   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10249   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10250     unsigned Opc;
10251     switch (IntNo) {
10252     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10253     case Intrinsic::x86_fma_vfmadd_ps:
10254     case Intrinsic::x86_fma_vfmadd_pd:
10255     case Intrinsic::x86_fma_vfmadd_ps_256:
10256     case Intrinsic::x86_fma_vfmadd_pd_256:
10257       Opc = X86ISD::FMADD;
10258       break;
10259     case Intrinsic::x86_fma_vfmsub_ps:
10260     case Intrinsic::x86_fma_vfmsub_pd:
10261     case Intrinsic::x86_fma_vfmsub_ps_256:
10262     case Intrinsic::x86_fma_vfmsub_pd_256:
10263       Opc = X86ISD::FMSUB;
10264       break;
10265     case Intrinsic::x86_fma_vfnmadd_ps:
10266     case Intrinsic::x86_fma_vfnmadd_pd:
10267     case Intrinsic::x86_fma_vfnmadd_ps_256:
10268     case Intrinsic::x86_fma_vfnmadd_pd_256:
10269       Opc = X86ISD::FNMADD;
10270       break;
10271     case Intrinsic::x86_fma_vfnmsub_ps:
10272     case Intrinsic::x86_fma_vfnmsub_pd:
10273     case Intrinsic::x86_fma_vfnmsub_ps_256:
10274     case Intrinsic::x86_fma_vfnmsub_pd_256:
10275       Opc = X86ISD::FNMSUB;
10276       break;
10277     case Intrinsic::x86_fma_vfmaddsub_ps:
10278     case Intrinsic::x86_fma_vfmaddsub_pd:
10279     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10280     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10281       Opc = X86ISD::FMADDSUB;
10282       break;
10283     case Intrinsic::x86_fma_vfmsubadd_ps:
10284     case Intrinsic::x86_fma_vfmsubadd_pd:
10285     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10286     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10287       Opc = X86ISD::FMSUBADD;
10288       break;
10289     }
10290
10291     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10292                        Op.getOperand(2), Op.getOperand(3));
10293   }
10294   }
10295 }
10296
10297 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10298   DebugLoc dl = Op.getDebugLoc();
10299   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10300   switch (IntNo) {
10301   default: return SDValue();    // Don't custom lower most intrinsics.
10302
10303   // RDRAND intrinsics.
10304   case Intrinsic::x86_rdrand_16:
10305   case Intrinsic::x86_rdrand_32:
10306   case Intrinsic::x86_rdrand_64: {
10307     // Emit the node with the right value type.
10308     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10309     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10310
10311     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10312     // return the value from Rand, which is always 0, casted to i32.
10313     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10314                       DAG.getConstant(1, Op->getValueType(1)),
10315                       DAG.getConstant(X86::COND_B, MVT::i32),
10316                       SDValue(Result.getNode(), 1) };
10317     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10318                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10319                                   Ops, 4);
10320
10321     // Return { result, isValid, chain }.
10322     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10323                        SDValue(Result.getNode(), 2));
10324   }
10325   }
10326 }
10327
10328 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10329                                            SelectionDAG &DAG) const {
10330   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10331   MFI->setReturnAddressIsTaken(true);
10332
10333   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10334   DebugLoc dl = Op.getDebugLoc();
10335
10336   if (Depth > 0) {
10337     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10338     SDValue Offset =
10339       DAG.getConstant(TD->getPointerSize(0),
10340                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10341     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10342                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10343                                    FrameAddr, Offset),
10344                        MachinePointerInfo(), false, false, false, 0);
10345   }
10346
10347   // Just load the return address.
10348   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10349   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10350                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10351 }
10352
10353 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10354   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10355   MFI->setFrameAddressIsTaken(true);
10356
10357   EVT VT = Op.getValueType();
10358   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10359   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10360   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10361   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10362   while (Depth--)
10363     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10364                             MachinePointerInfo(),
10365                             false, false, false, 0);
10366   return FrameAddr;
10367 }
10368
10369 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10370                                                      SelectionDAG &DAG) const {
10371   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10372 }
10373
10374 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10375   SDValue Chain     = Op.getOperand(0);
10376   SDValue Offset    = Op.getOperand(1);
10377   SDValue Handler   = Op.getOperand(2);
10378   DebugLoc dl       = Op.getDebugLoc();
10379
10380   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10381                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10382                                      getPointerTy());
10383   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10384
10385   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10386                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10387   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10388   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10389                        false, false, 0);
10390   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10391
10392   return DAG.getNode(X86ISD::EH_RETURN, dl,
10393                      MVT::Other,
10394                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10395 }
10396
10397 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10398                                                SelectionDAG &DAG) const {
10399   DebugLoc DL = Op.getDebugLoc();
10400   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10401                      DAG.getVTList(MVT::i32, MVT::Other),
10402                      Op.getOperand(0), Op.getOperand(1));
10403 }
10404
10405 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10406                                                 SelectionDAG &DAG) const {
10407   DebugLoc DL = Op.getDebugLoc();
10408   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10409                      Op.getOperand(0), Op.getOperand(1));
10410 }
10411
10412 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10413   return Op.getOperand(0);
10414 }
10415
10416 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10417                                                 SelectionDAG &DAG) const {
10418   SDValue Root = Op.getOperand(0);
10419   SDValue Trmp = Op.getOperand(1); // trampoline
10420   SDValue FPtr = Op.getOperand(2); // nested function
10421   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10422   DebugLoc dl  = Op.getDebugLoc();
10423
10424   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10425   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10426
10427   if (Subtarget->is64Bit()) {
10428     SDValue OutChains[6];
10429
10430     // Large code-model.
10431     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10432     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10433
10434     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10435     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10436
10437     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10438
10439     // Load the pointer to the nested function into R11.
10440     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10441     SDValue Addr = Trmp;
10442     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10443                                 Addr, MachinePointerInfo(TrmpAddr),
10444                                 false, false, 0);
10445
10446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10447                        DAG.getConstant(2, MVT::i64));
10448     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10449                                 MachinePointerInfo(TrmpAddr, 2),
10450                                 false, false, 2);
10451
10452     // Load the 'nest' parameter value into R10.
10453     // R10 is specified in X86CallingConv.td
10454     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10455     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10456                        DAG.getConstant(10, MVT::i64));
10457     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10458                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10459                                 false, false, 0);
10460
10461     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10462                        DAG.getConstant(12, MVT::i64));
10463     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10464                                 MachinePointerInfo(TrmpAddr, 12),
10465                                 false, false, 2);
10466
10467     // Jump to the nested function.
10468     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10469     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10470                        DAG.getConstant(20, MVT::i64));
10471     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10472                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10473                                 false, false, 0);
10474
10475     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10476     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10477                        DAG.getConstant(22, MVT::i64));
10478     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10479                                 MachinePointerInfo(TrmpAddr, 22),
10480                                 false, false, 0);
10481
10482     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10483   } else {
10484     const Function *Func =
10485       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10486     CallingConv::ID CC = Func->getCallingConv();
10487     unsigned NestReg;
10488
10489     switch (CC) {
10490     default:
10491       llvm_unreachable("Unsupported calling convention");
10492     case CallingConv::C:
10493     case CallingConv::X86_StdCall: {
10494       // Pass 'nest' parameter in ECX.
10495       // Must be kept in sync with X86CallingConv.td
10496       NestReg = X86::ECX;
10497
10498       // Check that ECX wasn't needed by an 'inreg' parameter.
10499       FunctionType *FTy = Func->getFunctionType();
10500       const AttrListPtr &Attrs = Func->getAttributes();
10501
10502       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10503         unsigned InRegCount = 0;
10504         unsigned Idx = 1;
10505
10506         for (FunctionType::param_iterator I = FTy->param_begin(),
10507              E = FTy->param_end(); I != E; ++I, ++Idx)
10508           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10509             // FIXME: should only count parameters that are lowered to integers.
10510             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10511
10512         if (InRegCount > 2) {
10513           report_fatal_error("Nest register in use - reduce number of inreg"
10514                              " parameters!");
10515         }
10516       }
10517       break;
10518     }
10519     case CallingConv::X86_FastCall:
10520     case CallingConv::X86_ThisCall:
10521     case CallingConv::Fast:
10522       // Pass 'nest' parameter in EAX.
10523       // Must be kept in sync with X86CallingConv.td
10524       NestReg = X86::EAX;
10525       break;
10526     }
10527
10528     SDValue OutChains[4];
10529     SDValue Addr, Disp;
10530
10531     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10532                        DAG.getConstant(10, MVT::i32));
10533     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10534
10535     // This is storing the opcode for MOV32ri.
10536     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10537     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10538     OutChains[0] = DAG.getStore(Root, dl,
10539                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10540                                 Trmp, MachinePointerInfo(TrmpAddr),
10541                                 false, false, 0);
10542
10543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10544                        DAG.getConstant(1, MVT::i32));
10545     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10546                                 MachinePointerInfo(TrmpAddr, 1),
10547                                 false, false, 1);
10548
10549     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10550     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10551                        DAG.getConstant(5, MVT::i32));
10552     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10553                                 MachinePointerInfo(TrmpAddr, 5),
10554                                 false, false, 1);
10555
10556     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10557                        DAG.getConstant(6, MVT::i32));
10558     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10559                                 MachinePointerInfo(TrmpAddr, 6),
10560                                 false, false, 1);
10561
10562     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10563   }
10564 }
10565
10566 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10567                                             SelectionDAG &DAG) const {
10568   /*
10569    The rounding mode is in bits 11:10 of FPSR, and has the following
10570    settings:
10571      00 Round to nearest
10572      01 Round to -inf
10573      10 Round to +inf
10574      11 Round to 0
10575
10576   FLT_ROUNDS, on the other hand, expects the following:
10577     -1 Undefined
10578      0 Round to 0
10579      1 Round to nearest
10580      2 Round to +inf
10581      3 Round to -inf
10582
10583   To perform the conversion, we do:
10584     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10585   */
10586
10587   MachineFunction &MF = DAG.getMachineFunction();
10588   const TargetMachine &TM = MF.getTarget();
10589   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10590   unsigned StackAlignment = TFI.getStackAlignment();
10591   EVT VT = Op.getValueType();
10592   DebugLoc DL = Op.getDebugLoc();
10593
10594   // Save FP Control Word to stack slot
10595   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10596   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10597
10598
10599   MachineMemOperand *MMO =
10600    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10601                            MachineMemOperand::MOStore, 2, 2);
10602
10603   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10604   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10605                                           DAG.getVTList(MVT::Other),
10606                                           Ops, 2, MVT::i16, MMO);
10607
10608   // Load FP Control Word from stack slot
10609   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10610                             MachinePointerInfo(), false, false, false, 0);
10611
10612   // Transform as necessary
10613   SDValue CWD1 =
10614     DAG.getNode(ISD::SRL, DL, MVT::i16,
10615                 DAG.getNode(ISD::AND, DL, MVT::i16,
10616                             CWD, DAG.getConstant(0x800, MVT::i16)),
10617                 DAG.getConstant(11, MVT::i8));
10618   SDValue CWD2 =
10619     DAG.getNode(ISD::SRL, DL, MVT::i16,
10620                 DAG.getNode(ISD::AND, DL, MVT::i16,
10621                             CWD, DAG.getConstant(0x400, MVT::i16)),
10622                 DAG.getConstant(9, MVT::i8));
10623
10624   SDValue RetVal =
10625     DAG.getNode(ISD::AND, DL, MVT::i16,
10626                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10627                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10628                             DAG.getConstant(1, MVT::i16)),
10629                 DAG.getConstant(3, MVT::i16));
10630
10631
10632   return DAG.getNode((VT.getSizeInBits() < 16 ?
10633                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10634 }
10635
10636 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10637   EVT VT = Op.getValueType();
10638   EVT OpVT = VT;
10639   unsigned NumBits = VT.getSizeInBits();
10640   DebugLoc dl = Op.getDebugLoc();
10641
10642   Op = Op.getOperand(0);
10643   if (VT == MVT::i8) {
10644     // Zero extend to i32 since there is not an i8 bsr.
10645     OpVT = MVT::i32;
10646     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10647   }
10648
10649   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10650   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10651   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10652
10653   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10654   SDValue Ops[] = {
10655     Op,
10656     DAG.getConstant(NumBits+NumBits-1, OpVT),
10657     DAG.getConstant(X86::COND_E, MVT::i8),
10658     Op.getValue(1)
10659   };
10660   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10661
10662   // Finally xor with NumBits-1.
10663   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10664
10665   if (VT == MVT::i8)
10666     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10667   return Op;
10668 }
10669
10670 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10671   EVT VT = Op.getValueType();
10672   EVT OpVT = VT;
10673   unsigned NumBits = VT.getSizeInBits();
10674   DebugLoc dl = Op.getDebugLoc();
10675
10676   Op = Op.getOperand(0);
10677   if (VT == MVT::i8) {
10678     // Zero extend to i32 since there is not an i8 bsr.
10679     OpVT = MVT::i32;
10680     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10681   }
10682
10683   // Issue a bsr (scan bits in reverse).
10684   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10685   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10686
10687   // And xor with NumBits-1.
10688   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10689
10690   if (VT == MVT::i8)
10691     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10692   return Op;
10693 }
10694
10695 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10696   EVT VT = Op.getValueType();
10697   unsigned NumBits = VT.getSizeInBits();
10698   DebugLoc dl = Op.getDebugLoc();
10699   Op = Op.getOperand(0);
10700
10701   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10702   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10703   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10704
10705   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10706   SDValue Ops[] = {
10707     Op,
10708     DAG.getConstant(NumBits, VT),
10709     DAG.getConstant(X86::COND_E, MVT::i8),
10710     Op.getValue(1)
10711   };
10712   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10713 }
10714
10715 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10716 // ones, and then concatenate the result back.
10717 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10718   EVT VT = Op.getValueType();
10719
10720   assert(VT.is256BitVector() && VT.isInteger() &&
10721          "Unsupported value type for operation");
10722
10723   unsigned NumElems = VT.getVectorNumElements();
10724   DebugLoc dl = Op.getDebugLoc();
10725
10726   // Extract the LHS vectors
10727   SDValue LHS = Op.getOperand(0);
10728   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10729   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10730
10731   // Extract the RHS vectors
10732   SDValue RHS = Op.getOperand(1);
10733   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10734   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10735
10736   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10737   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10738
10739   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10740                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10741                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10742 }
10743
10744 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10745   assert(Op.getValueType().is256BitVector() &&
10746          Op.getValueType().isInteger() &&
10747          "Only handle AVX 256-bit vector integer operation");
10748   return Lower256IntArith(Op, DAG);
10749 }
10750
10751 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10752   assert(Op.getValueType().is256BitVector() &&
10753          Op.getValueType().isInteger() &&
10754          "Only handle AVX 256-bit vector integer operation");
10755   return Lower256IntArith(Op, DAG);
10756 }
10757
10758 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10759                         SelectionDAG &DAG) {
10760   EVT VT = Op.getValueType();
10761
10762   // Decompose 256-bit ops into smaller 128-bit ops.
10763   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10764     return Lower256IntArith(Op, DAG);
10765
10766   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10767          "Only know how to lower V2I64/V4I64 multiply");
10768
10769   DebugLoc dl = Op.getDebugLoc();
10770
10771   //  Ahi = psrlqi(a, 32);
10772   //  Bhi = psrlqi(b, 32);
10773   //
10774   //  AloBlo = pmuludq(a, b);
10775   //  AloBhi = pmuludq(a, Bhi);
10776   //  AhiBlo = pmuludq(Ahi, b);
10777
10778   //  AloBhi = psllqi(AloBhi, 32);
10779   //  AhiBlo = psllqi(AhiBlo, 32);
10780   //  return AloBlo + AloBhi + AhiBlo;
10781
10782   SDValue A = Op.getOperand(0);
10783   SDValue B = Op.getOperand(1);
10784
10785   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10786
10787   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10788   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10789
10790   // Bit cast to 32-bit vectors for MULUDQ
10791   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10792   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10793   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10794   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10795   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10796
10797   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10798   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10799   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10800
10801   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10802   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10803
10804   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10805   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10806 }
10807
10808 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10809
10810   EVT VT = Op.getValueType();
10811   DebugLoc dl = Op.getDebugLoc();
10812   SDValue R = Op.getOperand(0);
10813   SDValue Amt = Op.getOperand(1);
10814   LLVMContext *Context = DAG.getContext();
10815
10816   if (!Subtarget->hasSSE2())
10817     return SDValue();
10818
10819   // Optimize shl/srl/sra with constant shift amount.
10820   if (isSplatVector(Amt.getNode())) {
10821     SDValue SclrAmt = Amt->getOperand(0);
10822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10823       uint64_t ShiftAmt = C->getZExtValue();
10824
10825       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10826           (Subtarget->hasAVX2() &&
10827            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10828         if (Op.getOpcode() == ISD::SHL)
10829           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10830                              DAG.getConstant(ShiftAmt, MVT::i32));
10831         if (Op.getOpcode() == ISD::SRL)
10832           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10833                              DAG.getConstant(ShiftAmt, MVT::i32));
10834         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10835           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10836                              DAG.getConstant(ShiftAmt, MVT::i32));
10837       }
10838
10839       if (VT == MVT::v16i8) {
10840         if (Op.getOpcode() == ISD::SHL) {
10841           // Make a large shift.
10842           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10843                                     DAG.getConstant(ShiftAmt, MVT::i32));
10844           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10845           // Zero out the rightmost bits.
10846           SmallVector<SDValue, 16> V(16,
10847                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10848                                                      MVT::i8));
10849           return DAG.getNode(ISD::AND, dl, VT, SHL,
10850                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10851         }
10852         if (Op.getOpcode() == ISD::SRL) {
10853           // Make a large shift.
10854           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10855                                     DAG.getConstant(ShiftAmt, MVT::i32));
10856           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10857           // Zero out the leftmost bits.
10858           SmallVector<SDValue, 16> V(16,
10859                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10860                                                      MVT::i8));
10861           return DAG.getNode(ISD::AND, dl, VT, SRL,
10862                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10863         }
10864         if (Op.getOpcode() == ISD::SRA) {
10865           if (ShiftAmt == 7) {
10866             // R s>> 7  ===  R s< 0
10867             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10868             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10869           }
10870
10871           // R s>> a === ((R u>> a) ^ m) - m
10872           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10873           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10874                                                          MVT::i8));
10875           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10876           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10877           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10878           return Res;
10879         }
10880         llvm_unreachable("Unknown shift opcode.");
10881       }
10882
10883       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10884         if (Op.getOpcode() == ISD::SHL) {
10885           // Make a large shift.
10886           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10887                                     DAG.getConstant(ShiftAmt, MVT::i32));
10888           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10889           // Zero out the rightmost bits.
10890           SmallVector<SDValue, 32> V(32,
10891                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10892                                                      MVT::i8));
10893           return DAG.getNode(ISD::AND, dl, VT, SHL,
10894                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10895         }
10896         if (Op.getOpcode() == ISD::SRL) {
10897           // Make a large shift.
10898           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10899                                     DAG.getConstant(ShiftAmt, MVT::i32));
10900           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10901           // Zero out the leftmost bits.
10902           SmallVector<SDValue, 32> V(32,
10903                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10904                                                      MVT::i8));
10905           return DAG.getNode(ISD::AND, dl, VT, SRL,
10906                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10907         }
10908         if (Op.getOpcode() == ISD::SRA) {
10909           if (ShiftAmt == 7) {
10910             // R s>> 7  ===  R s< 0
10911             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10912             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10913           }
10914
10915           // R s>> a === ((R u>> a) ^ m) - m
10916           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10917           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10918                                                          MVT::i8));
10919           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10920           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10921           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10922           return Res;
10923         }
10924         llvm_unreachable("Unknown shift opcode.");
10925       }
10926     }
10927   }
10928
10929   // Lower SHL with variable shift amount.
10930   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10931     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10932                      DAG.getConstant(23, MVT::i32));
10933
10934     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10935     Constant *C = ConstantDataVector::get(*Context, CV);
10936     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10937     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10938                                  MachinePointerInfo::getConstantPool(),
10939                                  false, false, false, 16);
10940
10941     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10942     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10943     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10944     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10945   }
10946   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10947     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10948
10949     // a = a << 5;
10950     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10951                      DAG.getConstant(5, MVT::i32));
10952     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10953
10954     // Turn 'a' into a mask suitable for VSELECT
10955     SDValue VSelM = DAG.getConstant(0x80, VT);
10956     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10957     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10958
10959     SDValue CM1 = DAG.getConstant(0x0f, VT);
10960     SDValue CM2 = DAG.getConstant(0x3f, VT);
10961
10962     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10963     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10964     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10965                             DAG.getConstant(4, MVT::i32), DAG);
10966     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10967     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10968
10969     // a += a
10970     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10971     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10972     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10973
10974     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10975     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10976     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10977                             DAG.getConstant(2, MVT::i32), DAG);
10978     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10979     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10980
10981     // a += a
10982     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10983     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10984     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10985
10986     // return VSELECT(r, r+r, a);
10987     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10988                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10989     return R;
10990   }
10991
10992   // Decompose 256-bit shifts into smaller 128-bit shifts.
10993   if (VT.is256BitVector()) {
10994     unsigned NumElems = VT.getVectorNumElements();
10995     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10996     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10997
10998     // Extract the two vectors
10999     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11000     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11001
11002     // Recreate the shift amount vectors
11003     SDValue Amt1, Amt2;
11004     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11005       // Constant shift amount
11006       SmallVector<SDValue, 4> Amt1Csts;
11007       SmallVector<SDValue, 4> Amt2Csts;
11008       for (unsigned i = 0; i != NumElems/2; ++i)
11009         Amt1Csts.push_back(Amt->getOperand(i));
11010       for (unsigned i = NumElems/2; i != NumElems; ++i)
11011         Amt2Csts.push_back(Amt->getOperand(i));
11012
11013       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11014                                  &Amt1Csts[0], NumElems/2);
11015       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11016                                  &Amt2Csts[0], NumElems/2);
11017     } else {
11018       // Variable shift amount
11019       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11020       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11021     }
11022
11023     // Issue new vector shifts for the smaller types
11024     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11025     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11026
11027     // Concatenate the result back
11028     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11029   }
11030
11031   return SDValue();
11032 }
11033
11034 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11035   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11036   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11037   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11038   // has only one use.
11039   SDNode *N = Op.getNode();
11040   SDValue LHS = N->getOperand(0);
11041   SDValue RHS = N->getOperand(1);
11042   unsigned BaseOp = 0;
11043   unsigned Cond = 0;
11044   DebugLoc DL = Op.getDebugLoc();
11045   switch (Op.getOpcode()) {
11046   default: llvm_unreachable("Unknown ovf instruction!");
11047   case ISD::SADDO:
11048     // A subtract of one will be selected as a INC. Note that INC doesn't
11049     // set CF, so we can't do this for UADDO.
11050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11051       if (C->isOne()) {
11052         BaseOp = X86ISD::INC;
11053         Cond = X86::COND_O;
11054         break;
11055       }
11056     BaseOp = X86ISD::ADD;
11057     Cond = X86::COND_O;
11058     break;
11059   case ISD::UADDO:
11060     BaseOp = X86ISD::ADD;
11061     Cond = X86::COND_B;
11062     break;
11063   case ISD::SSUBO:
11064     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11065     // set CF, so we can't do this for USUBO.
11066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11067       if (C->isOne()) {
11068         BaseOp = X86ISD::DEC;
11069         Cond = X86::COND_O;
11070         break;
11071       }
11072     BaseOp = X86ISD::SUB;
11073     Cond = X86::COND_O;
11074     break;
11075   case ISD::USUBO:
11076     BaseOp = X86ISD::SUB;
11077     Cond = X86::COND_B;
11078     break;
11079   case ISD::SMULO:
11080     BaseOp = X86ISD::SMUL;
11081     Cond = X86::COND_O;
11082     break;
11083   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11084     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11085                                  MVT::i32);
11086     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11087
11088     SDValue SetCC =
11089       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11090                   DAG.getConstant(X86::COND_O, MVT::i32),
11091                   SDValue(Sum.getNode(), 2));
11092
11093     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11094   }
11095   }
11096
11097   // Also sets EFLAGS.
11098   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11099   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11100
11101   SDValue SetCC =
11102     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11103                 DAG.getConstant(Cond, MVT::i32),
11104                 SDValue(Sum.getNode(), 1));
11105
11106   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11107 }
11108
11109 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11110                                                   SelectionDAG &DAG) const {
11111   DebugLoc dl = Op.getDebugLoc();
11112   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11113   EVT VT = Op.getValueType();
11114
11115   if (!Subtarget->hasSSE2() || !VT.isVector())
11116     return SDValue();
11117
11118   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11119                       ExtraVT.getScalarType().getSizeInBits();
11120   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11121
11122   switch (VT.getSimpleVT().SimpleTy) {
11123     default: return SDValue();
11124     case MVT::v8i32:
11125     case MVT::v16i16:
11126       if (!Subtarget->hasAVX())
11127         return SDValue();
11128       if (!Subtarget->hasAVX2()) {
11129         // needs to be split
11130         unsigned NumElems = VT.getVectorNumElements();
11131
11132         // Extract the LHS vectors
11133         SDValue LHS = Op.getOperand(0);
11134         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11135         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11136
11137         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11138         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11139
11140         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11141         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11142         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11143                                    ExtraNumElems/2);
11144         SDValue Extra = DAG.getValueType(ExtraVT);
11145
11146         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11147         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11148
11149         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11150       }
11151       // fall through
11152     case MVT::v4i32:
11153     case MVT::v8i16: {
11154       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11155                                          Op.getOperand(0), ShAmt, DAG);
11156       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11157     }
11158   }
11159 }
11160
11161
11162 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11163                               SelectionDAG &DAG) {
11164   DebugLoc dl = Op.getDebugLoc();
11165
11166   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11167   // There isn't any reason to disable it if the target processor supports it.
11168   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11169     SDValue Chain = Op.getOperand(0);
11170     SDValue Zero = DAG.getConstant(0, MVT::i32);
11171     SDValue Ops[] = {
11172       DAG.getRegister(X86::ESP, MVT::i32), // Base
11173       DAG.getTargetConstant(1, MVT::i8),   // Scale
11174       DAG.getRegister(0, MVT::i32),        // Index
11175       DAG.getTargetConstant(0, MVT::i32),  // Disp
11176       DAG.getRegister(0, MVT::i32),        // Segment.
11177       Zero,
11178       Chain
11179     };
11180     SDNode *Res =
11181       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11182                           array_lengthof(Ops));
11183     return SDValue(Res, 0);
11184   }
11185
11186   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11187   if (!isDev)
11188     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11189
11190   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11191   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11192   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11193   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11194
11195   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11196   if (!Op1 && !Op2 && !Op3 && Op4)
11197     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11198
11199   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11200   if (Op1 && !Op2 && !Op3 && !Op4)
11201     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11202
11203   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11204   //           (MFENCE)>;
11205   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11206 }
11207
11208 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11209                                  SelectionDAG &DAG) {
11210   DebugLoc dl = Op.getDebugLoc();
11211   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11212     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11213   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11214     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11215
11216   // The only fence that needs an instruction is a sequentially-consistent
11217   // cross-thread fence.
11218   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11219     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11220     // no-sse2). There isn't any reason to disable it if the target processor
11221     // supports it.
11222     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11223       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11224
11225     SDValue Chain = Op.getOperand(0);
11226     SDValue Zero = DAG.getConstant(0, MVT::i32);
11227     SDValue Ops[] = {
11228       DAG.getRegister(X86::ESP, MVT::i32), // Base
11229       DAG.getTargetConstant(1, MVT::i8),   // Scale
11230       DAG.getRegister(0, MVT::i32),        // Index
11231       DAG.getTargetConstant(0, MVT::i32),  // Disp
11232       DAG.getRegister(0, MVT::i32),        // Segment.
11233       Zero,
11234       Chain
11235     };
11236     SDNode *Res =
11237       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11238                          array_lengthof(Ops));
11239     return SDValue(Res, 0);
11240   }
11241
11242   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11243   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11244 }
11245
11246
11247 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11248                              SelectionDAG &DAG) {
11249   EVT T = Op.getValueType();
11250   DebugLoc DL = Op.getDebugLoc();
11251   unsigned Reg = 0;
11252   unsigned size = 0;
11253   switch(T.getSimpleVT().SimpleTy) {
11254   default: llvm_unreachable("Invalid value type!");
11255   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11256   case MVT::i16: Reg = X86::AX;  size = 2; break;
11257   case MVT::i32: Reg = X86::EAX; size = 4; break;
11258   case MVT::i64:
11259     assert(Subtarget->is64Bit() && "Node not type legal!");
11260     Reg = X86::RAX; size = 8;
11261     break;
11262   }
11263   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11264                                     Op.getOperand(2), SDValue());
11265   SDValue Ops[] = { cpIn.getValue(0),
11266                     Op.getOperand(1),
11267                     Op.getOperand(3),
11268                     DAG.getTargetConstant(size, MVT::i8),
11269                     cpIn.getValue(1) };
11270   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11271   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11272   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11273                                            Ops, 5, T, MMO);
11274   SDValue cpOut =
11275     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11276   return cpOut;
11277 }
11278
11279 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11280                                      SelectionDAG &DAG) {
11281   assert(Subtarget->is64Bit() && "Result not type legalized?");
11282   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11283   SDValue TheChain = Op.getOperand(0);
11284   DebugLoc dl = Op.getDebugLoc();
11285   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11286   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11287   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11288                                    rax.getValue(2));
11289   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11290                             DAG.getConstant(32, MVT::i8));
11291   SDValue Ops[] = {
11292     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11293     rdx.getValue(1)
11294   };
11295   return DAG.getMergeValues(Ops, 2, dl);
11296 }
11297
11298 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11299   EVT SrcVT = Op.getOperand(0).getValueType();
11300   EVT DstVT = Op.getValueType();
11301   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11302          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11303   assert((DstVT == MVT::i64 ||
11304           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11305          "Unexpected custom BITCAST");
11306   // i64 <=> MMX conversions are Legal.
11307   if (SrcVT==MVT::i64 && DstVT.isVector())
11308     return Op;
11309   if (DstVT==MVT::i64 && SrcVT.isVector())
11310     return Op;
11311   // MMX <=> MMX conversions are Legal.
11312   if (SrcVT.isVector() && DstVT.isVector())
11313     return Op;
11314   // All other conversions need to be expanded.
11315   return SDValue();
11316 }
11317
11318 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11319   SDNode *Node = Op.getNode();
11320   DebugLoc dl = Node->getDebugLoc();
11321   EVT T = Node->getValueType(0);
11322   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11323                               DAG.getConstant(0, T), Node->getOperand(2));
11324   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11325                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11326                        Node->getOperand(0),
11327                        Node->getOperand(1), negOp,
11328                        cast<AtomicSDNode>(Node)->getSrcValue(),
11329                        cast<AtomicSDNode>(Node)->getAlignment(),
11330                        cast<AtomicSDNode>(Node)->getOrdering(),
11331                        cast<AtomicSDNode>(Node)->getSynchScope());
11332 }
11333
11334 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11335   SDNode *Node = Op.getNode();
11336   DebugLoc dl = Node->getDebugLoc();
11337   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11338
11339   // Convert seq_cst store -> xchg
11340   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11341   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11342   //        (The only way to get a 16-byte store is cmpxchg16b)
11343   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11344   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11345       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11346     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11347                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11348                                  Node->getOperand(0),
11349                                  Node->getOperand(1), Node->getOperand(2),
11350                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11351                                  cast<AtomicSDNode>(Node)->getOrdering(),
11352                                  cast<AtomicSDNode>(Node)->getSynchScope());
11353     return Swap.getValue(1);
11354   }
11355   // Other atomic stores have a simple pattern.
11356   return Op;
11357 }
11358
11359 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11360   EVT VT = Op.getNode()->getValueType(0);
11361
11362   // Let legalize expand this if it isn't a legal type yet.
11363   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11364     return SDValue();
11365
11366   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11367
11368   unsigned Opc;
11369   bool ExtraOp = false;
11370   switch (Op.getOpcode()) {
11371   default: llvm_unreachable("Invalid code");
11372   case ISD::ADDC: Opc = X86ISD::ADD; break;
11373   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11374   case ISD::SUBC: Opc = X86ISD::SUB; break;
11375   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11376   }
11377
11378   if (!ExtraOp)
11379     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11380                        Op.getOperand(1));
11381   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11382                      Op.getOperand(1), Op.getOperand(2));
11383 }
11384
11385 /// LowerOperation - Provide custom lowering hooks for some operations.
11386 ///
11387 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11388   switch (Op.getOpcode()) {
11389   default: llvm_unreachable("Should not custom lower this!");
11390   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11391   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11392   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11393   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11394   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11395   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11396   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11397   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11398   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11399   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11400   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11401   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11402   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11403   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11404   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11405   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11406   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11407   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11408   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11409   case ISD::SHL_PARTS:
11410   case ISD::SRA_PARTS:
11411   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11412   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11413   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11414   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11415   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11416   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11417   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11418   case ISD::FABS:               return LowerFABS(Op, DAG);
11419   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11420   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11421   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11422   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11423   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11424   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11425   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11426   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11427   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11428   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11429   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11430   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11431   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11432   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11433   case ISD::FRAME_TO_ARGS_OFFSET:
11434                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11435   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11436   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11437   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11438   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11439   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11440   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11441   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11442   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11443   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11444   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11445   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11446   case ISD::SRA:
11447   case ISD::SRL:
11448   case ISD::SHL:                return LowerShift(Op, DAG);
11449   case ISD::SADDO:
11450   case ISD::UADDO:
11451   case ISD::SSUBO:
11452   case ISD::USUBO:
11453   case ISD::SMULO:
11454   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11455   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11456   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11457   case ISD::ADDC:
11458   case ISD::ADDE:
11459   case ISD::SUBC:
11460   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11461   case ISD::ADD:                return LowerADD(Op, DAG);
11462   case ISD::SUB:                return LowerSUB(Op, DAG);
11463   }
11464 }
11465
11466 static void ReplaceATOMIC_LOAD(SDNode *Node,
11467                                   SmallVectorImpl<SDValue> &Results,
11468                                   SelectionDAG &DAG) {
11469   DebugLoc dl = Node->getDebugLoc();
11470   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11471
11472   // Convert wide load -> cmpxchg8b/cmpxchg16b
11473   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11474   //        (The only way to get a 16-byte load is cmpxchg16b)
11475   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11476   SDValue Zero = DAG.getConstant(0, VT);
11477   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11478                                Node->getOperand(0),
11479                                Node->getOperand(1), Zero, Zero,
11480                                cast<AtomicSDNode>(Node)->getMemOperand(),
11481                                cast<AtomicSDNode>(Node)->getOrdering(),
11482                                cast<AtomicSDNode>(Node)->getSynchScope());
11483   Results.push_back(Swap.getValue(0));
11484   Results.push_back(Swap.getValue(1));
11485 }
11486
11487 static void
11488 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11489                         SelectionDAG &DAG, unsigned NewOp) {
11490   DebugLoc dl = Node->getDebugLoc();
11491   assert (Node->getValueType(0) == MVT::i64 &&
11492           "Only know how to expand i64 atomics");
11493
11494   SDValue Chain = Node->getOperand(0);
11495   SDValue In1 = Node->getOperand(1);
11496   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11497                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11498   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11499                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11500   SDValue Ops[] = { Chain, In1, In2L, In2H };
11501   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11502   SDValue Result =
11503     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11504                             cast<MemSDNode>(Node)->getMemOperand());
11505   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11506   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11507   Results.push_back(Result.getValue(2));
11508 }
11509
11510 /// ReplaceNodeResults - Replace a node with an illegal result type
11511 /// with a new node built out of custom code.
11512 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11513                                            SmallVectorImpl<SDValue>&Results,
11514                                            SelectionDAG &DAG) const {
11515   DebugLoc dl = N->getDebugLoc();
11516   switch (N->getOpcode()) {
11517   default:
11518     llvm_unreachable("Do not know how to custom type legalize this operation!");
11519   case ISD::SIGN_EXTEND_INREG:
11520   case ISD::ADDC:
11521   case ISD::ADDE:
11522   case ISD::SUBC:
11523   case ISD::SUBE:
11524     // We don't want to expand or promote these.
11525     return;
11526   case ISD::FP_TO_SINT:
11527   case ISD::FP_TO_UINT: {
11528     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11529
11530     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11531       return;
11532
11533     std::pair<SDValue,SDValue> Vals =
11534         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11535     SDValue FIST = Vals.first, StackSlot = Vals.second;
11536     if (FIST.getNode() != 0) {
11537       EVT VT = N->getValueType(0);
11538       // Return a load from the stack slot.
11539       if (StackSlot.getNode() != 0)
11540         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11541                                       MachinePointerInfo(),
11542                                       false, false, false, 0));
11543       else
11544         Results.push_back(FIST);
11545     }
11546     return;
11547   }
11548   case ISD::FP_ROUND: {
11549     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11550     Results.push_back(V);
11551     return;
11552   }
11553   case ISD::READCYCLECOUNTER: {
11554     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11555     SDValue TheChain = N->getOperand(0);
11556     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11557     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11558                                      rd.getValue(1));
11559     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11560                                      eax.getValue(2));
11561     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11562     SDValue Ops[] = { eax, edx };
11563     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11564     Results.push_back(edx.getValue(1));
11565     return;
11566   }
11567   case ISD::ATOMIC_CMP_SWAP: {
11568     EVT T = N->getValueType(0);
11569     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11570     bool Regs64bit = T == MVT::i128;
11571     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11572     SDValue cpInL, cpInH;
11573     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11574                         DAG.getConstant(0, HalfT));
11575     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11576                         DAG.getConstant(1, HalfT));
11577     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11578                              Regs64bit ? X86::RAX : X86::EAX,
11579                              cpInL, SDValue());
11580     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11581                              Regs64bit ? X86::RDX : X86::EDX,
11582                              cpInH, cpInL.getValue(1));
11583     SDValue swapInL, swapInH;
11584     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11585                           DAG.getConstant(0, HalfT));
11586     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11587                           DAG.getConstant(1, HalfT));
11588     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11589                                Regs64bit ? X86::RBX : X86::EBX,
11590                                swapInL, cpInH.getValue(1));
11591     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11592                                Regs64bit ? X86::RCX : X86::ECX,
11593                                swapInH, swapInL.getValue(1));
11594     SDValue Ops[] = { swapInH.getValue(0),
11595                       N->getOperand(1),
11596                       swapInH.getValue(1) };
11597     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11598     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11599     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11600                                   X86ISD::LCMPXCHG8_DAG;
11601     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11602                                              Ops, 3, T, MMO);
11603     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11604                                         Regs64bit ? X86::RAX : X86::EAX,
11605                                         HalfT, Result.getValue(1));
11606     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11607                                         Regs64bit ? X86::RDX : X86::EDX,
11608                                         HalfT, cpOutL.getValue(2));
11609     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11610     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11611     Results.push_back(cpOutH.getValue(1));
11612     return;
11613   }
11614   case ISD::ATOMIC_LOAD_ADD:
11615   case ISD::ATOMIC_LOAD_AND:
11616   case ISD::ATOMIC_LOAD_NAND:
11617   case ISD::ATOMIC_LOAD_OR:
11618   case ISD::ATOMIC_LOAD_SUB:
11619   case ISD::ATOMIC_LOAD_XOR:
11620   case ISD::ATOMIC_LOAD_MAX:
11621   case ISD::ATOMIC_LOAD_MIN:
11622   case ISD::ATOMIC_LOAD_UMAX:
11623   case ISD::ATOMIC_LOAD_UMIN:
11624   case ISD::ATOMIC_SWAP: {
11625     unsigned Opc;
11626     switch (N->getOpcode()) {
11627     default: llvm_unreachable("Unexpected opcode");
11628     case ISD::ATOMIC_LOAD_ADD:
11629       Opc = X86ISD::ATOMADD64_DAG;
11630       break;
11631     case ISD::ATOMIC_LOAD_AND:
11632       Opc = X86ISD::ATOMAND64_DAG;
11633       break;
11634     case ISD::ATOMIC_LOAD_NAND:
11635       Opc = X86ISD::ATOMNAND64_DAG;
11636       break;
11637     case ISD::ATOMIC_LOAD_OR:
11638       Opc = X86ISD::ATOMOR64_DAG;
11639       break;
11640     case ISD::ATOMIC_LOAD_SUB:
11641       Opc = X86ISD::ATOMSUB64_DAG;
11642       break;
11643     case ISD::ATOMIC_LOAD_XOR:
11644       Opc = X86ISD::ATOMXOR64_DAG;
11645       break;
11646     case ISD::ATOMIC_LOAD_MAX:
11647       Opc = X86ISD::ATOMMAX64_DAG;
11648       break;
11649     case ISD::ATOMIC_LOAD_MIN:
11650       Opc = X86ISD::ATOMMIN64_DAG;
11651       break;
11652     case ISD::ATOMIC_LOAD_UMAX:
11653       Opc = X86ISD::ATOMUMAX64_DAG;
11654       break;
11655     case ISD::ATOMIC_LOAD_UMIN:
11656       Opc = X86ISD::ATOMUMIN64_DAG;
11657       break;
11658     case ISD::ATOMIC_SWAP:
11659       Opc = X86ISD::ATOMSWAP64_DAG;
11660       break;
11661     }
11662     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11663     return;
11664   }
11665   case ISD::ATOMIC_LOAD:
11666     ReplaceATOMIC_LOAD(N, Results, DAG);
11667   }
11668 }
11669
11670 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11671   switch (Opcode) {
11672   default: return NULL;
11673   case X86ISD::BSF:                return "X86ISD::BSF";
11674   case X86ISD::BSR:                return "X86ISD::BSR";
11675   case X86ISD::SHLD:               return "X86ISD::SHLD";
11676   case X86ISD::SHRD:               return "X86ISD::SHRD";
11677   case X86ISD::FAND:               return "X86ISD::FAND";
11678   case X86ISD::FOR:                return "X86ISD::FOR";
11679   case X86ISD::FXOR:               return "X86ISD::FXOR";
11680   case X86ISD::FSRL:               return "X86ISD::FSRL";
11681   case X86ISD::FILD:               return "X86ISD::FILD";
11682   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11683   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11684   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11685   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11686   case X86ISD::FLD:                return "X86ISD::FLD";
11687   case X86ISD::FST:                return "X86ISD::FST";
11688   case X86ISD::CALL:               return "X86ISD::CALL";
11689   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11690   case X86ISD::BT:                 return "X86ISD::BT";
11691   case X86ISD::CMP:                return "X86ISD::CMP";
11692   case X86ISD::COMI:               return "X86ISD::COMI";
11693   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11694   case X86ISD::SETCC:              return "X86ISD::SETCC";
11695   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11696   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11697   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11698   case X86ISD::CMOV:               return "X86ISD::CMOV";
11699   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11700   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11701   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11702   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11703   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11704   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11705   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11706   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11707   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11708   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11709   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11710   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11711   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11712   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11713   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11714   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11715   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11716   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11717   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11718   case X86ISD::HADD:               return "X86ISD::HADD";
11719   case X86ISD::HSUB:               return "X86ISD::HSUB";
11720   case X86ISD::FHADD:              return "X86ISD::FHADD";
11721   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11722   case X86ISD::FMAX:               return "X86ISD::FMAX";
11723   case X86ISD::FMIN:               return "X86ISD::FMIN";
11724   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11725   case X86ISD::FMINC:              return "X86ISD::FMINC";
11726   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11727   case X86ISD::FRCP:               return "X86ISD::FRCP";
11728   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11729   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11730   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11731   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11732   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11733   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11734   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11735   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11736   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11737   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11738   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11739   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11740   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11741   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11742   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11743   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11744   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11745   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11746   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11747   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11748   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11749   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11750   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11751   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11752   case X86ISD::VSHL:               return "X86ISD::VSHL";
11753   case X86ISD::VSRL:               return "X86ISD::VSRL";
11754   case X86ISD::VSRA:               return "X86ISD::VSRA";
11755   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11756   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11757   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11758   case X86ISD::CMPP:               return "X86ISD::CMPP";
11759   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11760   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11761   case X86ISD::ADD:                return "X86ISD::ADD";
11762   case X86ISD::SUB:                return "X86ISD::SUB";
11763   case X86ISD::ADC:                return "X86ISD::ADC";
11764   case X86ISD::SBB:                return "X86ISD::SBB";
11765   case X86ISD::SMUL:               return "X86ISD::SMUL";
11766   case X86ISD::UMUL:               return "X86ISD::UMUL";
11767   case X86ISD::INC:                return "X86ISD::INC";
11768   case X86ISD::DEC:                return "X86ISD::DEC";
11769   case X86ISD::OR:                 return "X86ISD::OR";
11770   case X86ISD::XOR:                return "X86ISD::XOR";
11771   case X86ISD::AND:                return "X86ISD::AND";
11772   case X86ISD::ANDN:               return "X86ISD::ANDN";
11773   case X86ISD::BLSI:               return "X86ISD::BLSI";
11774   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11775   case X86ISD::BLSR:               return "X86ISD::BLSR";
11776   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11777   case X86ISD::PTEST:              return "X86ISD::PTEST";
11778   case X86ISD::TESTP:              return "X86ISD::TESTP";
11779   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11780   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11781   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11782   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11783   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11784   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11785   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11786   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11787   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11788   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11789   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11790   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11791   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11792   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11793   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11794   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11795   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11796   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11797   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11798   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11799   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11800   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11801   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11802   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11803   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11804   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11805   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11806   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11807   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11808   case X86ISD::SAHF:               return "X86ISD::SAHF";
11809   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11810   case X86ISD::FMADD:              return "X86ISD::FMADD";
11811   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11812   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11813   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11814   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11815   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11816   }
11817 }
11818
11819 // isLegalAddressingMode - Return true if the addressing mode represented
11820 // by AM is legal for this target, for a load/store of the specified type.
11821 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11822                                               Type *Ty) const {
11823   // X86 supports extremely general addressing modes.
11824   CodeModel::Model M = getTargetMachine().getCodeModel();
11825   Reloc::Model R = getTargetMachine().getRelocationModel();
11826
11827   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11828   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11829     return false;
11830
11831   if (AM.BaseGV) {
11832     unsigned GVFlags =
11833       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11834
11835     // If a reference to this global requires an extra load, we can't fold it.
11836     if (isGlobalStubReference(GVFlags))
11837       return false;
11838
11839     // If BaseGV requires a register for the PIC base, we cannot also have a
11840     // BaseReg specified.
11841     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11842       return false;
11843
11844     // If lower 4G is not available, then we must use rip-relative addressing.
11845     if ((M != CodeModel::Small || R != Reloc::Static) &&
11846         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11847       return false;
11848   }
11849
11850   switch (AM.Scale) {
11851   case 0:
11852   case 1:
11853   case 2:
11854   case 4:
11855   case 8:
11856     // These scales always work.
11857     break;
11858   case 3:
11859   case 5:
11860   case 9:
11861     // These scales are formed with basereg+scalereg.  Only accept if there is
11862     // no basereg yet.
11863     if (AM.HasBaseReg)
11864       return false;
11865     break;
11866   default:  // Other stuff never works.
11867     return false;
11868   }
11869
11870   return true;
11871 }
11872
11873
11874 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11875   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11876     return false;
11877   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11878   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11879   if (NumBits1 <= NumBits2)
11880     return false;
11881   return true;
11882 }
11883
11884 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11885   return Imm == (int32_t)Imm;
11886 }
11887
11888 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11889   // Can also use sub to handle negated immediates.
11890   return Imm == (int32_t)Imm;
11891 }
11892
11893 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11894   if (!VT1.isInteger() || !VT2.isInteger())
11895     return false;
11896   unsigned NumBits1 = VT1.getSizeInBits();
11897   unsigned NumBits2 = VT2.getSizeInBits();
11898   if (NumBits1 <= NumBits2)
11899     return false;
11900   return true;
11901 }
11902
11903 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11904   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11905   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11906 }
11907
11908 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11909   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11910   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11911 }
11912
11913 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11914   // i16 instructions are longer (0x66 prefix) and potentially slower.
11915   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11916 }
11917
11918 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11919 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11920 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11921 /// are assumed to be legal.
11922 bool
11923 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11924                                       EVT VT) const {
11925   // Very little shuffling can be done for 64-bit vectors right now.
11926   if (VT.getSizeInBits() == 64)
11927     return false;
11928
11929   // FIXME: pshufb, blends, shifts.
11930   return (VT.getVectorNumElements() == 2 ||
11931           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11932           isMOVLMask(M, VT) ||
11933           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11934           isPSHUFDMask(M, VT) ||
11935           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11936           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11937           isPALIGNRMask(M, VT, Subtarget) ||
11938           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11939           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11940           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11941           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11942 }
11943
11944 bool
11945 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11946                                           EVT VT) const {
11947   unsigned NumElts = VT.getVectorNumElements();
11948   // FIXME: This collection of masks seems suspect.
11949   if (NumElts == 2)
11950     return true;
11951   if (NumElts == 4 && VT.is128BitVector()) {
11952     return (isMOVLMask(Mask, VT)  ||
11953             isCommutedMOVLMask(Mask, VT, true) ||
11954             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11955             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11956   }
11957   return false;
11958 }
11959
11960 //===----------------------------------------------------------------------===//
11961 //                           X86 Scheduler Hooks
11962 //===----------------------------------------------------------------------===//
11963
11964 // private utility function
11965
11966 // Get CMPXCHG opcode for the specified data type.
11967 static unsigned getCmpXChgOpcode(EVT VT) {
11968   switch (VT.getSimpleVT().SimpleTy) {
11969   case MVT::i8:  return X86::LCMPXCHG8;
11970   case MVT::i16: return X86::LCMPXCHG16;
11971   case MVT::i32: return X86::LCMPXCHG32;
11972   case MVT::i64: return X86::LCMPXCHG64;
11973   default:
11974     break;
11975   }
11976   llvm_unreachable("Invalid operand size!");
11977 }
11978
11979 // Get LOAD opcode for the specified data type.
11980 static unsigned getLoadOpcode(EVT VT) {
11981   switch (VT.getSimpleVT().SimpleTy) {
11982   case MVT::i8:  return X86::MOV8rm;
11983   case MVT::i16: return X86::MOV16rm;
11984   case MVT::i32: return X86::MOV32rm;
11985   case MVT::i64: return X86::MOV64rm;
11986   default:
11987     break;
11988   }
11989   llvm_unreachable("Invalid operand size!");
11990 }
11991
11992 // Get opcode of the non-atomic one from the specified atomic instruction.
11993 static unsigned getNonAtomicOpcode(unsigned Opc) {
11994   switch (Opc) {
11995   case X86::ATOMAND8:  return X86::AND8rr;
11996   case X86::ATOMAND16: return X86::AND16rr;
11997   case X86::ATOMAND32: return X86::AND32rr;
11998   case X86::ATOMAND64: return X86::AND64rr;
11999   case X86::ATOMOR8:   return X86::OR8rr;
12000   case X86::ATOMOR16:  return X86::OR16rr;
12001   case X86::ATOMOR32:  return X86::OR32rr;
12002   case X86::ATOMOR64:  return X86::OR64rr;
12003   case X86::ATOMXOR8:  return X86::XOR8rr;
12004   case X86::ATOMXOR16: return X86::XOR16rr;
12005   case X86::ATOMXOR32: return X86::XOR32rr;
12006   case X86::ATOMXOR64: return X86::XOR64rr;
12007   }
12008   llvm_unreachable("Unhandled atomic-load-op opcode!");
12009 }
12010
12011 // Get opcode of the non-atomic one from the specified atomic instruction with
12012 // extra opcode.
12013 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12014                                                unsigned &ExtraOpc) {
12015   switch (Opc) {
12016   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12017   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12018   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12019   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12020   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12021   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12022   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12023   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12024   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12025   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12026   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12027   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12028   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12029   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12030   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12031   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12032   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12033   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12034   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12035   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12036   }
12037   llvm_unreachable("Unhandled atomic-load-op opcode!");
12038 }
12039
12040 // Get opcode of the non-atomic one from the specified atomic instruction for
12041 // 64-bit data type on 32-bit target.
12042 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12043   switch (Opc) {
12044   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12045   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12046   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12047   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12048   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12049   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12050   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12051   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12052   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12053   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12054   }
12055   llvm_unreachable("Unhandled atomic-load-op opcode!");
12056 }
12057
12058 // Get opcode of the non-atomic one from the specified atomic instruction for
12059 // 64-bit data type on 32-bit target with extra opcode.
12060 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12061                                                    unsigned &HiOpc,
12062                                                    unsigned &ExtraOpc) {
12063   switch (Opc) {
12064   case X86::ATOMNAND6432:
12065     ExtraOpc = X86::NOT32r;
12066     HiOpc = X86::AND32rr;
12067     return X86::AND32rr;
12068   }
12069   llvm_unreachable("Unhandled atomic-load-op opcode!");
12070 }
12071
12072 // Get pseudo CMOV opcode from the specified data type.
12073 static unsigned getPseudoCMOVOpc(EVT VT) {
12074   switch (VT.getSimpleVT().SimpleTy) {
12075   case MVT::i8:  return X86::CMOV_GR8;
12076   case MVT::i16: return X86::CMOV_GR16;
12077   case MVT::i32: return X86::CMOV_GR32;
12078   default:
12079     break;
12080   }
12081   llvm_unreachable("Unknown CMOV opcode!");
12082 }
12083
12084 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12085 // They will be translated into a spin-loop or compare-exchange loop from
12086 //
12087 //    ...
12088 //    dst = atomic-fetch-op MI.addr, MI.val
12089 //    ...
12090 //
12091 // to
12092 //
12093 //    ...
12094 //    EAX = LOAD MI.addr
12095 // loop:
12096 //    t1 = OP MI.val, EAX
12097 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12098 //    JNE loop
12099 // sink:
12100 //    dst = EAX
12101 //    ...
12102 MachineBasicBlock *
12103 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12104                                        MachineBasicBlock *MBB) const {
12105   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12106   DebugLoc DL = MI->getDebugLoc();
12107
12108   MachineFunction *MF = MBB->getParent();
12109   MachineRegisterInfo &MRI = MF->getRegInfo();
12110
12111   const BasicBlock *BB = MBB->getBasicBlock();
12112   MachineFunction::iterator I = MBB;
12113   ++I;
12114
12115   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12116          "Unexpected number of operands");
12117
12118   assert(MI->hasOneMemOperand() &&
12119          "Expected atomic-load-op to have one memoperand");
12120
12121   // Memory Reference
12122   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12123   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12124
12125   unsigned DstReg, SrcReg;
12126   unsigned MemOpndSlot;
12127
12128   unsigned CurOp = 0;
12129
12130   DstReg = MI->getOperand(CurOp++).getReg();
12131   MemOpndSlot = CurOp;
12132   CurOp += X86::AddrNumOperands;
12133   SrcReg = MI->getOperand(CurOp++).getReg();
12134
12135   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12136   MVT::SimpleValueType VT = *RC->vt_begin();
12137   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12138
12139   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12140   unsigned LOADOpc = getLoadOpcode(VT);
12141
12142   // For the atomic load-arith operator, we generate
12143   //
12144   //  thisMBB:
12145   //    EAX = LOAD [MI.addr]
12146   //  mainMBB:
12147   //    t1 = OP MI.val, EAX
12148   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12149   //    JNE mainMBB
12150   //  sinkMBB:
12151
12152   MachineBasicBlock *thisMBB = MBB;
12153   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12154   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12155   MF->insert(I, mainMBB);
12156   MF->insert(I, sinkMBB);
12157
12158   MachineInstrBuilder MIB;
12159
12160   // Transfer the remainder of BB and its successor edges to sinkMBB.
12161   sinkMBB->splice(sinkMBB->begin(), MBB,
12162                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12163   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12164
12165   // thisMBB:
12166   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12167   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12168     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12169   MIB.setMemRefs(MMOBegin, MMOEnd);
12170
12171   thisMBB->addSuccessor(mainMBB);
12172
12173   // mainMBB:
12174   MachineBasicBlock *origMainMBB = mainMBB;
12175   mainMBB->addLiveIn(AccPhyReg);
12176
12177   // Copy AccPhyReg as it is used more than once.
12178   unsigned AccReg = MRI.createVirtualRegister(RC);
12179   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12180     .addReg(AccPhyReg);
12181
12182   unsigned t1 = MRI.createVirtualRegister(RC);
12183   unsigned Opc = MI->getOpcode();
12184   switch (Opc) {
12185   default:
12186     llvm_unreachable("Unhandled atomic-load-op opcode!");
12187   case X86::ATOMAND8:
12188   case X86::ATOMAND16:
12189   case X86::ATOMAND32:
12190   case X86::ATOMAND64:
12191   case X86::ATOMOR8:
12192   case X86::ATOMOR16:
12193   case X86::ATOMOR32:
12194   case X86::ATOMOR64:
12195   case X86::ATOMXOR8:
12196   case X86::ATOMXOR16:
12197   case X86::ATOMXOR32:
12198   case X86::ATOMXOR64: {
12199     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12200     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12201       .addReg(AccReg);
12202     break;
12203   }
12204   case X86::ATOMNAND8:
12205   case X86::ATOMNAND16:
12206   case X86::ATOMNAND32:
12207   case X86::ATOMNAND64: {
12208     unsigned t2 = MRI.createVirtualRegister(RC);
12209     unsigned NOTOpc;
12210     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12211     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12212       .addReg(AccReg);
12213     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12214     break;
12215   }
12216   case X86::ATOMMAX8:
12217   case X86::ATOMMAX16:
12218   case X86::ATOMMAX32:
12219   case X86::ATOMMAX64:
12220   case X86::ATOMMIN8:
12221   case X86::ATOMMIN16:
12222   case X86::ATOMMIN32:
12223   case X86::ATOMMIN64:
12224   case X86::ATOMUMAX8:
12225   case X86::ATOMUMAX16:
12226   case X86::ATOMUMAX32:
12227   case X86::ATOMUMAX64:
12228   case X86::ATOMUMIN8:
12229   case X86::ATOMUMIN16:
12230   case X86::ATOMUMIN32:
12231   case X86::ATOMUMIN64: {
12232     unsigned CMPOpc;
12233     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12234
12235     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12236       .addReg(SrcReg)
12237       .addReg(AccReg);
12238
12239     if (Subtarget->hasCMov()) {
12240       if (VT != MVT::i8) {
12241         // Native support
12242         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12243           .addReg(SrcReg)
12244           .addReg(AccReg);
12245       } else {
12246         // Promote i8 to i32 to use CMOV32
12247         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12248         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12249         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12250         unsigned t2 = MRI.createVirtualRegister(RC32);
12251
12252         unsigned Undef = MRI.createVirtualRegister(RC32);
12253         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12254
12255         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12256           .addReg(Undef)
12257           .addReg(SrcReg)
12258           .addImm(X86::sub_8bit);
12259         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12260           .addReg(Undef)
12261           .addReg(AccReg)
12262           .addImm(X86::sub_8bit);
12263
12264         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12265           .addReg(SrcReg32)
12266           .addReg(AccReg32);
12267
12268         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12269           .addReg(t2, 0, X86::sub_8bit);
12270       }
12271     } else {
12272       // Use pseudo select and lower them.
12273       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12274              "Invalid atomic-load-op transformation!");
12275       unsigned SelOpc = getPseudoCMOVOpc(VT);
12276       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12277       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12278       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12279               .addReg(SrcReg).addReg(AccReg)
12280               .addImm(CC);
12281       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12282     }
12283     break;
12284   }
12285   }
12286
12287   // Copy AccPhyReg back from virtual register.
12288   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12289     .addReg(AccReg);
12290
12291   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12292   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12293     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12294   MIB.addReg(t1);
12295   MIB.setMemRefs(MMOBegin, MMOEnd);
12296
12297   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12298
12299   mainMBB->addSuccessor(origMainMBB);
12300   mainMBB->addSuccessor(sinkMBB);
12301
12302   // sinkMBB:
12303   sinkMBB->addLiveIn(AccPhyReg);
12304
12305   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12306           TII->get(TargetOpcode::COPY), DstReg)
12307     .addReg(AccPhyReg);
12308
12309   MI->eraseFromParent();
12310   return sinkMBB;
12311 }
12312
12313 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12314 // instructions. They will be translated into a spin-loop or compare-exchange
12315 // loop from
12316 //
12317 //    ...
12318 //    dst = atomic-fetch-op MI.addr, MI.val
12319 //    ...
12320 //
12321 // to
12322 //
12323 //    ...
12324 //    EAX = LOAD [MI.addr + 0]
12325 //    EDX = LOAD [MI.addr + 4]
12326 // loop:
12327 //    EBX = OP MI.val.lo, EAX
12328 //    ECX = OP MI.val.hi, EDX
12329 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12330 //    JNE loop
12331 // sink:
12332 //    dst = EDX:EAX
12333 //    ...
12334 MachineBasicBlock *
12335 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12336                                            MachineBasicBlock *MBB) const {
12337   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12338   DebugLoc DL = MI->getDebugLoc();
12339
12340   MachineFunction *MF = MBB->getParent();
12341   MachineRegisterInfo &MRI = MF->getRegInfo();
12342
12343   const BasicBlock *BB = MBB->getBasicBlock();
12344   MachineFunction::iterator I = MBB;
12345   ++I;
12346
12347   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12348          "Unexpected number of operands");
12349
12350   assert(MI->hasOneMemOperand() &&
12351          "Expected atomic-load-op32 to have one memoperand");
12352
12353   // Memory Reference
12354   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12355   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12356
12357   unsigned DstLoReg, DstHiReg;
12358   unsigned SrcLoReg, SrcHiReg;
12359   unsigned MemOpndSlot;
12360
12361   unsigned CurOp = 0;
12362
12363   DstLoReg = MI->getOperand(CurOp++).getReg();
12364   DstHiReg = MI->getOperand(CurOp++).getReg();
12365   MemOpndSlot = CurOp;
12366   CurOp += X86::AddrNumOperands;
12367   SrcLoReg = MI->getOperand(CurOp++).getReg();
12368   SrcHiReg = MI->getOperand(CurOp++).getReg();
12369
12370   const TargetRegisterClass *RC = &X86::GR32RegClass;
12371   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12372
12373   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12374   unsigned LOADOpc = X86::MOV32rm;
12375
12376   // For the atomic load-arith operator, we generate
12377   //
12378   //  thisMBB:
12379   //    EAX = LOAD [MI.addr + 0]
12380   //    EDX = LOAD [MI.addr + 4]
12381   //  mainMBB:
12382   //    EBX = OP MI.vallo, EAX
12383   //    ECX = OP MI.valhi, EDX
12384   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12385   //    JNE mainMBB
12386   //  sinkMBB:
12387
12388   MachineBasicBlock *thisMBB = MBB;
12389   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12390   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12391   MF->insert(I, mainMBB);
12392   MF->insert(I, sinkMBB);
12393
12394   MachineInstrBuilder MIB;
12395
12396   // Transfer the remainder of BB and its successor edges to sinkMBB.
12397   sinkMBB->splice(sinkMBB->begin(), MBB,
12398                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12399   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12400
12401   // thisMBB:
12402   // Lo
12403   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12404   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12405     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12406   MIB.setMemRefs(MMOBegin, MMOEnd);
12407   // Hi
12408   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12409   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12410     if (i == X86::AddrDisp)
12411       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12412     else
12413       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12414   }
12415   MIB.setMemRefs(MMOBegin, MMOEnd);
12416
12417   thisMBB->addSuccessor(mainMBB);
12418
12419   // mainMBB:
12420   MachineBasicBlock *origMainMBB = mainMBB;
12421   mainMBB->addLiveIn(X86::EAX);
12422   mainMBB->addLiveIn(X86::EDX);
12423
12424   // Copy EDX:EAX as they are used more than once.
12425   unsigned LoReg = MRI.createVirtualRegister(RC);
12426   unsigned HiReg = MRI.createVirtualRegister(RC);
12427   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12428   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12429
12430   unsigned t1L = MRI.createVirtualRegister(RC);
12431   unsigned t1H = MRI.createVirtualRegister(RC);
12432
12433   unsigned Opc = MI->getOpcode();
12434   switch (Opc) {
12435   default:
12436     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12437   case X86::ATOMAND6432:
12438   case X86::ATOMOR6432:
12439   case X86::ATOMXOR6432:
12440   case X86::ATOMADD6432:
12441   case X86::ATOMSUB6432: {
12442     unsigned HiOpc;
12443     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12444     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12445     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12446     break;
12447   }
12448   case X86::ATOMNAND6432: {
12449     unsigned HiOpc, NOTOpc;
12450     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12451     unsigned t2L = MRI.createVirtualRegister(RC);
12452     unsigned t2H = MRI.createVirtualRegister(RC);
12453     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12454     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12455     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12456     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12457     break;
12458   }
12459   case X86::ATOMMAX6432:
12460   case X86::ATOMMIN6432:
12461   case X86::ATOMUMAX6432:
12462   case X86::ATOMUMIN6432: {
12463     unsigned HiOpc;
12464     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12465     unsigned cL = MRI.createVirtualRegister(RC8);
12466     unsigned cH = MRI.createVirtualRegister(RC8);
12467     unsigned cL32 = MRI.createVirtualRegister(RC);
12468     unsigned cH32 = MRI.createVirtualRegister(RC);
12469     unsigned cc = MRI.createVirtualRegister(RC);
12470     // cl := cmp src_lo, lo
12471     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12472       .addReg(SrcLoReg).addReg(LoReg);
12473     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12474     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12475     // ch := cmp src_hi, hi
12476     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12477       .addReg(SrcHiReg).addReg(HiReg);
12478     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12479     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12480     // cc := if (src_hi == hi) ? cl : ch;
12481     if (Subtarget->hasCMov()) {
12482       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12483         .addReg(cH32).addReg(cL32);
12484     } else {
12485       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12486               .addReg(cH32).addReg(cL32)
12487               .addImm(X86::COND_E);
12488       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12489     }
12490     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12491     if (Subtarget->hasCMov()) {
12492       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12493         .addReg(SrcLoReg).addReg(LoReg);
12494       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12495         .addReg(SrcHiReg).addReg(HiReg);
12496     } else {
12497       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12498               .addReg(SrcLoReg).addReg(LoReg)
12499               .addImm(X86::COND_NE);
12500       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12501       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12502               .addReg(SrcHiReg).addReg(HiReg)
12503               .addImm(X86::COND_NE);
12504       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12505     }
12506     break;
12507   }
12508   case X86::ATOMSWAP6432: {
12509     unsigned HiOpc;
12510     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12511     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12512     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12513     break;
12514   }
12515   }
12516
12517   // Copy EDX:EAX back from HiReg:LoReg
12518   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12519   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12520   // Copy ECX:EBX from t1H:t1L
12521   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12522   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12523
12524   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12525   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12526     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12527   MIB.setMemRefs(MMOBegin, MMOEnd);
12528
12529   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12530
12531   mainMBB->addSuccessor(origMainMBB);
12532   mainMBB->addSuccessor(sinkMBB);
12533
12534   // sinkMBB:
12535   sinkMBB->addLiveIn(X86::EAX);
12536   sinkMBB->addLiveIn(X86::EDX);
12537
12538   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12539           TII->get(TargetOpcode::COPY), DstLoReg)
12540     .addReg(X86::EAX);
12541   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12542           TII->get(TargetOpcode::COPY), DstHiReg)
12543     .addReg(X86::EDX);
12544
12545   MI->eraseFromParent();
12546   return sinkMBB;
12547 }
12548
12549 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12550 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12551 // in the .td file.
12552 MachineBasicBlock *
12553 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12554                             unsigned numArgs, bool memArg) const {
12555   assert(Subtarget->hasSSE42() &&
12556          "Target must have SSE4.2 or AVX features enabled");
12557
12558   DebugLoc dl = MI->getDebugLoc();
12559   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12560   unsigned Opc;
12561   if (!Subtarget->hasAVX()) {
12562     if (memArg)
12563       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12564     else
12565       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12566   } else {
12567     if (memArg)
12568       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12569     else
12570       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12571   }
12572
12573   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12574   for (unsigned i = 0; i < numArgs; ++i) {
12575     MachineOperand &Op = MI->getOperand(i+1);
12576     if (!(Op.isReg() && Op.isImplicit()))
12577       MIB.addOperand(Op);
12578   }
12579   BuildMI(*BB, MI, dl,
12580     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12581     .addReg(X86::XMM0);
12582
12583   MI->eraseFromParent();
12584   return BB;
12585 }
12586
12587 MachineBasicBlock *
12588 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12589   DebugLoc dl = MI->getDebugLoc();
12590   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12591
12592   // Address into RAX/EAX, other two args into ECX, EDX.
12593   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12594   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12595   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12596   for (int i = 0; i < X86::AddrNumOperands; ++i)
12597     MIB.addOperand(MI->getOperand(i));
12598
12599   unsigned ValOps = X86::AddrNumOperands;
12600   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12601     .addReg(MI->getOperand(ValOps).getReg());
12602   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12603     .addReg(MI->getOperand(ValOps+1).getReg());
12604
12605   // The instruction doesn't actually take any operands though.
12606   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12607
12608   MI->eraseFromParent(); // The pseudo is gone now.
12609   return BB;
12610 }
12611
12612 MachineBasicBlock *
12613 X86TargetLowering::EmitVAARG64WithCustomInserter(
12614                    MachineInstr *MI,
12615                    MachineBasicBlock *MBB) const {
12616   // Emit va_arg instruction on X86-64.
12617
12618   // Operands to this pseudo-instruction:
12619   // 0  ) Output        : destination address (reg)
12620   // 1-5) Input         : va_list address (addr, i64mem)
12621   // 6  ) ArgSize       : Size (in bytes) of vararg type
12622   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12623   // 8  ) Align         : Alignment of type
12624   // 9  ) EFLAGS (implicit-def)
12625
12626   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12627   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12628
12629   unsigned DestReg = MI->getOperand(0).getReg();
12630   MachineOperand &Base = MI->getOperand(1);
12631   MachineOperand &Scale = MI->getOperand(2);
12632   MachineOperand &Index = MI->getOperand(3);
12633   MachineOperand &Disp = MI->getOperand(4);
12634   MachineOperand &Segment = MI->getOperand(5);
12635   unsigned ArgSize = MI->getOperand(6).getImm();
12636   unsigned ArgMode = MI->getOperand(7).getImm();
12637   unsigned Align = MI->getOperand(8).getImm();
12638
12639   // Memory Reference
12640   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12641   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12642   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12643
12644   // Machine Information
12645   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12646   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12647   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12648   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12649   DebugLoc DL = MI->getDebugLoc();
12650
12651   // struct va_list {
12652   //   i32   gp_offset
12653   //   i32   fp_offset
12654   //   i64   overflow_area (address)
12655   //   i64   reg_save_area (address)
12656   // }
12657   // sizeof(va_list) = 24
12658   // alignment(va_list) = 8
12659
12660   unsigned TotalNumIntRegs = 6;
12661   unsigned TotalNumXMMRegs = 8;
12662   bool UseGPOffset = (ArgMode == 1);
12663   bool UseFPOffset = (ArgMode == 2);
12664   unsigned MaxOffset = TotalNumIntRegs * 8 +
12665                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12666
12667   /* Align ArgSize to a multiple of 8 */
12668   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12669   bool NeedsAlign = (Align > 8);
12670
12671   MachineBasicBlock *thisMBB = MBB;
12672   MachineBasicBlock *overflowMBB;
12673   MachineBasicBlock *offsetMBB;
12674   MachineBasicBlock *endMBB;
12675
12676   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12677   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12678   unsigned OffsetReg = 0;
12679
12680   if (!UseGPOffset && !UseFPOffset) {
12681     // If we only pull from the overflow region, we don't create a branch.
12682     // We don't need to alter control flow.
12683     OffsetDestReg = 0; // unused
12684     OverflowDestReg = DestReg;
12685
12686     offsetMBB = NULL;
12687     overflowMBB = thisMBB;
12688     endMBB = thisMBB;
12689   } else {
12690     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12691     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12692     // If not, pull from overflow_area. (branch to overflowMBB)
12693     //
12694     //       thisMBB
12695     //         |     .
12696     //         |        .
12697     //     offsetMBB   overflowMBB
12698     //         |        .
12699     //         |     .
12700     //        endMBB
12701
12702     // Registers for the PHI in endMBB
12703     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12704     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12705
12706     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12707     MachineFunction *MF = MBB->getParent();
12708     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12709     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12710     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12711
12712     MachineFunction::iterator MBBIter = MBB;
12713     ++MBBIter;
12714
12715     // Insert the new basic blocks
12716     MF->insert(MBBIter, offsetMBB);
12717     MF->insert(MBBIter, overflowMBB);
12718     MF->insert(MBBIter, endMBB);
12719
12720     // Transfer the remainder of MBB and its successor edges to endMBB.
12721     endMBB->splice(endMBB->begin(), thisMBB,
12722                     llvm::next(MachineBasicBlock::iterator(MI)),
12723                     thisMBB->end());
12724     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12725
12726     // Make offsetMBB and overflowMBB successors of thisMBB
12727     thisMBB->addSuccessor(offsetMBB);
12728     thisMBB->addSuccessor(overflowMBB);
12729
12730     // endMBB is a successor of both offsetMBB and overflowMBB
12731     offsetMBB->addSuccessor(endMBB);
12732     overflowMBB->addSuccessor(endMBB);
12733
12734     // Load the offset value into a register
12735     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12736     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12737       .addOperand(Base)
12738       .addOperand(Scale)
12739       .addOperand(Index)
12740       .addDisp(Disp, UseFPOffset ? 4 : 0)
12741       .addOperand(Segment)
12742       .setMemRefs(MMOBegin, MMOEnd);
12743
12744     // Check if there is enough room left to pull this argument.
12745     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12746       .addReg(OffsetReg)
12747       .addImm(MaxOffset + 8 - ArgSizeA8);
12748
12749     // Branch to "overflowMBB" if offset >= max
12750     // Fall through to "offsetMBB" otherwise
12751     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12752       .addMBB(overflowMBB);
12753   }
12754
12755   // In offsetMBB, emit code to use the reg_save_area.
12756   if (offsetMBB) {
12757     assert(OffsetReg != 0);
12758
12759     // Read the reg_save_area address.
12760     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12761     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12762       .addOperand(Base)
12763       .addOperand(Scale)
12764       .addOperand(Index)
12765       .addDisp(Disp, 16)
12766       .addOperand(Segment)
12767       .setMemRefs(MMOBegin, MMOEnd);
12768
12769     // Zero-extend the offset
12770     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12771       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12772         .addImm(0)
12773         .addReg(OffsetReg)
12774         .addImm(X86::sub_32bit);
12775
12776     // Add the offset to the reg_save_area to get the final address.
12777     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12778       .addReg(OffsetReg64)
12779       .addReg(RegSaveReg);
12780
12781     // Compute the offset for the next argument
12782     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12783     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12784       .addReg(OffsetReg)
12785       .addImm(UseFPOffset ? 16 : 8);
12786
12787     // Store it back into the va_list.
12788     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12789       .addOperand(Base)
12790       .addOperand(Scale)
12791       .addOperand(Index)
12792       .addDisp(Disp, UseFPOffset ? 4 : 0)
12793       .addOperand(Segment)
12794       .addReg(NextOffsetReg)
12795       .setMemRefs(MMOBegin, MMOEnd);
12796
12797     // Jump to endMBB
12798     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12799       .addMBB(endMBB);
12800   }
12801
12802   //
12803   // Emit code to use overflow area
12804   //
12805
12806   // Load the overflow_area address into a register.
12807   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12808   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12809     .addOperand(Base)
12810     .addOperand(Scale)
12811     .addOperand(Index)
12812     .addDisp(Disp, 8)
12813     .addOperand(Segment)
12814     .setMemRefs(MMOBegin, MMOEnd);
12815
12816   // If we need to align it, do so. Otherwise, just copy the address
12817   // to OverflowDestReg.
12818   if (NeedsAlign) {
12819     // Align the overflow address
12820     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12821     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12822
12823     // aligned_addr = (addr + (align-1)) & ~(align-1)
12824     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12825       .addReg(OverflowAddrReg)
12826       .addImm(Align-1);
12827
12828     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12829       .addReg(TmpReg)
12830       .addImm(~(uint64_t)(Align-1));
12831   } else {
12832     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12833       .addReg(OverflowAddrReg);
12834   }
12835
12836   // Compute the next overflow address after this argument.
12837   // (the overflow address should be kept 8-byte aligned)
12838   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12839   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12840     .addReg(OverflowDestReg)
12841     .addImm(ArgSizeA8);
12842
12843   // Store the new overflow address.
12844   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12845     .addOperand(Base)
12846     .addOperand(Scale)
12847     .addOperand(Index)
12848     .addDisp(Disp, 8)
12849     .addOperand(Segment)
12850     .addReg(NextAddrReg)
12851     .setMemRefs(MMOBegin, MMOEnd);
12852
12853   // If we branched, emit the PHI to the front of endMBB.
12854   if (offsetMBB) {
12855     BuildMI(*endMBB, endMBB->begin(), DL,
12856             TII->get(X86::PHI), DestReg)
12857       .addReg(OffsetDestReg).addMBB(offsetMBB)
12858       .addReg(OverflowDestReg).addMBB(overflowMBB);
12859   }
12860
12861   // Erase the pseudo instruction
12862   MI->eraseFromParent();
12863
12864   return endMBB;
12865 }
12866
12867 MachineBasicBlock *
12868 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12869                                                  MachineInstr *MI,
12870                                                  MachineBasicBlock *MBB) const {
12871   // Emit code to save XMM registers to the stack. The ABI says that the
12872   // number of registers to save is given in %al, so it's theoretically
12873   // possible to do an indirect jump trick to avoid saving all of them,
12874   // however this code takes a simpler approach and just executes all
12875   // of the stores if %al is non-zero. It's less code, and it's probably
12876   // easier on the hardware branch predictor, and stores aren't all that
12877   // expensive anyway.
12878
12879   // Create the new basic blocks. One block contains all the XMM stores,
12880   // and one block is the final destination regardless of whether any
12881   // stores were performed.
12882   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12883   MachineFunction *F = MBB->getParent();
12884   MachineFunction::iterator MBBIter = MBB;
12885   ++MBBIter;
12886   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12887   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12888   F->insert(MBBIter, XMMSaveMBB);
12889   F->insert(MBBIter, EndMBB);
12890
12891   // Transfer the remainder of MBB and its successor edges to EndMBB.
12892   EndMBB->splice(EndMBB->begin(), MBB,
12893                  llvm::next(MachineBasicBlock::iterator(MI)),
12894                  MBB->end());
12895   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12896
12897   // The original block will now fall through to the XMM save block.
12898   MBB->addSuccessor(XMMSaveMBB);
12899   // The XMMSaveMBB will fall through to the end block.
12900   XMMSaveMBB->addSuccessor(EndMBB);
12901
12902   // Now add the instructions.
12903   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12904   DebugLoc DL = MI->getDebugLoc();
12905
12906   unsigned CountReg = MI->getOperand(0).getReg();
12907   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12908   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12909
12910   if (!Subtarget->isTargetWin64()) {
12911     // If %al is 0, branch around the XMM save block.
12912     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12913     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12914     MBB->addSuccessor(EndMBB);
12915   }
12916
12917   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12918   // In the XMM save block, save all the XMM argument registers.
12919   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12920     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12921     MachineMemOperand *MMO =
12922       F->getMachineMemOperand(
12923           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12924         MachineMemOperand::MOStore,
12925         /*Size=*/16, /*Align=*/16);
12926     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12927       .addFrameIndex(RegSaveFrameIndex)
12928       .addImm(/*Scale=*/1)
12929       .addReg(/*IndexReg=*/0)
12930       .addImm(/*Disp=*/Offset)
12931       .addReg(/*Segment=*/0)
12932       .addReg(MI->getOperand(i).getReg())
12933       .addMemOperand(MMO);
12934   }
12935
12936   MI->eraseFromParent();   // The pseudo instruction is gone now.
12937
12938   return EndMBB;
12939 }
12940
12941 // The EFLAGS operand of SelectItr might be missing a kill marker
12942 // because there were multiple uses of EFLAGS, and ISel didn't know
12943 // which to mark. Figure out whether SelectItr should have had a
12944 // kill marker, and set it if it should. Returns the correct kill
12945 // marker value.
12946 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12947                                      MachineBasicBlock* BB,
12948                                      const TargetRegisterInfo* TRI) {
12949   // Scan forward through BB for a use/def of EFLAGS.
12950   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12951   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12952     const MachineInstr& mi = *miI;
12953     if (mi.readsRegister(X86::EFLAGS))
12954       return false;
12955     if (mi.definesRegister(X86::EFLAGS))
12956       break; // Should have kill-flag - update below.
12957   }
12958
12959   // If we hit the end of the block, check whether EFLAGS is live into a
12960   // successor.
12961   if (miI == BB->end()) {
12962     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12963                                           sEnd = BB->succ_end();
12964          sItr != sEnd; ++sItr) {
12965       MachineBasicBlock* succ = *sItr;
12966       if (succ->isLiveIn(X86::EFLAGS))
12967         return false;
12968     }
12969   }
12970
12971   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12972   // out. SelectMI should have a kill flag on EFLAGS.
12973   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12974   return true;
12975 }
12976
12977 MachineBasicBlock *
12978 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12979                                      MachineBasicBlock *BB) const {
12980   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12981   DebugLoc DL = MI->getDebugLoc();
12982
12983   // To "insert" a SELECT_CC instruction, we actually have to insert the
12984   // diamond control-flow pattern.  The incoming instruction knows the
12985   // destination vreg to set, the condition code register to branch on, the
12986   // true/false values to select between, and a branch opcode to use.
12987   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12988   MachineFunction::iterator It = BB;
12989   ++It;
12990
12991   //  thisMBB:
12992   //  ...
12993   //   TrueVal = ...
12994   //   cmpTY ccX, r1, r2
12995   //   bCC copy1MBB
12996   //   fallthrough --> copy0MBB
12997   MachineBasicBlock *thisMBB = BB;
12998   MachineFunction *F = BB->getParent();
12999   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13000   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13001   F->insert(It, copy0MBB);
13002   F->insert(It, sinkMBB);
13003
13004   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13005   // live into the sink and copy blocks.
13006   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13007   if (!MI->killsRegister(X86::EFLAGS) &&
13008       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13009     copy0MBB->addLiveIn(X86::EFLAGS);
13010     sinkMBB->addLiveIn(X86::EFLAGS);
13011   }
13012
13013   // Transfer the remainder of BB and its successor edges to sinkMBB.
13014   sinkMBB->splice(sinkMBB->begin(), BB,
13015                   llvm::next(MachineBasicBlock::iterator(MI)),
13016                   BB->end());
13017   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13018
13019   // Add the true and fallthrough blocks as its successors.
13020   BB->addSuccessor(copy0MBB);
13021   BB->addSuccessor(sinkMBB);
13022
13023   // Create the conditional branch instruction.
13024   unsigned Opc =
13025     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13026   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13027
13028   //  copy0MBB:
13029   //   %FalseValue = ...
13030   //   # fallthrough to sinkMBB
13031   copy0MBB->addSuccessor(sinkMBB);
13032
13033   //  sinkMBB:
13034   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13035   //  ...
13036   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13037           TII->get(X86::PHI), MI->getOperand(0).getReg())
13038     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13039     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13040
13041   MI->eraseFromParent();   // The pseudo instruction is gone now.
13042   return sinkMBB;
13043 }
13044
13045 MachineBasicBlock *
13046 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13047                                         bool Is64Bit) const {
13048   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13049   DebugLoc DL = MI->getDebugLoc();
13050   MachineFunction *MF = BB->getParent();
13051   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13052
13053   assert(getTargetMachine().Options.EnableSegmentedStacks);
13054
13055   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13056   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13057
13058   // BB:
13059   //  ... [Till the alloca]
13060   // If stacklet is not large enough, jump to mallocMBB
13061   //
13062   // bumpMBB:
13063   //  Allocate by subtracting from RSP
13064   //  Jump to continueMBB
13065   //
13066   // mallocMBB:
13067   //  Allocate by call to runtime
13068   //
13069   // continueMBB:
13070   //  ...
13071   //  [rest of original BB]
13072   //
13073
13074   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13075   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13076   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13077
13078   MachineRegisterInfo &MRI = MF->getRegInfo();
13079   const TargetRegisterClass *AddrRegClass =
13080     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13081
13082   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13083     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13084     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13085     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13086     sizeVReg = MI->getOperand(1).getReg(),
13087     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13088
13089   MachineFunction::iterator MBBIter = BB;
13090   ++MBBIter;
13091
13092   MF->insert(MBBIter, bumpMBB);
13093   MF->insert(MBBIter, mallocMBB);
13094   MF->insert(MBBIter, continueMBB);
13095
13096   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13097                       (MachineBasicBlock::iterator(MI)), BB->end());
13098   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13099
13100   // Add code to the main basic block to check if the stack limit has been hit,
13101   // and if so, jump to mallocMBB otherwise to bumpMBB.
13102   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13103   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13104     .addReg(tmpSPVReg).addReg(sizeVReg);
13105   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13106     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13107     .addReg(SPLimitVReg);
13108   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13109
13110   // bumpMBB simply decreases the stack pointer, since we know the current
13111   // stacklet has enough space.
13112   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13113     .addReg(SPLimitVReg);
13114   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13115     .addReg(SPLimitVReg);
13116   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13117
13118   // Calls into a routine in libgcc to allocate more space from the heap.
13119   const uint32_t *RegMask =
13120     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13121   if (Is64Bit) {
13122     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13123       .addReg(sizeVReg);
13124     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13125       .addExternalSymbol("__morestack_allocate_stack_space")
13126       .addRegMask(RegMask)
13127       .addReg(X86::RDI, RegState::Implicit)
13128       .addReg(X86::RAX, RegState::ImplicitDefine);
13129   } else {
13130     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13131       .addImm(12);
13132     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13133     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13134       .addExternalSymbol("__morestack_allocate_stack_space")
13135       .addRegMask(RegMask)
13136       .addReg(X86::EAX, RegState::ImplicitDefine);
13137   }
13138
13139   if (!Is64Bit)
13140     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13141       .addImm(16);
13142
13143   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13144     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13145   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13146
13147   // Set up the CFG correctly.
13148   BB->addSuccessor(bumpMBB);
13149   BB->addSuccessor(mallocMBB);
13150   mallocMBB->addSuccessor(continueMBB);
13151   bumpMBB->addSuccessor(continueMBB);
13152
13153   // Take care of the PHI nodes.
13154   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13155           MI->getOperand(0).getReg())
13156     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13157     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13158
13159   // Delete the original pseudo instruction.
13160   MI->eraseFromParent();
13161
13162   // And we're done.
13163   return continueMBB;
13164 }
13165
13166 MachineBasicBlock *
13167 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13168                                           MachineBasicBlock *BB) const {
13169   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13170   DebugLoc DL = MI->getDebugLoc();
13171
13172   assert(!Subtarget->isTargetEnvMacho());
13173
13174   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13175   // non-trivial part is impdef of ESP.
13176
13177   if (Subtarget->isTargetWin64()) {
13178     if (Subtarget->isTargetCygMing()) {
13179       // ___chkstk(Mingw64):
13180       // Clobbers R10, R11, RAX and EFLAGS.
13181       // Updates RSP.
13182       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13183         .addExternalSymbol("___chkstk")
13184         .addReg(X86::RAX, RegState::Implicit)
13185         .addReg(X86::RSP, RegState::Implicit)
13186         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13187         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13188         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13189     } else {
13190       // __chkstk(MSVCRT): does not update stack pointer.
13191       // Clobbers R10, R11 and EFLAGS.
13192       // FIXME: RAX(allocated size) might be reused and not killed.
13193       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13194         .addExternalSymbol("__chkstk")
13195         .addReg(X86::RAX, RegState::Implicit)
13196         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13197       // RAX has the offset to subtracted from RSP.
13198       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13199         .addReg(X86::RSP)
13200         .addReg(X86::RAX);
13201     }
13202   } else {
13203     const char *StackProbeSymbol =
13204       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13205
13206     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13207       .addExternalSymbol(StackProbeSymbol)
13208       .addReg(X86::EAX, RegState::Implicit)
13209       .addReg(X86::ESP, RegState::Implicit)
13210       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13211       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13212       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13213   }
13214
13215   MI->eraseFromParent();   // The pseudo instruction is gone now.
13216   return BB;
13217 }
13218
13219 MachineBasicBlock *
13220 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13221                                       MachineBasicBlock *BB) const {
13222   // This is pretty easy.  We're taking the value that we received from
13223   // our load from the relocation, sticking it in either RDI (x86-64)
13224   // or EAX and doing an indirect call.  The return value will then
13225   // be in the normal return register.
13226   const X86InstrInfo *TII
13227     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13228   DebugLoc DL = MI->getDebugLoc();
13229   MachineFunction *F = BB->getParent();
13230
13231   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13232   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13233
13234   // Get a register mask for the lowered call.
13235   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13236   // proper register mask.
13237   const uint32_t *RegMask =
13238     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13239   if (Subtarget->is64Bit()) {
13240     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13241                                       TII->get(X86::MOV64rm), X86::RDI)
13242     .addReg(X86::RIP)
13243     .addImm(0).addReg(0)
13244     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13245                       MI->getOperand(3).getTargetFlags())
13246     .addReg(0);
13247     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13248     addDirectMem(MIB, X86::RDI);
13249     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13250   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13251     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13252                                       TII->get(X86::MOV32rm), X86::EAX)
13253     .addReg(0)
13254     .addImm(0).addReg(0)
13255     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13256                       MI->getOperand(3).getTargetFlags())
13257     .addReg(0);
13258     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13259     addDirectMem(MIB, X86::EAX);
13260     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13261   } else {
13262     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13263                                       TII->get(X86::MOV32rm), X86::EAX)
13264     .addReg(TII->getGlobalBaseReg(F))
13265     .addImm(0).addReg(0)
13266     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13267                       MI->getOperand(3).getTargetFlags())
13268     .addReg(0);
13269     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13270     addDirectMem(MIB, X86::EAX);
13271     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13272   }
13273
13274   MI->eraseFromParent(); // The pseudo instruction is gone now.
13275   return BB;
13276 }
13277
13278 MachineBasicBlock *
13279 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13280                                     MachineBasicBlock *MBB) const {
13281   DebugLoc DL = MI->getDebugLoc();
13282   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13283
13284   MachineFunction *MF = MBB->getParent();
13285   MachineRegisterInfo &MRI = MF->getRegInfo();
13286
13287   const BasicBlock *BB = MBB->getBasicBlock();
13288   MachineFunction::iterator I = MBB;
13289   ++I;
13290
13291   // Memory Reference
13292   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13293   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13294
13295   unsigned DstReg;
13296   unsigned MemOpndSlot = 0;
13297
13298   unsigned CurOp = 0;
13299
13300   DstReg = MI->getOperand(CurOp++).getReg();
13301   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13302   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13303   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13304   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13305
13306   MemOpndSlot = CurOp;
13307
13308   MVT PVT = getPointerTy();
13309   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13310          "Invalid Pointer Size!");
13311
13312   // For v = setjmp(buf), we generate
13313   //
13314   // thisMBB:
13315   //  buf[LabelOffset] = restoreMBB
13316   //  SjLjSetup restoreMBB
13317   //
13318   // mainMBB:
13319   //  v_main = 0
13320   //
13321   // sinkMBB:
13322   //  v = phi(main, restore)
13323   //
13324   // restoreMBB:
13325   //  v_restore = 1
13326
13327   MachineBasicBlock *thisMBB = MBB;
13328   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13329   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13330   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13331   MF->insert(I, mainMBB);
13332   MF->insert(I, sinkMBB);
13333   MF->push_back(restoreMBB);
13334
13335   MachineInstrBuilder MIB;
13336
13337   // Transfer the remainder of BB and its successor edges to sinkMBB.
13338   sinkMBB->splice(sinkMBB->begin(), MBB,
13339                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13340   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13341
13342   // thisMBB:
13343   unsigned PtrStoreOpc = 0;
13344   unsigned LabelReg = 0;
13345   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13346   Reloc::Model RM = getTargetMachine().getRelocationModel();
13347   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13348                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13349
13350   // Prepare IP either in reg or imm.
13351   if (!UseImmLabel) {
13352     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13353     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13354     LabelReg = MRI.createVirtualRegister(PtrRC);
13355     if (Subtarget->is64Bit()) {
13356       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13357               .addReg(X86::RIP)
13358               .addImm(0)
13359               .addReg(0)
13360               .addMBB(restoreMBB)
13361               .addReg(0);
13362     } else {
13363       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13364       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13365               .addReg(XII->getGlobalBaseReg(MF))
13366               .addImm(0)
13367               .addReg(0)
13368               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13369               .addReg(0);
13370     }
13371   } else
13372     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13373   // Store IP
13374   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13375   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13376     if (i == X86::AddrDisp)
13377       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13378     else
13379       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13380   }
13381   if (!UseImmLabel)
13382     MIB.addReg(LabelReg);
13383   else
13384     MIB.addMBB(restoreMBB);
13385   MIB.setMemRefs(MMOBegin, MMOEnd);
13386   // Setup
13387   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13388           .addMBB(restoreMBB);
13389   MIB.addRegMask(RegInfo->getNoPreservedMask());
13390   thisMBB->addSuccessor(mainMBB);
13391   thisMBB->addSuccessor(restoreMBB);
13392
13393   // mainMBB:
13394   //  EAX = 0
13395   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13396   mainMBB->addSuccessor(sinkMBB);
13397
13398   // sinkMBB:
13399   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13400           TII->get(X86::PHI), DstReg)
13401     .addReg(mainDstReg).addMBB(mainMBB)
13402     .addReg(restoreDstReg).addMBB(restoreMBB);
13403
13404   // restoreMBB:
13405   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13406   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13407   restoreMBB->addSuccessor(sinkMBB);
13408
13409   MI->eraseFromParent();
13410   return sinkMBB;
13411 }
13412
13413 MachineBasicBlock *
13414 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13415                                      MachineBasicBlock *MBB) const {
13416   DebugLoc DL = MI->getDebugLoc();
13417   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13418
13419   MachineFunction *MF = MBB->getParent();
13420   MachineRegisterInfo &MRI = MF->getRegInfo();
13421
13422   // Memory Reference
13423   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13424   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13425
13426   MVT PVT = getPointerTy();
13427   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13428          "Invalid Pointer Size!");
13429
13430   const TargetRegisterClass *RC =
13431     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13432   unsigned Tmp = MRI.createVirtualRegister(RC);
13433   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13434   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13435   unsigned SP = RegInfo->getStackRegister();
13436
13437   MachineInstrBuilder MIB;
13438
13439   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13440   const int64_t SPOffset = 2 * PVT.getStoreSize();
13441
13442   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13443   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13444
13445   // Reload FP
13446   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13447   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13448     MIB.addOperand(MI->getOperand(i));
13449   MIB.setMemRefs(MMOBegin, MMOEnd);
13450   // Reload IP
13451   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13452   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13453     if (i == X86::AddrDisp)
13454       MIB.addDisp(MI->getOperand(i), LabelOffset);
13455     else
13456       MIB.addOperand(MI->getOperand(i));
13457   }
13458   MIB.setMemRefs(MMOBegin, MMOEnd);
13459   // Reload SP
13460   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13461   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13462     if (i == X86::AddrDisp)
13463       MIB.addDisp(MI->getOperand(i), SPOffset);
13464     else
13465       MIB.addOperand(MI->getOperand(i));
13466   }
13467   MIB.setMemRefs(MMOBegin, MMOEnd);
13468   // Jump
13469   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13470
13471   MI->eraseFromParent();
13472   return MBB;
13473 }
13474
13475 MachineBasicBlock *
13476 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13477                                                MachineBasicBlock *BB) const {
13478   switch (MI->getOpcode()) {
13479   default: llvm_unreachable("Unexpected instr type to insert");
13480   case X86::TAILJMPd64:
13481   case X86::TAILJMPr64:
13482   case X86::TAILJMPm64:
13483     llvm_unreachable("TAILJMP64 would not be touched here.");
13484   case X86::TCRETURNdi64:
13485   case X86::TCRETURNri64:
13486   case X86::TCRETURNmi64:
13487     return BB;
13488   case X86::WIN_ALLOCA:
13489     return EmitLoweredWinAlloca(MI, BB);
13490   case X86::SEG_ALLOCA_32:
13491     return EmitLoweredSegAlloca(MI, BB, false);
13492   case X86::SEG_ALLOCA_64:
13493     return EmitLoweredSegAlloca(MI, BB, true);
13494   case X86::TLSCall_32:
13495   case X86::TLSCall_64:
13496     return EmitLoweredTLSCall(MI, BB);
13497   case X86::CMOV_GR8:
13498   case X86::CMOV_FR32:
13499   case X86::CMOV_FR64:
13500   case X86::CMOV_V4F32:
13501   case X86::CMOV_V2F64:
13502   case X86::CMOV_V2I64:
13503   case X86::CMOV_V8F32:
13504   case X86::CMOV_V4F64:
13505   case X86::CMOV_V4I64:
13506   case X86::CMOV_GR16:
13507   case X86::CMOV_GR32:
13508   case X86::CMOV_RFP32:
13509   case X86::CMOV_RFP64:
13510   case X86::CMOV_RFP80:
13511     return EmitLoweredSelect(MI, BB);
13512
13513   case X86::FP32_TO_INT16_IN_MEM:
13514   case X86::FP32_TO_INT32_IN_MEM:
13515   case X86::FP32_TO_INT64_IN_MEM:
13516   case X86::FP64_TO_INT16_IN_MEM:
13517   case X86::FP64_TO_INT32_IN_MEM:
13518   case X86::FP64_TO_INT64_IN_MEM:
13519   case X86::FP80_TO_INT16_IN_MEM:
13520   case X86::FP80_TO_INT32_IN_MEM:
13521   case X86::FP80_TO_INT64_IN_MEM: {
13522     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13523     DebugLoc DL = MI->getDebugLoc();
13524
13525     // Change the floating point control register to use "round towards zero"
13526     // mode when truncating to an integer value.
13527     MachineFunction *F = BB->getParent();
13528     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13529     addFrameReference(BuildMI(*BB, MI, DL,
13530                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13531
13532     // Load the old value of the high byte of the control word...
13533     unsigned OldCW =
13534       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13535     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13536                       CWFrameIdx);
13537
13538     // Set the high part to be round to zero...
13539     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13540       .addImm(0xC7F);
13541
13542     // Reload the modified control word now...
13543     addFrameReference(BuildMI(*BB, MI, DL,
13544                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13545
13546     // Restore the memory image of control word to original value
13547     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13548       .addReg(OldCW);
13549
13550     // Get the X86 opcode to use.
13551     unsigned Opc;
13552     switch (MI->getOpcode()) {
13553     default: llvm_unreachable("illegal opcode!");
13554     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13555     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13556     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13557     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13558     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13559     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13560     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13561     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13562     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13563     }
13564
13565     X86AddressMode AM;
13566     MachineOperand &Op = MI->getOperand(0);
13567     if (Op.isReg()) {
13568       AM.BaseType = X86AddressMode::RegBase;
13569       AM.Base.Reg = Op.getReg();
13570     } else {
13571       AM.BaseType = X86AddressMode::FrameIndexBase;
13572       AM.Base.FrameIndex = Op.getIndex();
13573     }
13574     Op = MI->getOperand(1);
13575     if (Op.isImm())
13576       AM.Scale = Op.getImm();
13577     Op = MI->getOperand(2);
13578     if (Op.isImm())
13579       AM.IndexReg = Op.getImm();
13580     Op = MI->getOperand(3);
13581     if (Op.isGlobal()) {
13582       AM.GV = Op.getGlobal();
13583     } else {
13584       AM.Disp = Op.getImm();
13585     }
13586     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13587                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13588
13589     // Reload the original control word now.
13590     addFrameReference(BuildMI(*BB, MI, DL,
13591                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13592
13593     MI->eraseFromParent();   // The pseudo instruction is gone now.
13594     return BB;
13595   }
13596     // String/text processing lowering.
13597   case X86::PCMPISTRM128REG:
13598   case X86::VPCMPISTRM128REG:
13599   case X86::PCMPISTRM128MEM:
13600   case X86::VPCMPISTRM128MEM:
13601   case X86::PCMPESTRM128REG:
13602   case X86::VPCMPESTRM128REG:
13603   case X86::PCMPESTRM128MEM:
13604   case X86::VPCMPESTRM128MEM: {
13605     unsigned NumArgs;
13606     bool MemArg;
13607     switch (MI->getOpcode()) {
13608     default: llvm_unreachable("illegal opcode!");
13609     case X86::PCMPISTRM128REG:
13610     case X86::VPCMPISTRM128REG:
13611       NumArgs = 3; MemArg = false; break;
13612     case X86::PCMPISTRM128MEM:
13613     case X86::VPCMPISTRM128MEM:
13614       NumArgs = 3; MemArg = true; break;
13615     case X86::PCMPESTRM128REG:
13616     case X86::VPCMPESTRM128REG:
13617       NumArgs = 5; MemArg = false; break;
13618     case X86::PCMPESTRM128MEM:
13619     case X86::VPCMPESTRM128MEM:
13620       NumArgs = 5; MemArg = true; break;
13621     }
13622     return EmitPCMP(MI, BB, NumArgs, MemArg);
13623   }
13624
13625     // Thread synchronization.
13626   case X86::MONITOR:
13627     return EmitMonitor(MI, BB);
13628
13629     // Atomic Lowering.
13630   case X86::ATOMAND8:
13631   case X86::ATOMAND16:
13632   case X86::ATOMAND32:
13633   case X86::ATOMAND64:
13634     // Fall through
13635   case X86::ATOMOR8:
13636   case X86::ATOMOR16:
13637   case X86::ATOMOR32:
13638   case X86::ATOMOR64:
13639     // Fall through
13640   case X86::ATOMXOR16:
13641   case X86::ATOMXOR8:
13642   case X86::ATOMXOR32:
13643   case X86::ATOMXOR64:
13644     // Fall through
13645   case X86::ATOMNAND8:
13646   case X86::ATOMNAND16:
13647   case X86::ATOMNAND32:
13648   case X86::ATOMNAND64:
13649     // Fall through
13650   case X86::ATOMMAX8:
13651   case X86::ATOMMAX16:
13652   case X86::ATOMMAX32:
13653   case X86::ATOMMAX64:
13654     // Fall through
13655   case X86::ATOMMIN8:
13656   case X86::ATOMMIN16:
13657   case X86::ATOMMIN32:
13658   case X86::ATOMMIN64:
13659     // Fall through
13660   case X86::ATOMUMAX8:
13661   case X86::ATOMUMAX16:
13662   case X86::ATOMUMAX32:
13663   case X86::ATOMUMAX64:
13664     // Fall through
13665   case X86::ATOMUMIN8:
13666   case X86::ATOMUMIN16:
13667   case X86::ATOMUMIN32:
13668   case X86::ATOMUMIN64:
13669     return EmitAtomicLoadArith(MI, BB);
13670
13671   // This group does 64-bit operations on a 32-bit host.
13672   case X86::ATOMAND6432:
13673   case X86::ATOMOR6432:
13674   case X86::ATOMXOR6432:
13675   case X86::ATOMNAND6432:
13676   case X86::ATOMADD6432:
13677   case X86::ATOMSUB6432:
13678   case X86::ATOMMAX6432:
13679   case X86::ATOMMIN6432:
13680   case X86::ATOMUMAX6432:
13681   case X86::ATOMUMIN6432:
13682   case X86::ATOMSWAP6432:
13683     return EmitAtomicLoadArith6432(MI, BB);
13684
13685   case X86::VASTART_SAVE_XMM_REGS:
13686     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13687
13688   case X86::VAARG_64:
13689     return EmitVAARG64WithCustomInserter(MI, BB);
13690
13691   case X86::EH_SjLj_SetJmp32:
13692   case X86::EH_SjLj_SetJmp64:
13693     return emitEHSjLjSetJmp(MI, BB);
13694
13695   case X86::EH_SjLj_LongJmp32:
13696   case X86::EH_SjLj_LongJmp64:
13697     return emitEHSjLjLongJmp(MI, BB);
13698   }
13699 }
13700
13701 //===----------------------------------------------------------------------===//
13702 //                           X86 Optimization Hooks
13703 //===----------------------------------------------------------------------===//
13704
13705 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13706                                                        APInt &KnownZero,
13707                                                        APInt &KnownOne,
13708                                                        const SelectionDAG &DAG,
13709                                                        unsigned Depth) const {
13710   unsigned BitWidth = KnownZero.getBitWidth();
13711   unsigned Opc = Op.getOpcode();
13712   assert((Opc >= ISD::BUILTIN_OP_END ||
13713           Opc == ISD::INTRINSIC_WO_CHAIN ||
13714           Opc == ISD::INTRINSIC_W_CHAIN ||
13715           Opc == ISD::INTRINSIC_VOID) &&
13716          "Should use MaskedValueIsZero if you don't know whether Op"
13717          " is a target node!");
13718
13719   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13720   switch (Opc) {
13721   default: break;
13722   case X86ISD::ADD:
13723   case X86ISD::SUB:
13724   case X86ISD::ADC:
13725   case X86ISD::SBB:
13726   case X86ISD::SMUL:
13727   case X86ISD::UMUL:
13728   case X86ISD::INC:
13729   case X86ISD::DEC:
13730   case X86ISD::OR:
13731   case X86ISD::XOR:
13732   case X86ISD::AND:
13733     // These nodes' second result is a boolean.
13734     if (Op.getResNo() == 0)
13735       break;
13736     // Fallthrough
13737   case X86ISD::SETCC:
13738     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13739     break;
13740   case ISD::INTRINSIC_WO_CHAIN: {
13741     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13742     unsigned NumLoBits = 0;
13743     switch (IntId) {
13744     default: break;
13745     case Intrinsic::x86_sse_movmsk_ps:
13746     case Intrinsic::x86_avx_movmsk_ps_256:
13747     case Intrinsic::x86_sse2_movmsk_pd:
13748     case Intrinsic::x86_avx_movmsk_pd_256:
13749     case Intrinsic::x86_mmx_pmovmskb:
13750     case Intrinsic::x86_sse2_pmovmskb_128:
13751     case Intrinsic::x86_avx2_pmovmskb: {
13752       // High bits of movmskp{s|d}, pmovmskb are known zero.
13753       switch (IntId) {
13754         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13755         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13756         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13757         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13758         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13759         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13760         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13761         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13762       }
13763       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13764       break;
13765     }
13766     }
13767     break;
13768   }
13769   }
13770 }
13771
13772 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13773                                                          unsigned Depth) const {
13774   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13775   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13776     return Op.getValueType().getScalarType().getSizeInBits();
13777
13778   // Fallback case.
13779   return 1;
13780 }
13781
13782 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13783 /// node is a GlobalAddress + offset.
13784 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13785                                        const GlobalValue* &GA,
13786                                        int64_t &Offset) const {
13787   if (N->getOpcode() == X86ISD::Wrapper) {
13788     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13789       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13790       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13791       return true;
13792     }
13793   }
13794   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13795 }
13796
13797 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13798 /// same as extracting the high 128-bit part of 256-bit vector and then
13799 /// inserting the result into the low part of a new 256-bit vector
13800 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13801   EVT VT = SVOp->getValueType(0);
13802   unsigned NumElems = VT.getVectorNumElements();
13803
13804   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13805   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13806     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13807         SVOp->getMaskElt(j) >= 0)
13808       return false;
13809
13810   return true;
13811 }
13812
13813 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13814 /// same as extracting the low 128-bit part of 256-bit vector and then
13815 /// inserting the result into the high part of a new 256-bit vector
13816 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13817   EVT VT = SVOp->getValueType(0);
13818   unsigned NumElems = VT.getVectorNumElements();
13819
13820   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13821   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13822     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13823         SVOp->getMaskElt(j) >= 0)
13824       return false;
13825
13826   return true;
13827 }
13828
13829 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13830 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13831                                         TargetLowering::DAGCombinerInfo &DCI,
13832                                         const X86Subtarget* Subtarget) {
13833   DebugLoc dl = N->getDebugLoc();
13834   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13835   SDValue V1 = SVOp->getOperand(0);
13836   SDValue V2 = SVOp->getOperand(1);
13837   EVT VT = SVOp->getValueType(0);
13838   unsigned NumElems = VT.getVectorNumElements();
13839
13840   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13841       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13842     //
13843     //                   0,0,0,...
13844     //                      |
13845     //    V      UNDEF    BUILD_VECTOR    UNDEF
13846     //     \      /           \           /
13847     //  CONCAT_VECTOR         CONCAT_VECTOR
13848     //         \                  /
13849     //          \                /
13850     //          RESULT: V + zero extended
13851     //
13852     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13853         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13854         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13855       return SDValue();
13856
13857     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13858       return SDValue();
13859
13860     // To match the shuffle mask, the first half of the mask should
13861     // be exactly the first vector, and all the rest a splat with the
13862     // first element of the second one.
13863     for (unsigned i = 0; i != NumElems/2; ++i)
13864       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13865           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13866         return SDValue();
13867
13868     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13869     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13870       if (Ld->hasNUsesOfValue(1, 0)) {
13871         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13872         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13873         SDValue ResNode =
13874           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13875                                   Ld->getMemoryVT(),
13876                                   Ld->getPointerInfo(),
13877                                   Ld->getAlignment(),
13878                                   false/*isVolatile*/, true/*ReadMem*/,
13879                                   false/*WriteMem*/);
13880         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13881       }
13882     }
13883
13884     // Emit a zeroed vector and insert the desired subvector on its
13885     // first half.
13886     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13887     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13888     return DCI.CombineTo(N, InsV);
13889   }
13890
13891   //===--------------------------------------------------------------------===//
13892   // Combine some shuffles into subvector extracts and inserts:
13893   //
13894
13895   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13896   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13897     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13898     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13899     return DCI.CombineTo(N, InsV);
13900   }
13901
13902   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13903   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13904     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13905     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13906     return DCI.CombineTo(N, InsV);
13907   }
13908
13909   return SDValue();
13910 }
13911
13912 /// PerformShuffleCombine - Performs several different shuffle combines.
13913 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13914                                      TargetLowering::DAGCombinerInfo &DCI,
13915                                      const X86Subtarget *Subtarget) {
13916   DebugLoc dl = N->getDebugLoc();
13917   EVT VT = N->getValueType(0);
13918
13919   // Don't create instructions with illegal types after legalize types has run.
13920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13921   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13922     return SDValue();
13923
13924   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13925   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13926       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13927     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13928
13929   // Only handle 128 wide vector from here on.
13930   if (!VT.is128BitVector())
13931     return SDValue();
13932
13933   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13934   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13935   // consecutive, non-overlapping, and in the right order.
13936   SmallVector<SDValue, 16> Elts;
13937   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13938     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13939
13940   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13941 }
13942
13943
13944 /// PerformTruncateCombine - Converts truncate operation to
13945 /// a sequence of vector shuffle operations.
13946 /// It is possible when we truncate 256-bit vector to 128-bit vector
13947 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13948                                       TargetLowering::DAGCombinerInfo &DCI,
13949                                       const X86Subtarget *Subtarget)  {
13950   if (!DCI.isBeforeLegalizeOps())
13951     return SDValue();
13952
13953   if (!Subtarget->hasAVX())
13954     return SDValue();
13955
13956   EVT VT = N->getValueType(0);
13957   SDValue Op = N->getOperand(0);
13958   EVT OpVT = Op.getValueType();
13959   DebugLoc dl = N->getDebugLoc();
13960
13961   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13962
13963     if (Subtarget->hasAVX2()) {
13964       // AVX2: v4i64 -> v4i32
13965
13966       // VPERMD
13967       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13968
13969       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13970       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13971                                 ShufMask);
13972
13973       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13974                          DAG.getIntPtrConstant(0));
13975     }
13976
13977     // AVX: v4i64 -> v4i32
13978     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13979                                DAG.getIntPtrConstant(0));
13980
13981     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13982                                DAG.getIntPtrConstant(2));
13983
13984     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13985     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13986
13987     // PSHUFD
13988     static const int ShufMask1[] = {0, 2, 0, 0};
13989
13990     SDValue Undef = DAG.getUNDEF(VT);
13991     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13992     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13993
13994     // MOVLHPS
13995     static const int ShufMask2[] = {0, 1, 4, 5};
13996
13997     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13998   }
13999
14000   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14001
14002     if (Subtarget->hasAVX2()) {
14003       // AVX2: v8i32 -> v8i16
14004
14005       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14006
14007       // PSHUFB
14008       SmallVector<SDValue,32> pshufbMask;
14009       for (unsigned i = 0; i < 2; ++i) {
14010         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14011         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14012         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14013         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14014         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14015         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14016         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14017         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14018         for (unsigned j = 0; j < 8; ++j)
14019           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14020       }
14021       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14022                                &pshufbMask[0], 32);
14023       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14024
14025       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14026
14027       static const int ShufMask[] = {0,  2,  -1,  -1};
14028       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14029                                 &ShufMask[0]);
14030
14031       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14032                        DAG.getIntPtrConstant(0));
14033
14034       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14035     }
14036
14037     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14038                                DAG.getIntPtrConstant(0));
14039
14040     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14041                                DAG.getIntPtrConstant(4));
14042
14043     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14044     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14045
14046     // PSHUFB
14047     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14048                                    -1, -1, -1, -1, -1, -1, -1, -1};
14049
14050     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14051     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14052     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14053
14054     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14055     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14056
14057     // MOVLHPS
14058     static const int ShufMask2[] = {0, 1, 4, 5};
14059
14060     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14061     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14062   }
14063
14064   return SDValue();
14065 }
14066
14067 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14068 /// specific shuffle of a load can be folded into a single element load.
14069 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14070 /// shuffles have been customed lowered so we need to handle those here.
14071 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14072                                          TargetLowering::DAGCombinerInfo &DCI) {
14073   if (DCI.isBeforeLegalizeOps())
14074     return SDValue();
14075
14076   SDValue InVec = N->getOperand(0);
14077   SDValue EltNo = N->getOperand(1);
14078
14079   if (!isa<ConstantSDNode>(EltNo))
14080     return SDValue();
14081
14082   EVT VT = InVec.getValueType();
14083
14084   bool HasShuffleIntoBitcast = false;
14085   if (InVec.getOpcode() == ISD::BITCAST) {
14086     // Don't duplicate a load with other uses.
14087     if (!InVec.hasOneUse())
14088       return SDValue();
14089     EVT BCVT = InVec.getOperand(0).getValueType();
14090     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14091       return SDValue();
14092     InVec = InVec.getOperand(0);
14093     HasShuffleIntoBitcast = true;
14094   }
14095
14096   if (!isTargetShuffle(InVec.getOpcode()))
14097     return SDValue();
14098
14099   // Don't duplicate a load with other uses.
14100   if (!InVec.hasOneUse())
14101     return SDValue();
14102
14103   SmallVector<int, 16> ShuffleMask;
14104   bool UnaryShuffle;
14105   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14106                             UnaryShuffle))
14107     return SDValue();
14108
14109   // Select the input vector, guarding against out of range extract vector.
14110   unsigned NumElems = VT.getVectorNumElements();
14111   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14112   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14113   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14114                                          : InVec.getOperand(1);
14115
14116   // If inputs to shuffle are the same for both ops, then allow 2 uses
14117   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14118
14119   if (LdNode.getOpcode() == ISD::BITCAST) {
14120     // Don't duplicate a load with other uses.
14121     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14122       return SDValue();
14123
14124     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14125     LdNode = LdNode.getOperand(0);
14126   }
14127
14128   if (!ISD::isNormalLoad(LdNode.getNode()))
14129     return SDValue();
14130
14131   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14132
14133   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14134     return SDValue();
14135
14136   if (HasShuffleIntoBitcast) {
14137     // If there's a bitcast before the shuffle, check if the load type and
14138     // alignment is valid.
14139     unsigned Align = LN0->getAlignment();
14140     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14141     unsigned NewAlign = TLI.getDataLayout()->
14142       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14143
14144     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14145       return SDValue();
14146   }
14147
14148   // All checks match so transform back to vector_shuffle so that DAG combiner
14149   // can finish the job
14150   DebugLoc dl = N->getDebugLoc();
14151
14152   // Create shuffle node taking into account the case that its a unary shuffle
14153   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14154   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14155                                  InVec.getOperand(0), Shuffle,
14156                                  &ShuffleMask[0]);
14157   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14158   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14159                      EltNo);
14160 }
14161
14162 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14163 /// generation and convert it from being a bunch of shuffles and extracts
14164 /// to a simple store and scalar loads to extract the elements.
14165 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14166                                          TargetLowering::DAGCombinerInfo &DCI) {
14167   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14168   if (NewOp.getNode())
14169     return NewOp;
14170
14171   SDValue InputVector = N->getOperand(0);
14172
14173   // Only operate on vectors of 4 elements, where the alternative shuffling
14174   // gets to be more expensive.
14175   if (InputVector.getValueType() != MVT::v4i32)
14176     return SDValue();
14177
14178   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14179   // single use which is a sign-extend or zero-extend, and all elements are
14180   // used.
14181   SmallVector<SDNode *, 4> Uses;
14182   unsigned ExtractedElements = 0;
14183   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14184        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14185     if (UI.getUse().getResNo() != InputVector.getResNo())
14186       return SDValue();
14187
14188     SDNode *Extract = *UI;
14189     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14190       return SDValue();
14191
14192     if (Extract->getValueType(0) != MVT::i32)
14193       return SDValue();
14194     if (!Extract->hasOneUse())
14195       return SDValue();
14196     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14197         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14198       return SDValue();
14199     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14200       return SDValue();
14201
14202     // Record which element was extracted.
14203     ExtractedElements |=
14204       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14205
14206     Uses.push_back(Extract);
14207   }
14208
14209   // If not all the elements were used, this may not be worthwhile.
14210   if (ExtractedElements != 15)
14211     return SDValue();
14212
14213   // Ok, we've now decided to do the transformation.
14214   DebugLoc dl = InputVector.getDebugLoc();
14215
14216   // Store the value to a temporary stack slot.
14217   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14218   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14219                             MachinePointerInfo(), false, false, 0);
14220
14221   // Replace each use (extract) with a load of the appropriate element.
14222   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14223        UE = Uses.end(); UI != UE; ++UI) {
14224     SDNode *Extract = *UI;
14225
14226     // cOMpute the element's address.
14227     SDValue Idx = Extract->getOperand(1);
14228     unsigned EltSize =
14229         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14230     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14231     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14232     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14233
14234     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14235                                      StackPtr, OffsetVal);
14236
14237     // Load the scalar.
14238     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14239                                      ScalarAddr, MachinePointerInfo(),
14240                                      false, false, false, 0);
14241
14242     // Replace the exact with the load.
14243     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14244   }
14245
14246   // The replacement was made in place; don't return anything.
14247   return SDValue();
14248 }
14249
14250 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14251 /// nodes.
14252 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14253                                     TargetLowering::DAGCombinerInfo &DCI,
14254                                     const X86Subtarget *Subtarget) {
14255   DebugLoc DL = N->getDebugLoc();
14256   SDValue Cond = N->getOperand(0);
14257   // Get the LHS/RHS of the select.
14258   SDValue LHS = N->getOperand(1);
14259   SDValue RHS = N->getOperand(2);
14260   EVT VT = LHS.getValueType();
14261
14262   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14263   // instructions match the semantics of the common C idiom x<y?x:y but not
14264   // x<=y?x:y, because of how they handle negative zero (which can be
14265   // ignored in unsafe-math mode).
14266   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14267       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14268       (Subtarget->hasSSE2() ||
14269        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14270     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14271
14272     unsigned Opcode = 0;
14273     // Check for x CC y ? x : y.
14274     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14275         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14276       switch (CC) {
14277       default: break;
14278       case ISD::SETULT:
14279         // Converting this to a min would handle NaNs incorrectly, and swapping
14280         // the operands would cause it to handle comparisons between positive
14281         // and negative zero incorrectly.
14282         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14283           if (!DAG.getTarget().Options.UnsafeFPMath &&
14284               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14285             break;
14286           std::swap(LHS, RHS);
14287         }
14288         Opcode = X86ISD::FMIN;
14289         break;
14290       case ISD::SETOLE:
14291         // Converting this to a min would handle comparisons between positive
14292         // and negative zero incorrectly.
14293         if (!DAG.getTarget().Options.UnsafeFPMath &&
14294             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14295           break;
14296         Opcode = X86ISD::FMIN;
14297         break;
14298       case ISD::SETULE:
14299         // Converting this to a min would handle both negative zeros and NaNs
14300         // incorrectly, but we can swap the operands to fix both.
14301         std::swap(LHS, RHS);
14302       case ISD::SETOLT:
14303       case ISD::SETLT:
14304       case ISD::SETLE:
14305         Opcode = X86ISD::FMIN;
14306         break;
14307
14308       case ISD::SETOGE:
14309         // Converting this to a max would handle comparisons between positive
14310         // and negative zero incorrectly.
14311         if (!DAG.getTarget().Options.UnsafeFPMath &&
14312             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14313           break;
14314         Opcode = X86ISD::FMAX;
14315         break;
14316       case ISD::SETUGT:
14317         // Converting this to a max would handle NaNs incorrectly, and swapping
14318         // the operands would cause it to handle comparisons between positive
14319         // and negative zero incorrectly.
14320         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14321           if (!DAG.getTarget().Options.UnsafeFPMath &&
14322               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14323             break;
14324           std::swap(LHS, RHS);
14325         }
14326         Opcode = X86ISD::FMAX;
14327         break;
14328       case ISD::SETUGE:
14329         // Converting this to a max would handle both negative zeros and NaNs
14330         // incorrectly, but we can swap the operands to fix both.
14331         std::swap(LHS, RHS);
14332       case ISD::SETOGT:
14333       case ISD::SETGT:
14334       case ISD::SETGE:
14335         Opcode = X86ISD::FMAX;
14336         break;
14337       }
14338     // Check for x CC y ? y : x -- a min/max with reversed arms.
14339     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14340                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14341       switch (CC) {
14342       default: break;
14343       case ISD::SETOGE:
14344         // Converting this to a min would handle comparisons between positive
14345         // and negative zero incorrectly, and swapping the operands would
14346         // cause it to handle NaNs incorrectly.
14347         if (!DAG.getTarget().Options.UnsafeFPMath &&
14348             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14349           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14350             break;
14351           std::swap(LHS, RHS);
14352         }
14353         Opcode = X86ISD::FMIN;
14354         break;
14355       case ISD::SETUGT:
14356         // Converting this to a min would handle NaNs incorrectly.
14357         if (!DAG.getTarget().Options.UnsafeFPMath &&
14358             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14359           break;
14360         Opcode = X86ISD::FMIN;
14361         break;
14362       case ISD::SETUGE:
14363         // Converting this to a min would handle both negative zeros and NaNs
14364         // incorrectly, but we can swap the operands to fix both.
14365         std::swap(LHS, RHS);
14366       case ISD::SETOGT:
14367       case ISD::SETGT:
14368       case ISD::SETGE:
14369         Opcode = X86ISD::FMIN;
14370         break;
14371
14372       case ISD::SETULT:
14373         // Converting this to a max would handle NaNs incorrectly.
14374         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14375           break;
14376         Opcode = X86ISD::FMAX;
14377         break;
14378       case ISD::SETOLE:
14379         // Converting this to a max would handle comparisons between positive
14380         // and negative zero incorrectly, and swapping the operands would
14381         // cause it to handle NaNs incorrectly.
14382         if (!DAG.getTarget().Options.UnsafeFPMath &&
14383             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14384           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14385             break;
14386           std::swap(LHS, RHS);
14387         }
14388         Opcode = X86ISD::FMAX;
14389         break;
14390       case ISD::SETULE:
14391         // Converting this to a max would handle both negative zeros and NaNs
14392         // incorrectly, but we can swap the operands to fix both.
14393         std::swap(LHS, RHS);
14394       case ISD::SETOLT:
14395       case ISD::SETLT:
14396       case ISD::SETLE:
14397         Opcode = X86ISD::FMAX;
14398         break;
14399       }
14400     }
14401
14402     if (Opcode)
14403       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14404   }
14405
14406   // If this is a select between two integer constants, try to do some
14407   // optimizations.
14408   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14409     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14410       // Don't do this for crazy integer types.
14411       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14412         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14413         // so that TrueC (the true value) is larger than FalseC.
14414         bool NeedsCondInvert = false;
14415
14416         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14417             // Efficiently invertible.
14418             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14419              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14420               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14421           NeedsCondInvert = true;
14422           std::swap(TrueC, FalseC);
14423         }
14424
14425         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14426         if (FalseC->getAPIntValue() == 0 &&
14427             TrueC->getAPIntValue().isPowerOf2()) {
14428           if (NeedsCondInvert) // Invert the condition if needed.
14429             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14430                                DAG.getConstant(1, Cond.getValueType()));
14431
14432           // Zero extend the condition if needed.
14433           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14434
14435           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14436           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14437                              DAG.getConstant(ShAmt, MVT::i8));
14438         }
14439
14440         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14441         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14442           if (NeedsCondInvert) // Invert the condition if needed.
14443             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14444                                DAG.getConstant(1, Cond.getValueType()));
14445
14446           // Zero extend the condition if needed.
14447           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14448                              FalseC->getValueType(0), Cond);
14449           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14450                              SDValue(FalseC, 0));
14451         }
14452
14453         // Optimize cases that will turn into an LEA instruction.  This requires
14454         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14455         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14456           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14457           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14458
14459           bool isFastMultiplier = false;
14460           if (Diff < 10) {
14461             switch ((unsigned char)Diff) {
14462               default: break;
14463               case 1:  // result = add base, cond
14464               case 2:  // result = lea base(    , cond*2)
14465               case 3:  // result = lea base(cond, cond*2)
14466               case 4:  // result = lea base(    , cond*4)
14467               case 5:  // result = lea base(cond, cond*4)
14468               case 8:  // result = lea base(    , cond*8)
14469               case 9:  // result = lea base(cond, cond*8)
14470                 isFastMultiplier = true;
14471                 break;
14472             }
14473           }
14474
14475           if (isFastMultiplier) {
14476             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14477             if (NeedsCondInvert) // Invert the condition if needed.
14478               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14479                                  DAG.getConstant(1, Cond.getValueType()));
14480
14481             // Zero extend the condition if needed.
14482             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14483                                Cond);
14484             // Scale the condition by the difference.
14485             if (Diff != 1)
14486               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14487                                  DAG.getConstant(Diff, Cond.getValueType()));
14488
14489             // Add the base if non-zero.
14490             if (FalseC->getAPIntValue() != 0)
14491               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14492                                  SDValue(FalseC, 0));
14493             return Cond;
14494           }
14495         }
14496       }
14497   }
14498
14499   // Canonicalize max and min:
14500   // (x > y) ? x : y -> (x >= y) ? x : y
14501   // (x < y) ? x : y -> (x <= y) ? x : y
14502   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14503   // the need for an extra compare
14504   // against zero. e.g.
14505   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14506   // subl   %esi, %edi
14507   // testl  %edi, %edi
14508   // movl   $0, %eax
14509   // cmovgl %edi, %eax
14510   // =>
14511   // xorl   %eax, %eax
14512   // subl   %esi, $edi
14513   // cmovsl %eax, %edi
14514   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14515       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14516       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14517     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14518     switch (CC) {
14519     default: break;
14520     case ISD::SETLT:
14521     case ISD::SETGT: {
14522       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14523       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14524                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14525       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14526     }
14527     }
14528   }
14529
14530   // If we know that this node is legal then we know that it is going to be
14531   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14532   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14533   // to simplify previous instructions.
14534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14535   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14536       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14537     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14538
14539     // Don't optimize vector selects that map to mask-registers.
14540     if (BitWidth == 1)
14541       return SDValue();
14542
14543     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14544     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14545
14546     APInt KnownZero, KnownOne;
14547     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14548                                           DCI.isBeforeLegalizeOps());
14549     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14550         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14551       DCI.CommitTargetLoweringOpt(TLO);
14552   }
14553
14554   return SDValue();
14555 }
14556
14557 // Check whether a boolean test is testing a boolean value generated by
14558 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14559 // code.
14560 //
14561 // Simplify the following patterns:
14562 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14563 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14564 // to (Op EFLAGS Cond)
14565 //
14566 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14567 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14568 // to (Op EFLAGS !Cond)
14569 //
14570 // where Op could be BRCOND or CMOV.
14571 //
14572 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14573   // Quit if not CMP and SUB with its value result used.
14574   if (Cmp.getOpcode() != X86ISD::CMP &&
14575       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14576       return SDValue();
14577
14578   // Quit if not used as a boolean value.
14579   if (CC != X86::COND_E && CC != X86::COND_NE)
14580     return SDValue();
14581
14582   // Check CMP operands. One of them should be 0 or 1 and the other should be
14583   // an SetCC or extended from it.
14584   SDValue Op1 = Cmp.getOperand(0);
14585   SDValue Op2 = Cmp.getOperand(1);
14586
14587   SDValue SetCC;
14588   const ConstantSDNode* C = 0;
14589   bool needOppositeCond = (CC == X86::COND_E);
14590
14591   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14592     SetCC = Op2;
14593   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14594     SetCC = Op1;
14595   else // Quit if all operands are not constants.
14596     return SDValue();
14597
14598   if (C->getZExtValue() == 1)
14599     needOppositeCond = !needOppositeCond;
14600   else if (C->getZExtValue() != 0)
14601     // Quit if the constant is neither 0 or 1.
14602     return SDValue();
14603
14604   // Skip 'zext' node.
14605   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14606     SetCC = SetCC.getOperand(0);
14607
14608   switch (SetCC.getOpcode()) {
14609   case X86ISD::SETCC:
14610     // Set the condition code or opposite one if necessary.
14611     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14612     if (needOppositeCond)
14613       CC = X86::GetOppositeBranchCondition(CC);
14614     return SetCC.getOperand(1);
14615   case X86ISD::CMOV: {
14616     // Check whether false/true value has canonical one, i.e. 0 or 1.
14617     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14618     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14619     // Quit if true value is not a constant.
14620     if (!TVal)
14621       return SDValue();
14622     // Quit if false value is not a constant.
14623     if (!FVal) {
14624       // A special case for rdrand, where 0 is set if false cond is found.
14625       SDValue Op = SetCC.getOperand(0);
14626       if (Op.getOpcode() != X86ISD::RDRAND)
14627         return SDValue();
14628     }
14629     // Quit if false value is not the constant 0 or 1.
14630     bool FValIsFalse = true;
14631     if (FVal && FVal->getZExtValue() != 0) {
14632       if (FVal->getZExtValue() != 1)
14633         return SDValue();
14634       // If FVal is 1, opposite cond is needed.
14635       needOppositeCond = !needOppositeCond;
14636       FValIsFalse = false;
14637     }
14638     // Quit if TVal is not the constant opposite of FVal.
14639     if (FValIsFalse && TVal->getZExtValue() != 1)
14640       return SDValue();
14641     if (!FValIsFalse && TVal->getZExtValue() != 0)
14642       return SDValue();
14643     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14644     if (needOppositeCond)
14645       CC = X86::GetOppositeBranchCondition(CC);
14646     return SetCC.getOperand(3);
14647   }
14648   }
14649
14650   return SDValue();
14651 }
14652
14653 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14654 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14655                                   TargetLowering::DAGCombinerInfo &DCI,
14656                                   const X86Subtarget *Subtarget) {
14657   DebugLoc DL = N->getDebugLoc();
14658
14659   // If the flag operand isn't dead, don't touch this CMOV.
14660   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14661     return SDValue();
14662
14663   SDValue FalseOp = N->getOperand(0);
14664   SDValue TrueOp = N->getOperand(1);
14665   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14666   SDValue Cond = N->getOperand(3);
14667
14668   if (CC == X86::COND_E || CC == X86::COND_NE) {
14669     switch (Cond.getOpcode()) {
14670     default: break;
14671     case X86ISD::BSR:
14672     case X86ISD::BSF:
14673       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14674       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14675         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14676     }
14677   }
14678
14679   SDValue Flags;
14680
14681   Flags = checkBoolTestSetCCCombine(Cond, CC);
14682   if (Flags.getNode() &&
14683       // Extra check as FCMOV only supports a subset of X86 cond.
14684       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14685     SDValue Ops[] = { FalseOp, TrueOp,
14686                       DAG.getConstant(CC, MVT::i8), Flags };
14687     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14688                        Ops, array_lengthof(Ops));
14689   }
14690
14691   // If this is a select between two integer constants, try to do some
14692   // optimizations.  Note that the operands are ordered the opposite of SELECT
14693   // operands.
14694   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14695     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14696       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14697       // larger than FalseC (the false value).
14698       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14699         CC = X86::GetOppositeBranchCondition(CC);
14700         std::swap(TrueC, FalseC);
14701         std::swap(TrueOp, FalseOp);
14702       }
14703
14704       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14705       // This is efficient for any integer data type (including i8/i16) and
14706       // shift amount.
14707       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14708         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14709                            DAG.getConstant(CC, MVT::i8), Cond);
14710
14711         // Zero extend the condition if needed.
14712         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14713
14714         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14715         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14716                            DAG.getConstant(ShAmt, MVT::i8));
14717         if (N->getNumValues() == 2)  // Dead flag value?
14718           return DCI.CombineTo(N, Cond, SDValue());
14719         return Cond;
14720       }
14721
14722       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14723       // for any integer data type, including i8/i16.
14724       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14725         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14726                            DAG.getConstant(CC, MVT::i8), Cond);
14727
14728         // Zero extend the condition if needed.
14729         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14730                            FalseC->getValueType(0), Cond);
14731         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14732                            SDValue(FalseC, 0));
14733
14734         if (N->getNumValues() == 2)  // Dead flag value?
14735           return DCI.CombineTo(N, Cond, SDValue());
14736         return Cond;
14737       }
14738
14739       // Optimize cases that will turn into an LEA instruction.  This requires
14740       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14741       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14742         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14743         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14744
14745         bool isFastMultiplier = false;
14746         if (Diff < 10) {
14747           switch ((unsigned char)Diff) {
14748           default: break;
14749           case 1:  // result = add base, cond
14750           case 2:  // result = lea base(    , cond*2)
14751           case 3:  // result = lea base(cond, cond*2)
14752           case 4:  // result = lea base(    , cond*4)
14753           case 5:  // result = lea base(cond, cond*4)
14754           case 8:  // result = lea base(    , cond*8)
14755           case 9:  // result = lea base(cond, cond*8)
14756             isFastMultiplier = true;
14757             break;
14758           }
14759         }
14760
14761         if (isFastMultiplier) {
14762           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14763           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14764                              DAG.getConstant(CC, MVT::i8), Cond);
14765           // Zero extend the condition if needed.
14766           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14767                              Cond);
14768           // Scale the condition by the difference.
14769           if (Diff != 1)
14770             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14771                                DAG.getConstant(Diff, Cond.getValueType()));
14772
14773           // Add the base if non-zero.
14774           if (FalseC->getAPIntValue() != 0)
14775             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14776                                SDValue(FalseC, 0));
14777           if (N->getNumValues() == 2)  // Dead flag value?
14778             return DCI.CombineTo(N, Cond, SDValue());
14779           return Cond;
14780         }
14781       }
14782     }
14783   }
14784
14785   // Handle these cases:
14786   //   (select (x != c), e, c) -> select (x != c), e, x),
14787   //   (select (x == c), c, e) -> select (x == c), x, e)
14788   // where the c is an integer constant, and the "select" is the combination
14789   // of CMOV and CMP.
14790   //
14791   // The rationale for this change is that the conditional-move from a constant
14792   // needs two instructions, however, conditional-move from a register needs
14793   // only one instruction.
14794   //
14795   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14796   //  some instruction-combining opportunities. This opt needs to be
14797   //  postponed as late as possible.
14798   //
14799   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14800     // the DCI.xxxx conditions are provided to postpone the optimization as
14801     // late as possible.
14802
14803     ConstantSDNode *CmpAgainst = 0;
14804     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14805         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14806         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14807
14808       if (CC == X86::COND_NE &&
14809           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14810         CC = X86::GetOppositeBranchCondition(CC);
14811         std::swap(TrueOp, FalseOp);
14812       }
14813
14814       if (CC == X86::COND_E &&
14815           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14816         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14817                           DAG.getConstant(CC, MVT::i8), Cond };
14818         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14819                            array_lengthof(Ops));
14820       }
14821     }
14822   }
14823
14824   return SDValue();
14825 }
14826
14827
14828 /// PerformMulCombine - Optimize a single multiply with constant into two
14829 /// in order to implement it with two cheaper instructions, e.g.
14830 /// LEA + SHL, LEA + LEA.
14831 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14832                                  TargetLowering::DAGCombinerInfo &DCI) {
14833   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14834     return SDValue();
14835
14836   EVT VT = N->getValueType(0);
14837   if (VT != MVT::i64)
14838     return SDValue();
14839
14840   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14841   if (!C)
14842     return SDValue();
14843   uint64_t MulAmt = C->getZExtValue();
14844   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14845     return SDValue();
14846
14847   uint64_t MulAmt1 = 0;
14848   uint64_t MulAmt2 = 0;
14849   if ((MulAmt % 9) == 0) {
14850     MulAmt1 = 9;
14851     MulAmt2 = MulAmt / 9;
14852   } else if ((MulAmt % 5) == 0) {
14853     MulAmt1 = 5;
14854     MulAmt2 = MulAmt / 5;
14855   } else if ((MulAmt % 3) == 0) {
14856     MulAmt1 = 3;
14857     MulAmt2 = MulAmt / 3;
14858   }
14859   if (MulAmt2 &&
14860       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14861     DebugLoc DL = N->getDebugLoc();
14862
14863     if (isPowerOf2_64(MulAmt2) &&
14864         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14865       // If second multiplifer is pow2, issue it first. We want the multiply by
14866       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14867       // is an add.
14868       std::swap(MulAmt1, MulAmt2);
14869
14870     SDValue NewMul;
14871     if (isPowerOf2_64(MulAmt1))
14872       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14873                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14874     else
14875       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14876                            DAG.getConstant(MulAmt1, VT));
14877
14878     if (isPowerOf2_64(MulAmt2))
14879       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14880                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14881     else
14882       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14883                            DAG.getConstant(MulAmt2, VT));
14884
14885     // Do not add new nodes to DAG combiner worklist.
14886     DCI.CombineTo(N, NewMul, false);
14887   }
14888   return SDValue();
14889 }
14890
14891 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14892   SDValue N0 = N->getOperand(0);
14893   SDValue N1 = N->getOperand(1);
14894   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14895   EVT VT = N0.getValueType();
14896
14897   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14898   // since the result of setcc_c is all zero's or all ones.
14899   if (VT.isInteger() && !VT.isVector() &&
14900       N1C && N0.getOpcode() == ISD::AND &&
14901       N0.getOperand(1).getOpcode() == ISD::Constant) {
14902     SDValue N00 = N0.getOperand(0);
14903     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14904         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14905           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14906          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14907       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14908       APInt ShAmt = N1C->getAPIntValue();
14909       Mask = Mask.shl(ShAmt);
14910       if (Mask != 0)
14911         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14912                            N00, DAG.getConstant(Mask, VT));
14913     }
14914   }
14915
14916
14917   // Hardware support for vector shifts is sparse which makes us scalarize the
14918   // vector operations in many cases. Also, on sandybridge ADD is faster than
14919   // shl.
14920   // (shl V, 1) -> add V,V
14921   if (isSplatVector(N1.getNode())) {
14922     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14923     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14924     // We shift all of the values by one. In many cases we do not have
14925     // hardware support for this operation. This is better expressed as an ADD
14926     // of two values.
14927     if (N1C && (1 == N1C->getZExtValue())) {
14928       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14929     }
14930   }
14931
14932   return SDValue();
14933 }
14934
14935 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14936 ///                       when possible.
14937 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14938                                    TargetLowering::DAGCombinerInfo &DCI,
14939                                    const X86Subtarget *Subtarget) {
14940   EVT VT = N->getValueType(0);
14941   if (N->getOpcode() == ISD::SHL) {
14942     SDValue V = PerformSHLCombine(N, DAG);
14943     if (V.getNode()) return V;
14944   }
14945
14946   // On X86 with SSE2 support, we can transform this to a vector shift if
14947   // all elements are shifted by the same amount.  We can't do this in legalize
14948   // because the a constant vector is typically transformed to a constant pool
14949   // so we have no knowledge of the shift amount.
14950   if (!Subtarget->hasSSE2())
14951     return SDValue();
14952
14953   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14954       (!Subtarget->hasAVX2() ||
14955        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14956     return SDValue();
14957
14958   SDValue ShAmtOp = N->getOperand(1);
14959   EVT EltVT = VT.getVectorElementType();
14960   DebugLoc DL = N->getDebugLoc();
14961   SDValue BaseShAmt = SDValue();
14962   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14963     unsigned NumElts = VT.getVectorNumElements();
14964     unsigned i = 0;
14965     for (; i != NumElts; ++i) {
14966       SDValue Arg = ShAmtOp.getOperand(i);
14967       if (Arg.getOpcode() == ISD::UNDEF) continue;
14968       BaseShAmt = Arg;
14969       break;
14970     }
14971     // Handle the case where the build_vector is all undef
14972     // FIXME: Should DAG allow this?
14973     if (i == NumElts)
14974       return SDValue();
14975
14976     for (; i != NumElts; ++i) {
14977       SDValue Arg = ShAmtOp.getOperand(i);
14978       if (Arg.getOpcode() == ISD::UNDEF) continue;
14979       if (Arg != BaseShAmt) {
14980         return SDValue();
14981       }
14982     }
14983   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14984              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14985     SDValue InVec = ShAmtOp.getOperand(0);
14986     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14987       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14988       unsigned i = 0;
14989       for (; i != NumElts; ++i) {
14990         SDValue Arg = InVec.getOperand(i);
14991         if (Arg.getOpcode() == ISD::UNDEF) continue;
14992         BaseShAmt = Arg;
14993         break;
14994       }
14995     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14996        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14997          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14998          if (C->getZExtValue() == SplatIdx)
14999            BaseShAmt = InVec.getOperand(1);
15000        }
15001     }
15002     if (BaseShAmt.getNode() == 0) {
15003       // Don't create instructions with illegal types after legalize
15004       // types has run.
15005       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15006           !DCI.isBeforeLegalize())
15007         return SDValue();
15008
15009       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15010                               DAG.getIntPtrConstant(0));
15011     }
15012   } else
15013     return SDValue();
15014
15015   // The shift amount is an i32.
15016   if (EltVT.bitsGT(MVT::i32))
15017     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15018   else if (EltVT.bitsLT(MVT::i32))
15019     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15020
15021   // The shift amount is identical so we can do a vector shift.
15022   SDValue  ValOp = N->getOperand(0);
15023   switch (N->getOpcode()) {
15024   default:
15025     llvm_unreachable("Unknown shift opcode!");
15026   case ISD::SHL:
15027     switch (VT.getSimpleVT().SimpleTy) {
15028     default: return SDValue();
15029     case MVT::v2i64:
15030     case MVT::v4i32:
15031     case MVT::v8i16:
15032     case MVT::v4i64:
15033     case MVT::v8i32:
15034     case MVT::v16i16:
15035       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15036     }
15037   case ISD::SRA:
15038     switch (VT.getSimpleVT().SimpleTy) {
15039     default: return SDValue();
15040     case MVT::v4i32:
15041     case MVT::v8i16:
15042     case MVT::v8i32:
15043     case MVT::v16i16:
15044       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15045     }
15046   case ISD::SRL:
15047     switch (VT.getSimpleVT().SimpleTy) {
15048     default: return SDValue();
15049     case MVT::v2i64:
15050     case MVT::v4i32:
15051     case MVT::v8i16:
15052     case MVT::v4i64:
15053     case MVT::v8i32:
15054     case MVT::v16i16:
15055       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15056     }
15057   }
15058 }
15059
15060
15061 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15062 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15063 // and friends.  Likewise for OR -> CMPNEQSS.
15064 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15065                             TargetLowering::DAGCombinerInfo &DCI,
15066                             const X86Subtarget *Subtarget) {
15067   unsigned opcode;
15068
15069   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15070   // we're requiring SSE2 for both.
15071   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15072     SDValue N0 = N->getOperand(0);
15073     SDValue N1 = N->getOperand(1);
15074     SDValue CMP0 = N0->getOperand(1);
15075     SDValue CMP1 = N1->getOperand(1);
15076     DebugLoc DL = N->getDebugLoc();
15077
15078     // The SETCCs should both refer to the same CMP.
15079     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15080       return SDValue();
15081
15082     SDValue CMP00 = CMP0->getOperand(0);
15083     SDValue CMP01 = CMP0->getOperand(1);
15084     EVT     VT    = CMP00.getValueType();
15085
15086     if (VT == MVT::f32 || VT == MVT::f64) {
15087       bool ExpectingFlags = false;
15088       // Check for any users that want flags:
15089       for (SDNode::use_iterator UI = N->use_begin(),
15090              UE = N->use_end();
15091            !ExpectingFlags && UI != UE; ++UI)
15092         switch (UI->getOpcode()) {
15093         default:
15094         case ISD::BR_CC:
15095         case ISD::BRCOND:
15096         case ISD::SELECT:
15097           ExpectingFlags = true;
15098           break;
15099         case ISD::CopyToReg:
15100         case ISD::SIGN_EXTEND:
15101         case ISD::ZERO_EXTEND:
15102         case ISD::ANY_EXTEND:
15103           break;
15104         }
15105
15106       if (!ExpectingFlags) {
15107         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15108         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15109
15110         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15111           X86::CondCode tmp = cc0;
15112           cc0 = cc1;
15113           cc1 = tmp;
15114         }
15115
15116         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15117             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15118           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15119           X86ISD::NodeType NTOperator = is64BitFP ?
15120             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15121           // FIXME: need symbolic constants for these magic numbers.
15122           // See X86ATTInstPrinter.cpp:printSSECC().
15123           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15124           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15125                                               DAG.getConstant(x86cc, MVT::i8));
15126           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15127                                               OnesOrZeroesF);
15128           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15129                                       DAG.getConstant(1, MVT::i32));
15130           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15131           return OneBitOfTruth;
15132         }
15133       }
15134     }
15135   }
15136   return SDValue();
15137 }
15138
15139 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15140 /// so it can be folded inside ANDNP.
15141 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15142   EVT VT = N->getValueType(0);
15143
15144   // Match direct AllOnes for 128 and 256-bit vectors
15145   if (ISD::isBuildVectorAllOnes(N))
15146     return true;
15147
15148   // Look through a bit convert.
15149   if (N->getOpcode() == ISD::BITCAST)
15150     N = N->getOperand(0).getNode();
15151
15152   // Sometimes the operand may come from a insert_subvector building a 256-bit
15153   // allones vector
15154   if (VT.is256BitVector() &&
15155       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15156     SDValue V1 = N->getOperand(0);
15157     SDValue V2 = N->getOperand(1);
15158
15159     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15160         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15161         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15162         ISD::isBuildVectorAllOnes(V2.getNode()))
15163       return true;
15164   }
15165
15166   return false;
15167 }
15168
15169 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15170                                  TargetLowering::DAGCombinerInfo &DCI,
15171                                  const X86Subtarget *Subtarget) {
15172   if (DCI.isBeforeLegalizeOps())
15173     return SDValue();
15174
15175   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15176   if (R.getNode())
15177     return R;
15178
15179   EVT VT = N->getValueType(0);
15180
15181   // Create ANDN, BLSI, and BLSR instructions
15182   // BLSI is X & (-X)
15183   // BLSR is X & (X-1)
15184   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15185     SDValue N0 = N->getOperand(0);
15186     SDValue N1 = N->getOperand(1);
15187     DebugLoc DL = N->getDebugLoc();
15188
15189     // Check LHS for not
15190     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15191       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15192     // Check RHS for not
15193     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15194       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15195
15196     // Check LHS for neg
15197     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15198         isZero(N0.getOperand(0)))
15199       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15200
15201     // Check RHS for neg
15202     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15203         isZero(N1.getOperand(0)))
15204       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15205
15206     // Check LHS for X-1
15207     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15208         isAllOnes(N0.getOperand(1)))
15209       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15210
15211     // Check RHS for X-1
15212     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15213         isAllOnes(N1.getOperand(1)))
15214       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15215
15216     return SDValue();
15217   }
15218
15219   // Want to form ANDNP nodes:
15220   // 1) In the hopes of then easily combining them with OR and AND nodes
15221   //    to form PBLEND/PSIGN.
15222   // 2) To match ANDN packed intrinsics
15223   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15224     return SDValue();
15225
15226   SDValue N0 = N->getOperand(0);
15227   SDValue N1 = N->getOperand(1);
15228   DebugLoc DL = N->getDebugLoc();
15229
15230   // Check LHS for vnot
15231   if (N0.getOpcode() == ISD::XOR &&
15232       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15233       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15234     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15235
15236   // Check RHS for vnot
15237   if (N1.getOpcode() == ISD::XOR &&
15238       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15239       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15240     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15241
15242   return SDValue();
15243 }
15244
15245 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15246                                 TargetLowering::DAGCombinerInfo &DCI,
15247                                 const X86Subtarget *Subtarget) {
15248   if (DCI.isBeforeLegalizeOps())
15249     return SDValue();
15250
15251   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15252   if (R.getNode())
15253     return R;
15254
15255   EVT VT = N->getValueType(0);
15256
15257   SDValue N0 = N->getOperand(0);
15258   SDValue N1 = N->getOperand(1);
15259
15260   // look for psign/blend
15261   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15262     if (!Subtarget->hasSSSE3() ||
15263         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15264       return SDValue();
15265
15266     // Canonicalize pandn to RHS
15267     if (N0.getOpcode() == X86ISD::ANDNP)
15268       std::swap(N0, N1);
15269     // or (and (m, y), (pandn m, x))
15270     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15271       SDValue Mask = N1.getOperand(0);
15272       SDValue X    = N1.getOperand(1);
15273       SDValue Y;
15274       if (N0.getOperand(0) == Mask)
15275         Y = N0.getOperand(1);
15276       if (N0.getOperand(1) == Mask)
15277         Y = N0.getOperand(0);
15278
15279       // Check to see if the mask appeared in both the AND and ANDNP and
15280       if (!Y.getNode())
15281         return SDValue();
15282
15283       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15284       // Look through mask bitcast.
15285       if (Mask.getOpcode() == ISD::BITCAST)
15286         Mask = Mask.getOperand(0);
15287       if (X.getOpcode() == ISD::BITCAST)
15288         X = X.getOperand(0);
15289       if (Y.getOpcode() == ISD::BITCAST)
15290         Y = Y.getOperand(0);
15291
15292       EVT MaskVT = Mask.getValueType();
15293
15294       // Validate that the Mask operand is a vector sra node.
15295       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15296       // there is no psrai.b
15297       if (Mask.getOpcode() != X86ISD::VSRAI)
15298         return SDValue();
15299
15300       // Check that the SRA is all signbits.
15301       SDValue SraC = Mask.getOperand(1);
15302       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15303       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15304       if ((SraAmt + 1) != EltBits)
15305         return SDValue();
15306
15307       DebugLoc DL = N->getDebugLoc();
15308
15309       // Now we know we at least have a plendvb with the mask val.  See if
15310       // we can form a psignb/w/d.
15311       // psign = x.type == y.type == mask.type && y = sub(0, x);
15312       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15313           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15314           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15315         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15316                "Unsupported VT for PSIGN");
15317         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15318         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15319       }
15320       // PBLENDVB only available on SSE 4.1
15321       if (!Subtarget->hasSSE41())
15322         return SDValue();
15323
15324       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15325
15326       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15327       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15328       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15329       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15330       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15331     }
15332   }
15333
15334   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15335     return SDValue();
15336
15337   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15338   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15339     std::swap(N0, N1);
15340   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15341     return SDValue();
15342   if (!N0.hasOneUse() || !N1.hasOneUse())
15343     return SDValue();
15344
15345   SDValue ShAmt0 = N0.getOperand(1);
15346   if (ShAmt0.getValueType() != MVT::i8)
15347     return SDValue();
15348   SDValue ShAmt1 = N1.getOperand(1);
15349   if (ShAmt1.getValueType() != MVT::i8)
15350     return SDValue();
15351   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15352     ShAmt0 = ShAmt0.getOperand(0);
15353   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15354     ShAmt1 = ShAmt1.getOperand(0);
15355
15356   DebugLoc DL = N->getDebugLoc();
15357   unsigned Opc = X86ISD::SHLD;
15358   SDValue Op0 = N0.getOperand(0);
15359   SDValue Op1 = N1.getOperand(0);
15360   if (ShAmt0.getOpcode() == ISD::SUB) {
15361     Opc = X86ISD::SHRD;
15362     std::swap(Op0, Op1);
15363     std::swap(ShAmt0, ShAmt1);
15364   }
15365
15366   unsigned Bits = VT.getSizeInBits();
15367   if (ShAmt1.getOpcode() == ISD::SUB) {
15368     SDValue Sum = ShAmt1.getOperand(0);
15369     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15370       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15371       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15372         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15373       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15374         return DAG.getNode(Opc, DL, VT,
15375                            Op0, Op1,
15376                            DAG.getNode(ISD::TRUNCATE, DL,
15377                                        MVT::i8, ShAmt0));
15378     }
15379   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15380     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15381     if (ShAmt0C &&
15382         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15383       return DAG.getNode(Opc, DL, VT,
15384                          N0.getOperand(0), N1.getOperand(0),
15385                          DAG.getNode(ISD::TRUNCATE, DL,
15386                                        MVT::i8, ShAmt0));
15387   }
15388
15389   return SDValue();
15390 }
15391
15392 // Generate NEG and CMOV for integer abs.
15393 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15394   EVT VT = N->getValueType(0);
15395
15396   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15397   // 8-bit integer abs to NEG and CMOV.
15398   if (VT.isInteger() && VT.getSizeInBits() == 8)
15399     return SDValue();
15400
15401   SDValue N0 = N->getOperand(0);
15402   SDValue N1 = N->getOperand(1);
15403   DebugLoc DL = N->getDebugLoc();
15404
15405   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15406   // and change it to SUB and CMOV.
15407   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15408       N0.getOpcode() == ISD::ADD &&
15409       N0.getOperand(1) == N1 &&
15410       N1.getOpcode() == ISD::SRA &&
15411       N1.getOperand(0) == N0.getOperand(0))
15412     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15413       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15414         // Generate SUB & CMOV.
15415         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15416                                   DAG.getConstant(0, VT), N0.getOperand(0));
15417
15418         SDValue Ops[] = { N0.getOperand(0), Neg,
15419                           DAG.getConstant(X86::COND_GE, MVT::i8),
15420                           SDValue(Neg.getNode(), 1) };
15421         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15422                            Ops, array_lengthof(Ops));
15423       }
15424   return SDValue();
15425 }
15426
15427 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15428 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15429                                  TargetLowering::DAGCombinerInfo &DCI,
15430                                  const X86Subtarget *Subtarget) {
15431   if (DCI.isBeforeLegalizeOps())
15432     return SDValue();
15433
15434   if (Subtarget->hasCMov()) {
15435     SDValue RV = performIntegerAbsCombine(N, DAG);
15436     if (RV.getNode())
15437       return RV;
15438   }
15439
15440   // Try forming BMI if it is available.
15441   if (!Subtarget->hasBMI())
15442     return SDValue();
15443
15444   EVT VT = N->getValueType(0);
15445
15446   if (VT != MVT::i32 && VT != MVT::i64)
15447     return SDValue();
15448
15449   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15450
15451   // Create BLSMSK instructions by finding X ^ (X-1)
15452   SDValue N0 = N->getOperand(0);
15453   SDValue N1 = N->getOperand(1);
15454   DebugLoc DL = N->getDebugLoc();
15455
15456   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15457       isAllOnes(N0.getOperand(1)))
15458     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15459
15460   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15461       isAllOnes(N1.getOperand(1)))
15462     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15463
15464   return SDValue();
15465 }
15466
15467 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15468 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15469                                   TargetLowering::DAGCombinerInfo &DCI,
15470                                   const X86Subtarget *Subtarget) {
15471   LoadSDNode *Ld = cast<LoadSDNode>(N);
15472   EVT RegVT = Ld->getValueType(0);
15473   EVT MemVT = Ld->getMemoryVT();
15474   DebugLoc dl = Ld->getDebugLoc();
15475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15476
15477   ISD::LoadExtType Ext = Ld->getExtensionType();
15478
15479   // If this is a vector EXT Load then attempt to optimize it using a
15480   // shuffle. We need SSSE3 shuffles.
15481   // TODO: It is possible to support ZExt by zeroing the undef values
15482   // during the shuffle phase or after the shuffle.
15483   if (RegVT.isVector() && RegVT.isInteger() &&
15484       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15485     assert(MemVT != RegVT && "Cannot extend to the same type");
15486     assert(MemVT.isVector() && "Must load a vector from memory");
15487
15488     unsigned NumElems = RegVT.getVectorNumElements();
15489     unsigned RegSz = RegVT.getSizeInBits();
15490     unsigned MemSz = MemVT.getSizeInBits();
15491     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15492
15493     // All sizes must be a power of two.
15494     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15495       return SDValue();
15496
15497     // Attempt to load the original value using scalar loads.
15498     // Find the largest scalar type that divides the total loaded size.
15499     MVT SclrLoadTy = MVT::i8;
15500     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15501          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15502       MVT Tp = (MVT::SimpleValueType)tp;
15503       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15504         SclrLoadTy = Tp;
15505       }
15506     }
15507
15508     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15509     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15510         (64 <= MemSz))
15511       SclrLoadTy = MVT::f64;
15512
15513     // Calculate the number of scalar loads that we need to perform
15514     // in order to load our vector from memory.
15515     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15516
15517     // Represent our vector as a sequence of elements which are the
15518     // largest scalar that we can load.
15519     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15520       RegSz/SclrLoadTy.getSizeInBits());
15521
15522     // Represent the data using the same element type that is stored in
15523     // memory. In practice, we ''widen'' MemVT.
15524     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15525                                   RegSz/MemVT.getScalarType().getSizeInBits());
15526
15527     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15528       "Invalid vector type");
15529
15530     // We can't shuffle using an illegal type.
15531     if (!TLI.isTypeLegal(WideVecVT))
15532       return SDValue();
15533
15534     SmallVector<SDValue, 8> Chains;
15535     SDValue Ptr = Ld->getBasePtr();
15536     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15537                                         TLI.getPointerTy());
15538     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15539
15540     for (unsigned i = 0; i < NumLoads; ++i) {
15541       // Perform a single load.
15542       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15543                                        Ptr, Ld->getPointerInfo(),
15544                                        Ld->isVolatile(), Ld->isNonTemporal(),
15545                                        Ld->isInvariant(), Ld->getAlignment());
15546       Chains.push_back(ScalarLoad.getValue(1));
15547       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15548       // another round of DAGCombining.
15549       if (i == 0)
15550         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15551       else
15552         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15553                           ScalarLoad, DAG.getIntPtrConstant(i));
15554
15555       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15556     }
15557
15558     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15559                                Chains.size());
15560
15561     // Bitcast the loaded value to a vector of the original element type, in
15562     // the size of the target vector type.
15563     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15564     unsigned SizeRatio = RegSz/MemSz;
15565
15566     // Redistribute the loaded elements into the different locations.
15567     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15568     for (unsigned i = 0; i != NumElems; ++i)
15569       ShuffleVec[i*SizeRatio] = i;
15570
15571     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15572                                          DAG.getUNDEF(WideVecVT),
15573                                          &ShuffleVec[0]);
15574
15575     // Bitcast to the requested type.
15576     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15577     // Replace the original load with the new sequence
15578     // and return the new chain.
15579     return DCI.CombineTo(N, Shuff, TF, true);
15580   }
15581
15582   return SDValue();
15583 }
15584
15585 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15586 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15587                                    const X86Subtarget *Subtarget) {
15588   StoreSDNode *St = cast<StoreSDNode>(N);
15589   EVT VT = St->getValue().getValueType();
15590   EVT StVT = St->getMemoryVT();
15591   DebugLoc dl = St->getDebugLoc();
15592   SDValue StoredVal = St->getOperand(1);
15593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15594
15595   // If we are saving a concatenation of two XMM registers, perform two stores.
15596   // On Sandy Bridge, 256-bit memory operations are executed by two
15597   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15598   // memory  operation.
15599   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15600       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15601       StoredVal.getNumOperands() == 2) {
15602     SDValue Value0 = StoredVal.getOperand(0);
15603     SDValue Value1 = StoredVal.getOperand(1);
15604
15605     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15606     SDValue Ptr0 = St->getBasePtr();
15607     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15608
15609     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15610                                 St->getPointerInfo(), St->isVolatile(),
15611                                 St->isNonTemporal(), St->getAlignment());
15612     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15613                                 St->getPointerInfo(), St->isVolatile(),
15614                                 St->isNonTemporal(), St->getAlignment());
15615     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15616   }
15617
15618   // Optimize trunc store (of multiple scalars) to shuffle and store.
15619   // First, pack all of the elements in one place. Next, store to memory
15620   // in fewer chunks.
15621   if (St->isTruncatingStore() && VT.isVector()) {
15622     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15623     unsigned NumElems = VT.getVectorNumElements();
15624     assert(StVT != VT && "Cannot truncate to the same type");
15625     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15626     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15627
15628     // From, To sizes and ElemCount must be pow of two
15629     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15630     // We are going to use the original vector elt for storing.
15631     // Accumulated smaller vector elements must be a multiple of the store size.
15632     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15633
15634     unsigned SizeRatio  = FromSz / ToSz;
15635
15636     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15637
15638     // Create a type on which we perform the shuffle
15639     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15640             StVT.getScalarType(), NumElems*SizeRatio);
15641
15642     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15643
15644     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15645     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15646     for (unsigned i = 0; i != NumElems; ++i)
15647       ShuffleVec[i] = i * SizeRatio;
15648
15649     // Can't shuffle using an illegal type.
15650     if (!TLI.isTypeLegal(WideVecVT))
15651       return SDValue();
15652
15653     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15654                                          DAG.getUNDEF(WideVecVT),
15655                                          &ShuffleVec[0]);
15656     // At this point all of the data is stored at the bottom of the
15657     // register. We now need to save it to mem.
15658
15659     // Find the largest store unit
15660     MVT StoreType = MVT::i8;
15661     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15662          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15663       MVT Tp = (MVT::SimpleValueType)tp;
15664       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15665         StoreType = Tp;
15666     }
15667
15668     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15669     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15670         (64 <= NumElems * ToSz))
15671       StoreType = MVT::f64;
15672
15673     // Bitcast the original vector into a vector of store-size units
15674     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15675             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15676     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15677     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15678     SmallVector<SDValue, 8> Chains;
15679     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15680                                         TLI.getPointerTy());
15681     SDValue Ptr = St->getBasePtr();
15682
15683     // Perform one or more big stores into memory.
15684     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15685       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15686                                    StoreType, ShuffWide,
15687                                    DAG.getIntPtrConstant(i));
15688       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15689                                 St->getPointerInfo(), St->isVolatile(),
15690                                 St->isNonTemporal(), St->getAlignment());
15691       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15692       Chains.push_back(Ch);
15693     }
15694
15695     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15696                                Chains.size());
15697   }
15698
15699
15700   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15701   // the FP state in cases where an emms may be missing.
15702   // A preferable solution to the general problem is to figure out the right
15703   // places to insert EMMS.  This qualifies as a quick hack.
15704
15705   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15706   if (VT.getSizeInBits() != 64)
15707     return SDValue();
15708
15709   const Function *F = DAG.getMachineFunction().getFunction();
15710   bool NoImplicitFloatOps = F->getFnAttributes().
15711     hasAttribute(Attributes::NoImplicitFloat);
15712   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15713                      && Subtarget->hasSSE2();
15714   if ((VT.isVector() ||
15715        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15716       isa<LoadSDNode>(St->getValue()) &&
15717       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15718       St->getChain().hasOneUse() && !St->isVolatile()) {
15719     SDNode* LdVal = St->getValue().getNode();
15720     LoadSDNode *Ld = 0;
15721     int TokenFactorIndex = -1;
15722     SmallVector<SDValue, 8> Ops;
15723     SDNode* ChainVal = St->getChain().getNode();
15724     // Must be a store of a load.  We currently handle two cases:  the load
15725     // is a direct child, and it's under an intervening TokenFactor.  It is
15726     // possible to dig deeper under nested TokenFactors.
15727     if (ChainVal == LdVal)
15728       Ld = cast<LoadSDNode>(St->getChain());
15729     else if (St->getValue().hasOneUse() &&
15730              ChainVal->getOpcode() == ISD::TokenFactor) {
15731       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15732         if (ChainVal->getOperand(i).getNode() == LdVal) {
15733           TokenFactorIndex = i;
15734           Ld = cast<LoadSDNode>(St->getValue());
15735         } else
15736           Ops.push_back(ChainVal->getOperand(i));
15737       }
15738     }
15739
15740     if (!Ld || !ISD::isNormalLoad(Ld))
15741       return SDValue();
15742
15743     // If this is not the MMX case, i.e. we are just turning i64 load/store
15744     // into f64 load/store, avoid the transformation if there are multiple
15745     // uses of the loaded value.
15746     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15747       return SDValue();
15748
15749     DebugLoc LdDL = Ld->getDebugLoc();
15750     DebugLoc StDL = N->getDebugLoc();
15751     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15752     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15753     // pair instead.
15754     if (Subtarget->is64Bit() || F64IsLegal) {
15755       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15756       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15757                                   Ld->getPointerInfo(), Ld->isVolatile(),
15758                                   Ld->isNonTemporal(), Ld->isInvariant(),
15759                                   Ld->getAlignment());
15760       SDValue NewChain = NewLd.getValue(1);
15761       if (TokenFactorIndex != -1) {
15762         Ops.push_back(NewChain);
15763         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15764                                Ops.size());
15765       }
15766       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15767                           St->getPointerInfo(),
15768                           St->isVolatile(), St->isNonTemporal(),
15769                           St->getAlignment());
15770     }
15771
15772     // Otherwise, lower to two pairs of 32-bit loads / stores.
15773     SDValue LoAddr = Ld->getBasePtr();
15774     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15775                                  DAG.getConstant(4, MVT::i32));
15776
15777     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15778                                Ld->getPointerInfo(),
15779                                Ld->isVolatile(), Ld->isNonTemporal(),
15780                                Ld->isInvariant(), Ld->getAlignment());
15781     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15782                                Ld->getPointerInfo().getWithOffset(4),
15783                                Ld->isVolatile(), Ld->isNonTemporal(),
15784                                Ld->isInvariant(),
15785                                MinAlign(Ld->getAlignment(), 4));
15786
15787     SDValue NewChain = LoLd.getValue(1);
15788     if (TokenFactorIndex != -1) {
15789       Ops.push_back(LoLd);
15790       Ops.push_back(HiLd);
15791       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15792                              Ops.size());
15793     }
15794
15795     LoAddr = St->getBasePtr();
15796     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15797                          DAG.getConstant(4, MVT::i32));
15798
15799     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15800                                 St->getPointerInfo(),
15801                                 St->isVolatile(), St->isNonTemporal(),
15802                                 St->getAlignment());
15803     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15804                                 St->getPointerInfo().getWithOffset(4),
15805                                 St->isVolatile(),
15806                                 St->isNonTemporal(),
15807                                 MinAlign(St->getAlignment(), 4));
15808     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15809   }
15810   return SDValue();
15811 }
15812
15813 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15814 /// and return the operands for the horizontal operation in LHS and RHS.  A
15815 /// horizontal operation performs the binary operation on successive elements
15816 /// of its first operand, then on successive elements of its second operand,
15817 /// returning the resulting values in a vector.  For example, if
15818 ///   A = < float a0, float a1, float a2, float a3 >
15819 /// and
15820 ///   B = < float b0, float b1, float b2, float b3 >
15821 /// then the result of doing a horizontal operation on A and B is
15822 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15823 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15824 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15825 /// set to A, RHS to B, and the routine returns 'true'.
15826 /// Note that the binary operation should have the property that if one of the
15827 /// operands is UNDEF then the result is UNDEF.
15828 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15829   // Look for the following pattern: if
15830   //   A = < float a0, float a1, float a2, float a3 >
15831   //   B = < float b0, float b1, float b2, float b3 >
15832   // and
15833   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15834   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15835   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15836   // which is A horizontal-op B.
15837
15838   // At least one of the operands should be a vector shuffle.
15839   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15840       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15841     return false;
15842
15843   EVT VT = LHS.getValueType();
15844
15845   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15846          "Unsupported vector type for horizontal add/sub");
15847
15848   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15849   // operate independently on 128-bit lanes.
15850   unsigned NumElts = VT.getVectorNumElements();
15851   unsigned NumLanes = VT.getSizeInBits()/128;
15852   unsigned NumLaneElts = NumElts / NumLanes;
15853   assert((NumLaneElts % 2 == 0) &&
15854          "Vector type should have an even number of elements in each lane");
15855   unsigned HalfLaneElts = NumLaneElts/2;
15856
15857   // View LHS in the form
15858   //   LHS = VECTOR_SHUFFLE A, B, LMask
15859   // If LHS is not a shuffle then pretend it is the shuffle
15860   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15861   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15862   // type VT.
15863   SDValue A, B;
15864   SmallVector<int, 16> LMask(NumElts);
15865   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15866     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15867       A = LHS.getOperand(0);
15868     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15869       B = LHS.getOperand(1);
15870     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15871     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15872   } else {
15873     if (LHS.getOpcode() != ISD::UNDEF)
15874       A = LHS;
15875     for (unsigned i = 0; i != NumElts; ++i)
15876       LMask[i] = i;
15877   }
15878
15879   // Likewise, view RHS in the form
15880   //   RHS = VECTOR_SHUFFLE C, D, RMask
15881   SDValue C, D;
15882   SmallVector<int, 16> RMask(NumElts);
15883   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15884     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15885       C = RHS.getOperand(0);
15886     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15887       D = RHS.getOperand(1);
15888     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15889     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15890   } else {
15891     if (RHS.getOpcode() != ISD::UNDEF)
15892       C = RHS;
15893     for (unsigned i = 0; i != NumElts; ++i)
15894       RMask[i] = i;
15895   }
15896
15897   // Check that the shuffles are both shuffling the same vectors.
15898   if (!(A == C && B == D) && !(A == D && B == C))
15899     return false;
15900
15901   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15902   if (!A.getNode() && !B.getNode())
15903     return false;
15904
15905   // If A and B occur in reverse order in RHS, then "swap" them (which means
15906   // rewriting the mask).
15907   if (A != C)
15908     CommuteVectorShuffleMask(RMask, NumElts);
15909
15910   // At this point LHS and RHS are equivalent to
15911   //   LHS = VECTOR_SHUFFLE A, B, LMask
15912   //   RHS = VECTOR_SHUFFLE A, B, RMask
15913   // Check that the masks correspond to performing a horizontal operation.
15914   for (unsigned i = 0; i != NumElts; ++i) {
15915     int LIdx = LMask[i], RIdx = RMask[i];
15916
15917     // Ignore any UNDEF components.
15918     if (LIdx < 0 || RIdx < 0 ||
15919         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15920         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15921       continue;
15922
15923     // Check that successive elements are being operated on.  If not, this is
15924     // not a horizontal operation.
15925     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15926     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15927     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15928     if (!(LIdx == Index && RIdx == Index + 1) &&
15929         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15930       return false;
15931   }
15932
15933   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15934   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15935   return true;
15936 }
15937
15938 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15939 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15940                                   const X86Subtarget *Subtarget) {
15941   EVT VT = N->getValueType(0);
15942   SDValue LHS = N->getOperand(0);
15943   SDValue RHS = N->getOperand(1);
15944
15945   // Try to synthesize horizontal adds from adds of shuffles.
15946   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15947        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15948       isHorizontalBinOp(LHS, RHS, true))
15949     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15950   return SDValue();
15951 }
15952
15953 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15954 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15955                                   const X86Subtarget *Subtarget) {
15956   EVT VT = N->getValueType(0);
15957   SDValue LHS = N->getOperand(0);
15958   SDValue RHS = N->getOperand(1);
15959
15960   // Try to synthesize horizontal subs from subs of shuffles.
15961   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15962        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15963       isHorizontalBinOp(LHS, RHS, false))
15964     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15965   return SDValue();
15966 }
15967
15968 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15969 /// X86ISD::FXOR nodes.
15970 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15971   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15972   // F[X]OR(0.0, x) -> x
15973   // F[X]OR(x, 0.0) -> x
15974   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15975     if (C->getValueAPF().isPosZero())
15976       return N->getOperand(1);
15977   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15978     if (C->getValueAPF().isPosZero())
15979       return N->getOperand(0);
15980   return SDValue();
15981 }
15982
15983 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15984 /// X86ISD::FMAX nodes.
15985 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15986   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15987
15988   // Only perform optimizations if UnsafeMath is used.
15989   if (!DAG.getTarget().Options.UnsafeFPMath)
15990     return SDValue();
15991
15992   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15993   // into FMINC and FMAXC, which are Commutative operations.
15994   unsigned NewOp = 0;
15995   switch (N->getOpcode()) {
15996     default: llvm_unreachable("unknown opcode");
15997     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15998     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15999   }
16000
16001   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16002                      N->getOperand(0), N->getOperand(1));
16003 }
16004
16005
16006 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16007 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16008   // FAND(0.0, x) -> 0.0
16009   // FAND(x, 0.0) -> 0.0
16010   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16011     if (C->getValueAPF().isPosZero())
16012       return N->getOperand(0);
16013   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16014     if (C->getValueAPF().isPosZero())
16015       return N->getOperand(1);
16016   return SDValue();
16017 }
16018
16019 static SDValue PerformBTCombine(SDNode *N,
16020                                 SelectionDAG &DAG,
16021                                 TargetLowering::DAGCombinerInfo &DCI) {
16022   // BT ignores high bits in the bit index operand.
16023   SDValue Op1 = N->getOperand(1);
16024   if (Op1.hasOneUse()) {
16025     unsigned BitWidth = Op1.getValueSizeInBits();
16026     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16027     APInt KnownZero, KnownOne;
16028     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16029                                           !DCI.isBeforeLegalizeOps());
16030     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16031     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16032         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16033       DCI.CommitTargetLoweringOpt(TLO);
16034   }
16035   return SDValue();
16036 }
16037
16038 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16039   SDValue Op = N->getOperand(0);
16040   if (Op.getOpcode() == ISD::BITCAST)
16041     Op = Op.getOperand(0);
16042   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16043   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16044       VT.getVectorElementType().getSizeInBits() ==
16045       OpVT.getVectorElementType().getSizeInBits()) {
16046     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16047   }
16048   return SDValue();
16049 }
16050
16051 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16052                                   TargetLowering::DAGCombinerInfo &DCI,
16053                                   const X86Subtarget *Subtarget) {
16054   if (!DCI.isBeforeLegalizeOps())
16055     return SDValue();
16056
16057   if (!Subtarget->hasAVX())
16058     return SDValue();
16059
16060   EVT VT = N->getValueType(0);
16061   SDValue Op = N->getOperand(0);
16062   EVT OpVT = Op.getValueType();
16063   DebugLoc dl = N->getDebugLoc();
16064
16065   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16066       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16067
16068     if (Subtarget->hasAVX2())
16069       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16070
16071     // Optimize vectors in AVX mode
16072     // Sign extend  v8i16 to v8i32 and
16073     //              v4i32 to v4i64
16074     //
16075     // Divide input vector into two parts
16076     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16077     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16078     // concat the vectors to original VT
16079
16080     unsigned NumElems = OpVT.getVectorNumElements();
16081     SDValue Undef = DAG.getUNDEF(OpVT);
16082
16083     SmallVector<int,8> ShufMask1(NumElems, -1);
16084     for (unsigned i = 0; i != NumElems/2; ++i)
16085       ShufMask1[i] = i;
16086
16087     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16088
16089     SmallVector<int,8> ShufMask2(NumElems, -1);
16090     for (unsigned i = 0; i != NumElems/2; ++i)
16091       ShufMask2[i] = i + NumElems/2;
16092
16093     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16094
16095     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16096                                   VT.getVectorNumElements()/2);
16097
16098     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16099     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16100
16101     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16102   }
16103   return SDValue();
16104 }
16105
16106 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16107                                  const X86Subtarget* Subtarget) {
16108   DebugLoc dl = N->getDebugLoc();
16109   EVT VT = N->getValueType(0);
16110
16111   // Let legalize expand this if it isn't a legal type yet.
16112   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16113     return SDValue();
16114
16115   EVT ScalarVT = VT.getScalarType();
16116   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16117       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16118     return SDValue();
16119
16120   SDValue A = N->getOperand(0);
16121   SDValue B = N->getOperand(1);
16122   SDValue C = N->getOperand(2);
16123
16124   bool NegA = (A.getOpcode() == ISD::FNEG);
16125   bool NegB = (B.getOpcode() == ISD::FNEG);
16126   bool NegC = (C.getOpcode() == ISD::FNEG);
16127
16128   // Negative multiplication when NegA xor NegB
16129   bool NegMul = (NegA != NegB);
16130   if (NegA)
16131     A = A.getOperand(0);
16132   if (NegB)
16133     B = B.getOperand(0);
16134   if (NegC)
16135     C = C.getOperand(0);
16136
16137   unsigned Opcode;
16138   if (!NegMul)
16139     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16140   else
16141     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16142
16143   return DAG.getNode(Opcode, dl, VT, A, B, C);
16144 }
16145
16146 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16147                                   TargetLowering::DAGCombinerInfo &DCI,
16148                                   const X86Subtarget *Subtarget) {
16149   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16150   //           (and (i32 x86isd::setcc_carry), 1)
16151   // This eliminates the zext. This transformation is necessary because
16152   // ISD::SETCC is always legalized to i8.
16153   DebugLoc dl = N->getDebugLoc();
16154   SDValue N0 = N->getOperand(0);
16155   EVT VT = N->getValueType(0);
16156   EVT OpVT = N0.getValueType();
16157
16158   if (N0.getOpcode() == ISD::AND &&
16159       N0.hasOneUse() &&
16160       N0.getOperand(0).hasOneUse()) {
16161     SDValue N00 = N0.getOperand(0);
16162     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16163       return SDValue();
16164     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16165     if (!C || C->getZExtValue() != 1)
16166       return SDValue();
16167     return DAG.getNode(ISD::AND, dl, VT,
16168                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16169                                    N00.getOperand(0), N00.getOperand(1)),
16170                        DAG.getConstant(1, VT));
16171   }
16172
16173   // Optimize vectors in AVX mode:
16174   //
16175   //   v8i16 -> v8i32
16176   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16177   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16178   //   Concat upper and lower parts.
16179   //
16180   //   v4i32 -> v4i64
16181   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16182   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16183   //   Concat upper and lower parts.
16184   //
16185   if (!DCI.isBeforeLegalizeOps())
16186     return SDValue();
16187
16188   if (!Subtarget->hasAVX())
16189     return SDValue();
16190
16191   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16192       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16193
16194     if (Subtarget->hasAVX2())
16195       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16196
16197     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16198     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16199     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16200
16201     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16202                                VT.getVectorNumElements()/2);
16203
16204     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16205     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16206
16207     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16208   }
16209
16210   return SDValue();
16211 }
16212
16213 // Optimize x == -y --> x+y == 0
16214 //          x != -y --> x+y != 0
16215 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16216   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16217   SDValue LHS = N->getOperand(0);
16218   SDValue RHS = N->getOperand(1);
16219
16220   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16221     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16222       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16223         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16224                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16225         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16226                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16227       }
16228   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16229     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16230       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16231         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16232                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16233         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16234                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16235       }
16236   return SDValue();
16237 }
16238
16239 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16240 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16241                                    TargetLowering::DAGCombinerInfo &DCI,
16242                                    const X86Subtarget *Subtarget) {
16243   DebugLoc DL = N->getDebugLoc();
16244   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16245   SDValue EFLAGS = N->getOperand(1);
16246
16247   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16248   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16249   // cases.
16250   if (CC == X86::COND_B)
16251     return DAG.getNode(ISD::AND, DL, MVT::i8,
16252                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16253                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16254                        DAG.getConstant(1, MVT::i8));
16255
16256   SDValue Flags;
16257
16258   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16259   if (Flags.getNode()) {
16260     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16261     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16262   }
16263
16264   return SDValue();
16265 }
16266
16267 // Optimize branch condition evaluation.
16268 //
16269 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16270                                     TargetLowering::DAGCombinerInfo &DCI,
16271                                     const X86Subtarget *Subtarget) {
16272   DebugLoc DL = N->getDebugLoc();
16273   SDValue Chain = N->getOperand(0);
16274   SDValue Dest = N->getOperand(1);
16275   SDValue EFLAGS = N->getOperand(3);
16276   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16277
16278   SDValue Flags;
16279
16280   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16281   if (Flags.getNode()) {
16282     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16283     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16284                        Flags);
16285   }
16286
16287   return SDValue();
16288 }
16289
16290 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16291   SDValue Op0 = N->getOperand(0);
16292   EVT InVT = Op0->getValueType(0);
16293
16294   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16295   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16296     DebugLoc dl = N->getDebugLoc();
16297     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16298     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16299     // Notice that we use SINT_TO_FP because we know that the high bits
16300     // are zero and SINT_TO_FP is better supported by the hardware.
16301     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16302   }
16303
16304   return SDValue();
16305 }
16306
16307 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16308                                         const X86TargetLowering *XTLI) {
16309   SDValue Op0 = N->getOperand(0);
16310   EVT InVT = Op0->getValueType(0);
16311
16312   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16313   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16314     DebugLoc dl = N->getDebugLoc();
16315     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16316     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16317     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16318   }
16319
16320   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16321   // a 32-bit target where SSE doesn't support i64->FP operations.
16322   if (Op0.getOpcode() == ISD::LOAD) {
16323     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16324     EVT VT = Ld->getValueType(0);
16325     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16326         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16327         !XTLI->getSubtarget()->is64Bit() &&
16328         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16329       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16330                                           Ld->getChain(), Op0, DAG);
16331       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16332       return FILDChain;
16333     }
16334   }
16335   return SDValue();
16336 }
16337
16338 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16339 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16340                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16341   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16342   // the result is either zero or one (depending on the input carry bit).
16343   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16344   if (X86::isZeroNode(N->getOperand(0)) &&
16345       X86::isZeroNode(N->getOperand(1)) &&
16346       // We don't have a good way to replace an EFLAGS use, so only do this when
16347       // dead right now.
16348       SDValue(N, 1).use_empty()) {
16349     DebugLoc DL = N->getDebugLoc();
16350     EVT VT = N->getValueType(0);
16351     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16352     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16353                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16354                                            DAG.getConstant(X86::COND_B,MVT::i8),
16355                                            N->getOperand(2)),
16356                                DAG.getConstant(1, VT));
16357     return DCI.CombineTo(N, Res1, CarryOut);
16358   }
16359
16360   return SDValue();
16361 }
16362
16363 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16364 //      (add Y, (setne X, 0)) -> sbb -1, Y
16365 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16366 //      (sub (setne X, 0), Y) -> adc -1, Y
16367 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16368   DebugLoc DL = N->getDebugLoc();
16369
16370   // Look through ZExts.
16371   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16372   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16373     return SDValue();
16374
16375   SDValue SetCC = Ext.getOperand(0);
16376   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16377     return SDValue();
16378
16379   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16380   if (CC != X86::COND_E && CC != X86::COND_NE)
16381     return SDValue();
16382
16383   SDValue Cmp = SetCC.getOperand(1);
16384   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16385       !X86::isZeroNode(Cmp.getOperand(1)) ||
16386       !Cmp.getOperand(0).getValueType().isInteger())
16387     return SDValue();
16388
16389   SDValue CmpOp0 = Cmp.getOperand(0);
16390   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16391                                DAG.getConstant(1, CmpOp0.getValueType()));
16392
16393   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16394   if (CC == X86::COND_NE)
16395     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16396                        DL, OtherVal.getValueType(), OtherVal,
16397                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16398   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16399                      DL, OtherVal.getValueType(), OtherVal,
16400                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16401 }
16402
16403 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16404 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16405                                  const X86Subtarget *Subtarget) {
16406   EVT VT = N->getValueType(0);
16407   SDValue Op0 = N->getOperand(0);
16408   SDValue Op1 = N->getOperand(1);
16409
16410   // Try to synthesize horizontal adds from adds of shuffles.
16411   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16412        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16413       isHorizontalBinOp(Op0, Op1, true))
16414     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16415
16416   return OptimizeConditionalInDecrement(N, DAG);
16417 }
16418
16419 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16420                                  const X86Subtarget *Subtarget) {
16421   SDValue Op0 = N->getOperand(0);
16422   SDValue Op1 = N->getOperand(1);
16423
16424   // X86 can't encode an immediate LHS of a sub. See if we can push the
16425   // negation into a preceding instruction.
16426   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16427     // If the RHS of the sub is a XOR with one use and a constant, invert the
16428     // immediate. Then add one to the LHS of the sub so we can turn
16429     // X-Y -> X+~Y+1, saving one register.
16430     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16431         isa<ConstantSDNode>(Op1.getOperand(1))) {
16432       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16433       EVT VT = Op0.getValueType();
16434       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16435                                    Op1.getOperand(0),
16436                                    DAG.getConstant(~XorC, VT));
16437       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16438                          DAG.getConstant(C->getAPIntValue()+1, VT));
16439     }
16440   }
16441
16442   // Try to synthesize horizontal adds from adds of shuffles.
16443   EVT VT = N->getValueType(0);
16444   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16445        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16446       isHorizontalBinOp(Op0, Op1, true))
16447     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16448
16449   return OptimizeConditionalInDecrement(N, DAG);
16450 }
16451
16452 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16453                                              DAGCombinerInfo &DCI) const {
16454   SelectionDAG &DAG = DCI.DAG;
16455   switch (N->getOpcode()) {
16456   default: break;
16457   case ISD::EXTRACT_VECTOR_ELT:
16458     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16459   case ISD::VSELECT:
16460   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16461   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16462   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16463   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16464   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16465   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16466   case ISD::SHL:
16467   case ISD::SRA:
16468   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16469   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16470   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16471   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16472   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16473   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16474   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16475   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16476   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16477   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16478   case X86ISD::FXOR:
16479   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16480   case X86ISD::FMIN:
16481   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16482   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16483   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16484   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16485   case ISD::ANY_EXTEND:
16486   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16487   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16488   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16489   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16490   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16491   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16492   case X86ISD::SHUFP:       // Handle all target specific shuffles
16493   case X86ISD::PALIGN:
16494   case X86ISD::UNPCKH:
16495   case X86ISD::UNPCKL:
16496   case X86ISD::MOVHLPS:
16497   case X86ISD::MOVLHPS:
16498   case X86ISD::PSHUFD:
16499   case X86ISD::PSHUFHW:
16500   case X86ISD::PSHUFLW:
16501   case X86ISD::MOVSS:
16502   case X86ISD::MOVSD:
16503   case X86ISD::VPERMILP:
16504   case X86ISD::VPERM2X128:
16505   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16506   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16507   }
16508
16509   return SDValue();
16510 }
16511
16512 /// isTypeDesirableForOp - Return true if the target has native support for
16513 /// the specified value type and it is 'desirable' to use the type for the
16514 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16515 /// instruction encodings are longer and some i16 instructions are slow.
16516 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16517   if (!isTypeLegal(VT))
16518     return false;
16519   if (VT != MVT::i16)
16520     return true;
16521
16522   switch (Opc) {
16523   default:
16524     return true;
16525   case ISD::LOAD:
16526   case ISD::SIGN_EXTEND:
16527   case ISD::ZERO_EXTEND:
16528   case ISD::ANY_EXTEND:
16529   case ISD::SHL:
16530   case ISD::SRL:
16531   case ISD::SUB:
16532   case ISD::ADD:
16533   case ISD::MUL:
16534   case ISD::AND:
16535   case ISD::OR:
16536   case ISD::XOR:
16537     return false;
16538   }
16539 }
16540
16541 /// IsDesirableToPromoteOp - This method query the target whether it is
16542 /// beneficial for dag combiner to promote the specified node. If true, it
16543 /// should return the desired promotion type by reference.
16544 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16545   EVT VT = Op.getValueType();
16546   if (VT != MVT::i16)
16547     return false;
16548
16549   bool Promote = false;
16550   bool Commute = false;
16551   switch (Op.getOpcode()) {
16552   default: break;
16553   case ISD::LOAD: {
16554     LoadSDNode *LD = cast<LoadSDNode>(Op);
16555     // If the non-extending load has a single use and it's not live out, then it
16556     // might be folded.
16557     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16558                                                      Op.hasOneUse()*/) {
16559       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16560              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16561         // The only case where we'd want to promote LOAD (rather then it being
16562         // promoted as an operand is when it's only use is liveout.
16563         if (UI->getOpcode() != ISD::CopyToReg)
16564           return false;
16565       }
16566     }
16567     Promote = true;
16568     break;
16569   }
16570   case ISD::SIGN_EXTEND:
16571   case ISD::ZERO_EXTEND:
16572   case ISD::ANY_EXTEND:
16573     Promote = true;
16574     break;
16575   case ISD::SHL:
16576   case ISD::SRL: {
16577     SDValue N0 = Op.getOperand(0);
16578     // Look out for (store (shl (load), x)).
16579     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16580       return false;
16581     Promote = true;
16582     break;
16583   }
16584   case ISD::ADD:
16585   case ISD::MUL:
16586   case ISD::AND:
16587   case ISD::OR:
16588   case ISD::XOR:
16589     Commute = true;
16590     // fallthrough
16591   case ISD::SUB: {
16592     SDValue N0 = Op.getOperand(0);
16593     SDValue N1 = Op.getOperand(1);
16594     if (!Commute && MayFoldLoad(N1))
16595       return false;
16596     // Avoid disabling potential load folding opportunities.
16597     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16598       return false;
16599     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16600       return false;
16601     Promote = true;
16602   }
16603   }
16604
16605   PVT = MVT::i32;
16606   return Promote;
16607 }
16608
16609 //===----------------------------------------------------------------------===//
16610 //                           X86 Inline Assembly Support
16611 //===----------------------------------------------------------------------===//
16612
16613 namespace {
16614   // Helper to match a string separated by whitespace.
16615   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16616     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16617
16618     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16619       StringRef piece(*args[i]);
16620       if (!s.startswith(piece)) // Check if the piece matches.
16621         return false;
16622
16623       s = s.substr(piece.size());
16624       StringRef::size_type pos = s.find_first_not_of(" \t");
16625       if (pos == 0) // We matched a prefix.
16626         return false;
16627
16628       s = s.substr(pos);
16629     }
16630
16631     return s.empty();
16632   }
16633   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16634 }
16635
16636 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16637   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16638
16639   std::string AsmStr = IA->getAsmString();
16640
16641   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16642   if (!Ty || Ty->getBitWidth() % 16 != 0)
16643     return false;
16644
16645   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16646   SmallVector<StringRef, 4> AsmPieces;
16647   SplitString(AsmStr, AsmPieces, ";\n");
16648
16649   switch (AsmPieces.size()) {
16650   default: return false;
16651   case 1:
16652     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16653     // we will turn this bswap into something that will be lowered to logical
16654     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16655     // lower so don't worry about this.
16656     // bswap $0
16657     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16658         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16659         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16660         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16661         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16662         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16663       // No need to check constraints, nothing other than the equivalent of
16664       // "=r,0" would be valid here.
16665       return IntrinsicLowering::LowerToByteSwap(CI);
16666     }
16667
16668     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16669     if (CI->getType()->isIntegerTy(16) &&
16670         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16671         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16672          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16673       AsmPieces.clear();
16674       const std::string &ConstraintsStr = IA->getConstraintString();
16675       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16676       std::sort(AsmPieces.begin(), AsmPieces.end());
16677       if (AsmPieces.size() == 4 &&
16678           AsmPieces[0] == "~{cc}" &&
16679           AsmPieces[1] == "~{dirflag}" &&
16680           AsmPieces[2] == "~{flags}" &&
16681           AsmPieces[3] == "~{fpsr}")
16682       return IntrinsicLowering::LowerToByteSwap(CI);
16683     }
16684     break;
16685   case 3:
16686     if (CI->getType()->isIntegerTy(32) &&
16687         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16688         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16689         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16690         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16691       AsmPieces.clear();
16692       const std::string &ConstraintsStr = IA->getConstraintString();
16693       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16694       std::sort(AsmPieces.begin(), AsmPieces.end());
16695       if (AsmPieces.size() == 4 &&
16696           AsmPieces[0] == "~{cc}" &&
16697           AsmPieces[1] == "~{dirflag}" &&
16698           AsmPieces[2] == "~{flags}" &&
16699           AsmPieces[3] == "~{fpsr}")
16700         return IntrinsicLowering::LowerToByteSwap(CI);
16701     }
16702
16703     if (CI->getType()->isIntegerTy(64)) {
16704       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16705       if (Constraints.size() >= 2 &&
16706           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16707           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16708         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16709         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16710             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16711             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16712           return IntrinsicLowering::LowerToByteSwap(CI);
16713       }
16714     }
16715     break;
16716   }
16717   return false;
16718 }
16719
16720
16721
16722 /// getConstraintType - Given a constraint letter, return the type of
16723 /// constraint it is for this target.
16724 X86TargetLowering::ConstraintType
16725 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16726   if (Constraint.size() == 1) {
16727     switch (Constraint[0]) {
16728     case 'R':
16729     case 'q':
16730     case 'Q':
16731     case 'f':
16732     case 't':
16733     case 'u':
16734     case 'y':
16735     case 'x':
16736     case 'Y':
16737     case 'l':
16738       return C_RegisterClass;
16739     case 'a':
16740     case 'b':
16741     case 'c':
16742     case 'd':
16743     case 'S':
16744     case 'D':
16745     case 'A':
16746       return C_Register;
16747     case 'I':
16748     case 'J':
16749     case 'K':
16750     case 'L':
16751     case 'M':
16752     case 'N':
16753     case 'G':
16754     case 'C':
16755     case 'e':
16756     case 'Z':
16757       return C_Other;
16758     default:
16759       break;
16760     }
16761   }
16762   return TargetLowering::getConstraintType(Constraint);
16763 }
16764
16765 /// Examine constraint type and operand type and determine a weight value.
16766 /// This object must already have been set up with the operand type
16767 /// and the current alternative constraint selected.
16768 TargetLowering::ConstraintWeight
16769   X86TargetLowering::getSingleConstraintMatchWeight(
16770     AsmOperandInfo &info, const char *constraint) const {
16771   ConstraintWeight weight = CW_Invalid;
16772   Value *CallOperandVal = info.CallOperandVal;
16773     // If we don't have a value, we can't do a match,
16774     // but allow it at the lowest weight.
16775   if (CallOperandVal == NULL)
16776     return CW_Default;
16777   Type *type = CallOperandVal->getType();
16778   // Look at the constraint type.
16779   switch (*constraint) {
16780   default:
16781     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16782   case 'R':
16783   case 'q':
16784   case 'Q':
16785   case 'a':
16786   case 'b':
16787   case 'c':
16788   case 'd':
16789   case 'S':
16790   case 'D':
16791   case 'A':
16792     if (CallOperandVal->getType()->isIntegerTy())
16793       weight = CW_SpecificReg;
16794     break;
16795   case 'f':
16796   case 't':
16797   case 'u':
16798       if (type->isFloatingPointTy())
16799         weight = CW_SpecificReg;
16800       break;
16801   case 'y':
16802       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16803         weight = CW_SpecificReg;
16804       break;
16805   case 'x':
16806   case 'Y':
16807     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16808         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16809       weight = CW_Register;
16810     break;
16811   case 'I':
16812     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16813       if (C->getZExtValue() <= 31)
16814         weight = CW_Constant;
16815     }
16816     break;
16817   case 'J':
16818     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16819       if (C->getZExtValue() <= 63)
16820         weight = CW_Constant;
16821     }
16822     break;
16823   case 'K':
16824     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16825       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16826         weight = CW_Constant;
16827     }
16828     break;
16829   case 'L':
16830     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16831       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16832         weight = CW_Constant;
16833     }
16834     break;
16835   case 'M':
16836     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16837       if (C->getZExtValue() <= 3)
16838         weight = CW_Constant;
16839     }
16840     break;
16841   case 'N':
16842     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16843       if (C->getZExtValue() <= 0xff)
16844         weight = CW_Constant;
16845     }
16846     break;
16847   case 'G':
16848   case 'C':
16849     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16850       weight = CW_Constant;
16851     }
16852     break;
16853   case 'e':
16854     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16855       if ((C->getSExtValue() >= -0x80000000LL) &&
16856           (C->getSExtValue() <= 0x7fffffffLL))
16857         weight = CW_Constant;
16858     }
16859     break;
16860   case 'Z':
16861     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16862       if (C->getZExtValue() <= 0xffffffff)
16863         weight = CW_Constant;
16864     }
16865     break;
16866   }
16867   return weight;
16868 }
16869
16870 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16871 /// with another that has more specific requirements based on the type of the
16872 /// corresponding operand.
16873 const char *X86TargetLowering::
16874 LowerXConstraint(EVT ConstraintVT) const {
16875   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16876   // 'f' like normal targets.
16877   if (ConstraintVT.isFloatingPoint()) {
16878     if (Subtarget->hasSSE2())
16879       return "Y";
16880     if (Subtarget->hasSSE1())
16881       return "x";
16882   }
16883
16884   return TargetLowering::LowerXConstraint(ConstraintVT);
16885 }
16886
16887 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16888 /// vector.  If it is invalid, don't add anything to Ops.
16889 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16890                                                      std::string &Constraint,
16891                                                      std::vector<SDValue>&Ops,
16892                                                      SelectionDAG &DAG) const {
16893   SDValue Result(0, 0);
16894
16895   // Only support length 1 constraints for now.
16896   if (Constraint.length() > 1) return;
16897
16898   char ConstraintLetter = Constraint[0];
16899   switch (ConstraintLetter) {
16900   default: break;
16901   case 'I':
16902     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16903       if (C->getZExtValue() <= 31) {
16904         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16905         break;
16906       }
16907     }
16908     return;
16909   case 'J':
16910     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16911       if (C->getZExtValue() <= 63) {
16912         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16913         break;
16914       }
16915     }
16916     return;
16917   case 'K':
16918     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16919       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16920         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16921         break;
16922       }
16923     }
16924     return;
16925   case 'N':
16926     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16927       if (C->getZExtValue() <= 255) {
16928         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16929         break;
16930       }
16931     }
16932     return;
16933   case 'e': {
16934     // 32-bit signed value
16935     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16936       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16937                                            C->getSExtValue())) {
16938         // Widen to 64 bits here to get it sign extended.
16939         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16940         break;
16941       }
16942     // FIXME gcc accepts some relocatable values here too, but only in certain
16943     // memory models; it's complicated.
16944     }
16945     return;
16946   }
16947   case 'Z': {
16948     // 32-bit unsigned value
16949     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16950       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16951                                            C->getZExtValue())) {
16952         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16953         break;
16954       }
16955     }
16956     // FIXME gcc accepts some relocatable values here too, but only in certain
16957     // memory models; it's complicated.
16958     return;
16959   }
16960   case 'i': {
16961     // Literal immediates are always ok.
16962     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16963       // Widen to 64 bits here to get it sign extended.
16964       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16965       break;
16966     }
16967
16968     // In any sort of PIC mode addresses need to be computed at runtime by
16969     // adding in a register or some sort of table lookup.  These can't
16970     // be used as immediates.
16971     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16972       return;
16973
16974     // If we are in non-pic codegen mode, we allow the address of a global (with
16975     // an optional displacement) to be used with 'i'.
16976     GlobalAddressSDNode *GA = 0;
16977     int64_t Offset = 0;
16978
16979     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16980     while (1) {
16981       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16982         Offset += GA->getOffset();
16983         break;
16984       } else if (Op.getOpcode() == ISD::ADD) {
16985         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16986           Offset += C->getZExtValue();
16987           Op = Op.getOperand(0);
16988           continue;
16989         }
16990       } else if (Op.getOpcode() == ISD::SUB) {
16991         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16992           Offset += -C->getZExtValue();
16993           Op = Op.getOperand(0);
16994           continue;
16995         }
16996       }
16997
16998       // Otherwise, this isn't something we can handle, reject it.
16999       return;
17000     }
17001
17002     const GlobalValue *GV = GA->getGlobal();
17003     // If we require an extra load to get this address, as in PIC mode, we
17004     // can't accept it.
17005     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17006                                                         getTargetMachine())))
17007       return;
17008
17009     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17010                                         GA->getValueType(0), Offset);
17011     break;
17012   }
17013   }
17014
17015   if (Result.getNode()) {
17016     Ops.push_back(Result);
17017     return;
17018   }
17019   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17020 }
17021
17022 std::pair<unsigned, const TargetRegisterClass*>
17023 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17024                                                 EVT VT) const {
17025   // First, see if this is a constraint that directly corresponds to an LLVM
17026   // register class.
17027   if (Constraint.size() == 1) {
17028     // GCC Constraint Letters
17029     switch (Constraint[0]) {
17030     default: break;
17031       // TODO: Slight differences here in allocation order and leaving
17032       // RIP in the class. Do they matter any more here than they do
17033       // in the normal allocation?
17034     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17035       if (Subtarget->is64Bit()) {
17036         if (VT == MVT::i32 || VT == MVT::f32)
17037           return std::make_pair(0U, &X86::GR32RegClass);
17038         if (VT == MVT::i16)
17039           return std::make_pair(0U, &X86::GR16RegClass);
17040         if (VT == MVT::i8 || VT == MVT::i1)
17041           return std::make_pair(0U, &X86::GR8RegClass);
17042         if (VT == MVT::i64 || VT == MVT::f64)
17043           return std::make_pair(0U, &X86::GR64RegClass);
17044         break;
17045       }
17046       // 32-bit fallthrough
17047     case 'Q':   // Q_REGS
17048       if (VT == MVT::i32 || VT == MVT::f32)
17049         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17050       if (VT == MVT::i16)
17051         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17052       if (VT == MVT::i8 || VT == MVT::i1)
17053         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17054       if (VT == MVT::i64)
17055         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17056       break;
17057     case 'r':   // GENERAL_REGS
17058     case 'l':   // INDEX_REGS
17059       if (VT == MVT::i8 || VT == MVT::i1)
17060         return std::make_pair(0U, &X86::GR8RegClass);
17061       if (VT == MVT::i16)
17062         return std::make_pair(0U, &X86::GR16RegClass);
17063       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17064         return std::make_pair(0U, &X86::GR32RegClass);
17065       return std::make_pair(0U, &X86::GR64RegClass);
17066     case 'R':   // LEGACY_REGS
17067       if (VT == MVT::i8 || VT == MVT::i1)
17068         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17069       if (VT == MVT::i16)
17070         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17071       if (VT == MVT::i32 || !Subtarget->is64Bit())
17072         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17073       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17074     case 'f':  // FP Stack registers.
17075       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17076       // value to the correct fpstack register class.
17077       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17078         return std::make_pair(0U, &X86::RFP32RegClass);
17079       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17080         return std::make_pair(0U, &X86::RFP64RegClass);
17081       return std::make_pair(0U, &X86::RFP80RegClass);
17082     case 'y':   // MMX_REGS if MMX allowed.
17083       if (!Subtarget->hasMMX()) break;
17084       return std::make_pair(0U, &X86::VR64RegClass);
17085     case 'Y':   // SSE_REGS if SSE2 allowed
17086       if (!Subtarget->hasSSE2()) break;
17087       // FALL THROUGH.
17088     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17089       if (!Subtarget->hasSSE1()) break;
17090
17091       switch (VT.getSimpleVT().SimpleTy) {
17092       default: break;
17093       // Scalar SSE types.
17094       case MVT::f32:
17095       case MVT::i32:
17096         return std::make_pair(0U, &X86::FR32RegClass);
17097       case MVT::f64:
17098       case MVT::i64:
17099         return std::make_pair(0U, &X86::FR64RegClass);
17100       // Vector types.
17101       case MVT::v16i8:
17102       case MVT::v8i16:
17103       case MVT::v4i32:
17104       case MVT::v2i64:
17105       case MVT::v4f32:
17106       case MVT::v2f64:
17107         return std::make_pair(0U, &X86::VR128RegClass);
17108       // AVX types.
17109       case MVT::v32i8:
17110       case MVT::v16i16:
17111       case MVT::v8i32:
17112       case MVT::v4i64:
17113       case MVT::v8f32:
17114       case MVT::v4f64:
17115         return std::make_pair(0U, &X86::VR256RegClass);
17116       }
17117       break;
17118     }
17119   }
17120
17121   // Use the default implementation in TargetLowering to convert the register
17122   // constraint into a member of a register class.
17123   std::pair<unsigned, const TargetRegisterClass*> Res;
17124   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17125
17126   // Not found as a standard register?
17127   if (Res.second == 0) {
17128     // Map st(0) -> st(7) -> ST0
17129     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17130         tolower(Constraint[1]) == 's' &&
17131         tolower(Constraint[2]) == 't' &&
17132         Constraint[3] == '(' &&
17133         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17134         Constraint[5] == ')' &&
17135         Constraint[6] == '}') {
17136
17137       Res.first = X86::ST0+Constraint[4]-'0';
17138       Res.second = &X86::RFP80RegClass;
17139       return Res;
17140     }
17141
17142     // GCC allows "st(0)" to be called just plain "st".
17143     if (StringRef("{st}").equals_lower(Constraint)) {
17144       Res.first = X86::ST0;
17145       Res.second = &X86::RFP80RegClass;
17146       return Res;
17147     }
17148
17149     // flags -> EFLAGS
17150     if (StringRef("{flags}").equals_lower(Constraint)) {
17151       Res.first = X86::EFLAGS;
17152       Res.second = &X86::CCRRegClass;
17153       return Res;
17154     }
17155
17156     // 'A' means EAX + EDX.
17157     if (Constraint == "A") {
17158       Res.first = X86::EAX;
17159       Res.second = &X86::GR32_ADRegClass;
17160       return Res;
17161     }
17162     return Res;
17163   }
17164
17165   // Otherwise, check to see if this is a register class of the wrong value
17166   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17167   // turn into {ax},{dx}.
17168   if (Res.second->hasType(VT))
17169     return Res;   // Correct type already, nothing to do.
17170
17171   // All of the single-register GCC register classes map their values onto
17172   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17173   // really want an 8-bit or 32-bit register, map to the appropriate register
17174   // class and return the appropriate register.
17175   if (Res.second == &X86::GR16RegClass) {
17176     if (VT == MVT::i8) {
17177       unsigned DestReg = 0;
17178       switch (Res.first) {
17179       default: break;
17180       case X86::AX: DestReg = X86::AL; break;
17181       case X86::DX: DestReg = X86::DL; break;
17182       case X86::CX: DestReg = X86::CL; break;
17183       case X86::BX: DestReg = X86::BL; break;
17184       }
17185       if (DestReg) {
17186         Res.first = DestReg;
17187         Res.second = &X86::GR8RegClass;
17188       }
17189     } else if (VT == MVT::i32) {
17190       unsigned DestReg = 0;
17191       switch (Res.first) {
17192       default: break;
17193       case X86::AX: DestReg = X86::EAX; break;
17194       case X86::DX: DestReg = X86::EDX; break;
17195       case X86::CX: DestReg = X86::ECX; break;
17196       case X86::BX: DestReg = X86::EBX; break;
17197       case X86::SI: DestReg = X86::ESI; break;
17198       case X86::DI: DestReg = X86::EDI; break;
17199       case X86::BP: DestReg = X86::EBP; break;
17200       case X86::SP: DestReg = X86::ESP; break;
17201       }
17202       if (DestReg) {
17203         Res.first = DestReg;
17204         Res.second = &X86::GR32RegClass;
17205       }
17206     } else if (VT == MVT::i64) {
17207       unsigned DestReg = 0;
17208       switch (Res.first) {
17209       default: break;
17210       case X86::AX: DestReg = X86::RAX; break;
17211       case X86::DX: DestReg = X86::RDX; break;
17212       case X86::CX: DestReg = X86::RCX; break;
17213       case X86::BX: DestReg = X86::RBX; break;
17214       case X86::SI: DestReg = X86::RSI; break;
17215       case X86::DI: DestReg = X86::RDI; break;
17216       case X86::BP: DestReg = X86::RBP; break;
17217       case X86::SP: DestReg = X86::RSP; break;
17218       }
17219       if (DestReg) {
17220         Res.first = DestReg;
17221         Res.second = &X86::GR64RegClass;
17222       }
17223     }
17224   } else if (Res.second == &X86::FR32RegClass ||
17225              Res.second == &X86::FR64RegClass ||
17226              Res.second == &X86::VR128RegClass) {
17227     // Handle references to XMM physical registers that got mapped into the
17228     // wrong class.  This can happen with constraints like {xmm0} where the
17229     // target independent register mapper will just pick the first match it can
17230     // find, ignoring the required type.
17231
17232     if (VT == MVT::f32 || VT == MVT::i32)
17233       Res.second = &X86::FR32RegClass;
17234     else if (VT == MVT::f64 || VT == MVT::i64)
17235       Res.second = &X86::FR64RegClass;
17236     else if (X86::VR128RegClass.hasType(VT))
17237       Res.second = &X86::VR128RegClass;
17238     else if (X86::VR256RegClass.hasType(VT))
17239       Res.second = &X86::VR256RegClass;
17240   }
17241
17242   return Res;
17243 }