Fix PR14161
[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   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561
562   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
564   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
567     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
568   } else {
569     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
570     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
575
576   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578                        MVT::i64 : MVT::i32, Custom);
579   else if (TM.Options.EnableSegmentedStacks)
580     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581                        MVT::i64 : MVT::i32, Custom);
582   else
583     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584                        MVT::i64 : MVT::i32, Expand);
585
586   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587     // f32 and f64 use SSE.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, &X86::FR32RegClass);
590     addRegisterClass(MVT::f64, &X86::FR64RegClass);
591
592     // Use ANDPD to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f64, Custom);
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f64, Custom);
598     setOperationAction(ISD::FNEG , MVT::f32, Custom);
599
600     // Use ANDPD and ORPD to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // Lower this to FGETSIGNx86 plus an AND.
605     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607
608     // We don't support sin/cos/fmod
609     setOperationAction(ISD::FSIN , MVT::f64, Expand);
610     setOperationAction(ISD::FCOS , MVT::f64, Expand);
611     setOperationAction(ISD::FSIN , MVT::f32, Expand);
612     setOperationAction(ISD::FCOS , MVT::f32, Expand);
613
614     // Expand FP immediates into loads from the stack, except for the special
615     // cases we handle.
616     addLegalFPImmediate(APFloat(+0.0)); // xorpd
617     addLegalFPImmediate(APFloat(+0.0f)); // xorps
618   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619     // Use SSE for f32, x87 for f64.
620     // Set up the FP register classes.
621     addRegisterClass(MVT::f32, &X86::FR32RegClass);
622     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623
624     // Use ANDPS to simulate FABS.
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f32, Custom);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631
632     // Use ANDPS and ORPS to simulate FCOPYSIGN.
633     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635
636     // We don't support sin/cos/fmod
637     setOperationAction(ISD::FSIN , MVT::f32, Expand);
638     setOperationAction(ISD::FCOS , MVT::f32, Expand);
639
640     // Special cases we handle for FP constants.
641     addLegalFPImmediate(APFloat(+0.0f)); // xorps
642     addLegalFPImmediate(APFloat(+0.0)); // FLD0
643     addLegalFPImmediate(APFloat(+1.0)); // FLD1
644     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646
647     if (!TM.Options.UnsafeFPMath) {
648       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
649       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
650     }
651   } else if (!TM.Options.UseSoftFloat) {
652     // f32 and f64 in x87.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656
657     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
658     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661
662     if (!TM.Options.UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
664       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
666       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
667     }
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
676   }
677
678   // We don't support FMA.
679   setOperationAction(ISD::FMA, MVT::f64, Expand);
680   setOperationAction(ISD::FMA, MVT::f32, Expand);
681
682   // Long double always uses X87.
683   if (!TM.Options.UseSoftFloat) {
684     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687     {
688       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689       addLegalFPImmediate(TmpFlt);  // FLD0
690       TmpFlt.changeSign();
691       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
692
693       bool ignored;
694       APFloat TmpFlt2(+1.0);
695       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696                       &ignored);
697       addLegalFPImmediate(TmpFlt2);  // FLD1
698       TmpFlt2.changeSign();
699       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
700     }
701
702     if (!TM.Options.UnsafeFPMath) {
703       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
704       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
705     }
706
707     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
709     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
711     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712     setOperationAction(ISD::FMA, MVT::f80, Expand);
713   }
714
715   // Always use a library call for pow.
716   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
718   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
719
720   setOperationAction(ISD::FLOG, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP, MVT::f80, Expand);
724   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725
726   // First set operation action for all vector types to either promote
727   // (for widening) or expand (for scalarization). Then we will selectively
728   // turn on ones that can be effectively codegen'd.
729   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
789     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
790     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792       setTruncStoreAction((MVT::SimpleValueType)VT,
793                           (MVT::SimpleValueType)InnerVT, Expand);
794     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
797   }
798
799   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800   // with -msoft-float, disable use of MMX as well.
801   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803     // No operations on x86mmx supported, everything uses intrinsics.
804   }
805
806   // MMX-sized vectors (other than x86mmx) are expected to be expanded
807   // into smaller operations.
808   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
809   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
811   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
812   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
813   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
814   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
815   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
816   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
817   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
818   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
819   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
820   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
821   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
822   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
823   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
827   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
828   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
829   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
830   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
832   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
836   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
837
838   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840
841     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
845     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
846     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
847     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
848     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
849     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
850     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
853   }
854
855   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857
858     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859     // registers cannot be used even for integer operations.
860     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864
865     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
866     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
867     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
868     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
869     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
870     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
871     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
872     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
873     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
874     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
875     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
879     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
880     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
881     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
882
883     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
886     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
887
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
889     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897       // Do not attempt to custom lower non-power-of-2 vectors
898       if (!isPowerOf2_32(VT.getVectorNumElements()))
899         continue;
900       // Do not attempt to custom lower non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
909     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
911     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
913     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914
915     if (Subtarget->is64Bit()) {
916       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
917       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
918     }
919
920     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922       MVT VT = (MVT::SimpleValueType)i;
923
924       // Do not attempt to promote non-128-bit vectors
925       if (!VT.is128BitVector())
926         continue;
927
928       setOperationAction(ISD::AND,    VT, Promote);
929       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
930       setOperationAction(ISD::OR,     VT, Promote);
931       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
932       setOperationAction(ISD::XOR,    VT, Promote);
933       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
934       setOperationAction(ISD::LOAD,   VT, Promote);
935       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
936       setOperationAction(ISD::SELECT, VT, Promote);
937       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
938     }
939
940     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941
942     // Custom lower v2i64 and v2f64 selects.
943     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
944     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
945     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
946     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
947
948     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
949     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
950
951     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
952     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
953
954     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
955     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
956
957     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
958   }
959
960   if (Subtarget->hasSSE41()) {
961     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
962     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
963     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
964     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
965     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
966     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
967     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
968     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
969     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
970     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
971
972     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
973     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
979     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
982     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
983
984     // i8 and i16 vectors are custom , because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal but thats only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     if (Subtarget->hasAVX2()) {
1017       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1018       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1019
1020       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1021       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1022
1023       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1024     } else {
1025       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1026       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1027
1028       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1029       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1030
1031       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1032     }
1033   }
1034
1035   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1066
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1071     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1072
1073     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1076
1077     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1080     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1081
1082     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1083     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1084
1085     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1089     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1090     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1092
1093     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1094     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1095     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1096
1097     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1098     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1099     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1100     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1101
1102     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1103       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1104       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1105       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1106       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1107       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1108       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1109     }
1110
1111     if (Subtarget->hasAVX2()) {
1112       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1113       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1115       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1116
1117       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1120       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1123       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1125       // Don't lower v32i8 because there is no 128-bit byte mul
1126
1127       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1128
1129       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1130       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1131
1132       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1133       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1134
1135       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1136     } else {
1137       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1138       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1139       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1140       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1141
1142       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1143       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1144       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1145       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1146
1147       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1149       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1150       // Don't lower v32i8 because there is no 128-bit byte mul
1151
1152       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1153       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1154
1155       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1156       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1157
1158       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1159     }
1160
1161     // Custom lower several nodes for 256-bit types.
1162     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1163              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1164       MVT VT = (MVT::SimpleValueType)i;
1165
1166       // Extract subvector is special because the value type
1167       // (result) is 128-bit but the source is 256-bit wide.
1168       if (VT.is128BitVector())
1169         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1170
1171       // Do not attempt to custom lower other non-256-bit vectors
1172       if (!VT.is256BitVector())
1173         continue;
1174
1175       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1176       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1177       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1178       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1179       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1180       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1181       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1182     }
1183
1184     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1185     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1186       MVT VT = (MVT::SimpleValueType)i;
1187
1188       // Do not attempt to promote non-256-bit vectors
1189       if (!VT.is256BitVector())
1190         continue;
1191
1192       setOperationAction(ISD::AND,    VT, Promote);
1193       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1194       setOperationAction(ISD::OR,     VT, Promote);
1195       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1196       setOperationAction(ISD::XOR,    VT, Promote);
1197       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1198       setOperationAction(ISD::LOAD,   VT, Promote);
1199       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1200       setOperationAction(ISD::SELECT, VT, Promote);
1201       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1202     }
1203   }
1204
1205   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1206   // of this type with custom code.
1207   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1208            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1209     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1210                        Custom);
1211   }
1212
1213   // We want to custom lower some of our intrinsics.
1214   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1215   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1216
1217
1218   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1219   // handle type legalization for these operations here.
1220   //
1221   // FIXME: We really should do custom legalization for addition and
1222   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1223   // than generic legalization for 64-bit multiplication-with-overflow, though.
1224   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1225     // Add/Sub/Mul with overflow operations are custom lowered.
1226     MVT VT = IntVTs[i];
1227     setOperationAction(ISD::SADDO, VT, Custom);
1228     setOperationAction(ISD::UADDO, VT, Custom);
1229     setOperationAction(ISD::SSUBO, VT, Custom);
1230     setOperationAction(ISD::USUBO, VT, Custom);
1231     setOperationAction(ISD::SMULO, VT, Custom);
1232     setOperationAction(ISD::UMULO, VT, Custom);
1233   }
1234
1235   // There are no 8-bit 3-address imul/mul instructions
1236   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1237   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1238
1239   if (!Subtarget->is64Bit()) {
1240     // These libcalls are not available in 32-bit.
1241     setLibcallName(RTLIB::SHL_I128, 0);
1242     setLibcallName(RTLIB::SRL_I128, 0);
1243     setLibcallName(RTLIB::SRA_I128, 0);
1244   }
1245
1246   // We have target-specific dag combine patterns for the following nodes:
1247   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1248   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1249   setTargetDAGCombine(ISD::VSELECT);
1250   setTargetDAGCombine(ISD::SELECT);
1251   setTargetDAGCombine(ISD::SHL);
1252   setTargetDAGCombine(ISD::SRA);
1253   setTargetDAGCombine(ISD::SRL);
1254   setTargetDAGCombine(ISD::OR);
1255   setTargetDAGCombine(ISD::AND);
1256   setTargetDAGCombine(ISD::ADD);
1257   setTargetDAGCombine(ISD::FADD);
1258   setTargetDAGCombine(ISD::FSUB);
1259   setTargetDAGCombine(ISD::FMA);
1260   setTargetDAGCombine(ISD::SUB);
1261   setTargetDAGCombine(ISD::LOAD);
1262   setTargetDAGCombine(ISD::STORE);
1263   setTargetDAGCombine(ISD::ZERO_EXTEND);
1264   setTargetDAGCombine(ISD::ANY_EXTEND);
1265   setTargetDAGCombine(ISD::SIGN_EXTEND);
1266   setTargetDAGCombine(ISD::TRUNCATE);
1267   setTargetDAGCombine(ISD::SINT_TO_FP);
1268   setTargetDAGCombine(ISD::SETCC);
1269   if (Subtarget->is64Bit())
1270     setTargetDAGCombine(ISD::MUL);
1271   setTargetDAGCombine(ISD::XOR);
1272
1273   computeRegisterProperties();
1274
1275   // On Darwin, -Os means optimize for size without hurting performance,
1276   // do not reduce the limit.
1277   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1278   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1279   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1280   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1281   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1282   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1283   setPrefLoopAlignment(4); // 2^4 bytes.
1284   benefitFromCodePlacementOpt = true;
1285
1286   // Predictable cmov don't hurt on atom because it's in-order.
1287   predictableSelectIsExpensive = !Subtarget->isAtom();
1288
1289   setPrefFunctionAlignment(4); // 2^4 bytes.
1290 }
1291
1292
1293 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1294   if (!VT.isVector()) return MVT::i8;
1295   return VT.changeVectorElementTypeToInteger();
1296 }
1297
1298
1299 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1300 /// the desired ByVal argument alignment.
1301 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1302   if (MaxAlign == 16)
1303     return;
1304   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1305     if (VTy->getBitWidth() == 128)
1306       MaxAlign = 16;
1307   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1308     unsigned EltAlign = 0;
1309     getMaxByValAlign(ATy->getElementType(), EltAlign);
1310     if (EltAlign > MaxAlign)
1311       MaxAlign = EltAlign;
1312   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1313     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1314       unsigned EltAlign = 0;
1315       getMaxByValAlign(STy->getElementType(i), EltAlign);
1316       if (EltAlign > MaxAlign)
1317         MaxAlign = EltAlign;
1318       if (MaxAlign == 16)
1319         break;
1320     }
1321   }
1322 }
1323
1324 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1325 /// function arguments in the caller parameter area. For X86, aggregates
1326 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1327 /// are at 4-byte boundaries.
1328 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1329   if (Subtarget->is64Bit()) {
1330     // Max of 8 and alignment of type.
1331     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1332     if (TyAlign > 8)
1333       return TyAlign;
1334     return 8;
1335   }
1336
1337   unsigned Align = 4;
1338   if (Subtarget->hasSSE1())
1339     getMaxByValAlign(Ty, Align);
1340   return Align;
1341 }
1342
1343 /// getOptimalMemOpType - Returns the target specific optimal type for load
1344 /// and store operations as a result of memset, memcpy, and memmove
1345 /// lowering. If DstAlign is zero that means it's safe to destination
1346 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1347 /// means there isn't a need to check it against alignment requirement,
1348 /// probably because the source does not need to be loaded. If
1349 /// 'IsZeroVal' is true, that means it's safe to return a
1350 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1351 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1352 /// constant so it does not need to be loaded.
1353 /// It returns EVT::Other if the type should be determined using generic
1354 /// target-independent logic.
1355 EVT
1356 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1357                                        unsigned DstAlign, unsigned SrcAlign,
1358                                        bool IsZeroVal,
1359                                        bool MemcpyStrSrc,
1360                                        MachineFunction &MF) const {
1361   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1362   // linux.  This is because the stack realignment code can't handle certain
1363   // cases like PR2962.  This should be removed when PR2962 is fixed.
1364   const Function *F = MF.getFunction();
1365   if (IsZeroVal &&
1366       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1367     if (Size >= 16 &&
1368         (Subtarget->isUnalignedMemAccessFast() ||
1369          ((DstAlign == 0 || DstAlign >= 16) &&
1370           (SrcAlign == 0 || SrcAlign >= 16))) &&
1371         Subtarget->getStackAlignment() >= 16) {
1372       if (Subtarget->getStackAlignment() >= 32) {
1373         if (Subtarget->hasAVX2())
1374           return MVT::v8i32;
1375         if (Subtarget->hasAVX())
1376           return MVT::v8f32;
1377       }
1378       if (Subtarget->hasSSE2())
1379         return MVT::v4i32;
1380       if (Subtarget->hasSSE1())
1381         return MVT::v4f32;
1382     } else if (!MemcpyStrSrc && Size >= 8 &&
1383                !Subtarget->is64Bit() &&
1384                Subtarget->getStackAlignment() >= 8 &&
1385                Subtarget->hasSSE2()) {
1386       // Do not use f64 to lower memcpy if source is string constant. It's
1387       // better to use i32 to avoid the loads.
1388       return MVT::f64;
1389     }
1390   }
1391   if (Subtarget->is64Bit() && Size >= 8)
1392     return MVT::i64;
1393   return MVT::i32;
1394 }
1395
1396 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1397 /// current function.  The returned value is a member of the
1398 /// MachineJumpTableInfo::JTEntryKind enum.
1399 unsigned X86TargetLowering::getJumpTableEncoding() const {
1400   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1401   // symbol.
1402   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1403       Subtarget->isPICStyleGOT())
1404     return MachineJumpTableInfo::EK_Custom32;
1405
1406   // Otherwise, use the normal jump table encoding heuristics.
1407   return TargetLowering::getJumpTableEncoding();
1408 }
1409
1410 const MCExpr *
1411 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1412                                              const MachineBasicBlock *MBB,
1413                                              unsigned uid,MCContext &Ctx) const{
1414   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1415          Subtarget->isPICStyleGOT());
1416   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1417   // entries.
1418   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1419                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1420 }
1421
1422 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1423 /// jumptable.
1424 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1425                                                     SelectionDAG &DAG) const {
1426   if (!Subtarget->is64Bit())
1427     // This doesn't have DebugLoc associated with it, but is not really the
1428     // same as a Register.
1429     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1430   return Table;
1431 }
1432
1433 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1434 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1435 /// MCExpr.
1436 const MCExpr *X86TargetLowering::
1437 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1438                              MCContext &Ctx) const {
1439   // X86-64 uses RIP relative addressing based on the jump table label.
1440   if (Subtarget->isPICStyleRIPRel())
1441     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1442
1443   // Otherwise, the reference is relative to the PIC base.
1444   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1445 }
1446
1447 // FIXME: Why this routine is here? Move to RegInfo!
1448 std::pair<const TargetRegisterClass*, uint8_t>
1449 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1450   const TargetRegisterClass *RRC = 0;
1451   uint8_t Cost = 1;
1452   switch (VT.getSimpleVT().SimpleTy) {
1453   default:
1454     return TargetLowering::findRepresentativeClass(VT);
1455   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1456     RRC = Subtarget->is64Bit() ?
1457       (const TargetRegisterClass*)&X86::GR64RegClass :
1458       (const TargetRegisterClass*)&X86::GR32RegClass;
1459     break;
1460   case MVT::x86mmx:
1461     RRC = &X86::VR64RegClass;
1462     break;
1463   case MVT::f32: case MVT::f64:
1464   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1465   case MVT::v4f32: case MVT::v2f64:
1466   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1467   case MVT::v4f64:
1468     RRC = &X86::VR128RegClass;
1469     break;
1470   }
1471   return std::make_pair(RRC, Cost);
1472 }
1473
1474 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1475                                                unsigned &Offset) const {
1476   if (!Subtarget->isTargetLinux())
1477     return false;
1478
1479   if (Subtarget->is64Bit()) {
1480     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1481     Offset = 0x28;
1482     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1483       AddressSpace = 256;
1484     else
1485       AddressSpace = 257;
1486   } else {
1487     // %gs:0x14 on i386
1488     Offset = 0x14;
1489     AddressSpace = 256;
1490   }
1491   return true;
1492 }
1493
1494
1495 //===----------------------------------------------------------------------===//
1496 //               Return Value Calling Convention Implementation
1497 //===----------------------------------------------------------------------===//
1498
1499 #include "X86GenCallingConv.inc"
1500
1501 bool
1502 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1503                                   MachineFunction &MF, bool isVarArg,
1504                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1505                         LLVMContext &Context) const {
1506   SmallVector<CCValAssign, 16> RVLocs;
1507   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1508                  RVLocs, Context);
1509   return CCInfo.CheckReturn(Outs, RetCC_X86);
1510 }
1511
1512 SDValue
1513 X86TargetLowering::LowerReturn(SDValue Chain,
1514                                CallingConv::ID CallConv, bool isVarArg,
1515                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1516                                const SmallVectorImpl<SDValue> &OutVals,
1517                                DebugLoc dl, SelectionDAG &DAG) const {
1518   MachineFunction &MF = DAG.getMachineFunction();
1519   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1520
1521   SmallVector<CCValAssign, 16> RVLocs;
1522   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1523                  RVLocs, *DAG.getContext());
1524   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1525
1526   // Add the regs to the liveout set for the function.
1527   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1528   for (unsigned i = 0; i != RVLocs.size(); ++i)
1529     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1530       MRI.addLiveOut(RVLocs[i].getLocReg());
1531
1532   SDValue Flag;
1533
1534   SmallVector<SDValue, 6> RetOps;
1535   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1536   // Operand #1 = Bytes To Pop
1537   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1538                    MVT::i16));
1539
1540   // Copy the result values into the output registers.
1541   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1542     CCValAssign &VA = RVLocs[i];
1543     assert(VA.isRegLoc() && "Can only return in registers!");
1544     SDValue ValToCopy = OutVals[i];
1545     EVT ValVT = ValToCopy.getValueType();
1546
1547     // Promote values to the appropriate types
1548     if (VA.getLocInfo() == CCValAssign::SExt)
1549       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1550     else if (VA.getLocInfo() == CCValAssign::ZExt)
1551       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1552     else if (VA.getLocInfo() == CCValAssign::AExt)
1553       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1554     else if (VA.getLocInfo() == CCValAssign::BCvt)
1555       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1556
1557     // If this is x86-64, and we disabled SSE, we can't return FP values,
1558     // or SSE or MMX vectors.
1559     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1560          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1561           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1562       report_fatal_error("SSE register return with SSE disabled");
1563     }
1564     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1565     // llvm-gcc has never done it right and no one has noticed, so this
1566     // should be OK for now.
1567     if (ValVT == MVT::f64 &&
1568         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1569       report_fatal_error("SSE2 register return with SSE2 disabled");
1570
1571     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1572     // the RET instruction and handled by the FP Stackifier.
1573     if (VA.getLocReg() == X86::ST0 ||
1574         VA.getLocReg() == X86::ST1) {
1575       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1576       // change the value to the FP stack register class.
1577       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1578         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1579       RetOps.push_back(ValToCopy);
1580       // Don't emit a copytoreg.
1581       continue;
1582     }
1583
1584     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1585     // which is returned in RAX / RDX.
1586     if (Subtarget->is64Bit()) {
1587       if (ValVT == MVT::x86mmx) {
1588         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1589           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1590           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1591                                   ValToCopy);
1592           // If we don't have SSE2 available, convert to v4f32 so the generated
1593           // register is legal.
1594           if (!Subtarget->hasSSE2())
1595             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1596         }
1597       }
1598     }
1599
1600     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1601     Flag = Chain.getValue(1);
1602   }
1603
1604   // The x86-64 ABI for returning structs by value requires that we copy
1605   // the sret argument into %rax for the return. We saved the argument into
1606   // a virtual register in the entry block, so now we copy the value out
1607   // and into %rax.
1608   if (Subtarget->is64Bit() &&
1609       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1610     MachineFunction &MF = DAG.getMachineFunction();
1611     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1612     unsigned Reg = FuncInfo->getSRetReturnReg();
1613     assert(Reg &&
1614            "SRetReturnReg should have been set in LowerFormalArguments().");
1615     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1616
1617     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1618     Flag = Chain.getValue(1);
1619
1620     // RAX now acts like a return value.
1621     MRI.addLiveOut(X86::RAX);
1622   }
1623
1624   RetOps[0] = Chain;  // Update chain.
1625
1626   // Add the flag if we have it.
1627   if (Flag.getNode())
1628     RetOps.push_back(Flag);
1629
1630   return DAG.getNode(X86ISD::RET_FLAG, dl,
1631                      MVT::Other, &RetOps[0], RetOps.size());
1632 }
1633
1634 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1635   if (N->getNumValues() != 1)
1636     return false;
1637   if (!N->hasNUsesOfValue(1, 0))
1638     return false;
1639
1640   SDValue TCChain = Chain;
1641   SDNode *Copy = *N->use_begin();
1642   if (Copy->getOpcode() == ISD::CopyToReg) {
1643     // If the copy has a glue operand, we conservatively assume it isn't safe to
1644     // perform a tail call.
1645     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1646       return false;
1647     TCChain = Copy->getOperand(0);
1648   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1649     return false;
1650
1651   bool HasRet = false;
1652   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1653        UI != UE; ++UI) {
1654     if (UI->getOpcode() != X86ISD::RET_FLAG)
1655       return false;
1656     HasRet = true;
1657   }
1658
1659   if (!HasRet)
1660     return false;
1661
1662   Chain = TCChain;
1663   return true;
1664 }
1665
1666 EVT
1667 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1668                                             ISD::NodeType ExtendKind) const {
1669   MVT ReturnMVT;
1670   // TODO: Is this also valid on 32-bit?
1671   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1672     ReturnMVT = MVT::i8;
1673   else
1674     ReturnMVT = MVT::i32;
1675
1676   EVT MinVT = getRegisterType(Context, ReturnMVT);
1677   return VT.bitsLT(MinVT) ? MinVT : VT;
1678 }
1679
1680 /// LowerCallResult - Lower the result values of a call into the
1681 /// appropriate copies out of appropriate physical registers.
1682 ///
1683 SDValue
1684 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1685                                    CallingConv::ID CallConv, bool isVarArg,
1686                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1687                                    DebugLoc dl, SelectionDAG &DAG,
1688                                    SmallVectorImpl<SDValue> &InVals) const {
1689
1690   // Assign locations to each value returned by this call.
1691   SmallVector<CCValAssign, 16> RVLocs;
1692   bool Is64Bit = Subtarget->is64Bit();
1693   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1694                  getTargetMachine(), RVLocs, *DAG.getContext());
1695   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1696
1697   // Copy all of the result registers out of their specified physreg.
1698   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1699     CCValAssign &VA = RVLocs[i];
1700     EVT CopyVT = VA.getValVT();
1701
1702     // If this is x86-64, and we disabled SSE, we can't return FP values
1703     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1704         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1705       report_fatal_error("SSE register return with SSE disabled");
1706     }
1707
1708     SDValue Val;
1709
1710     // If this is a call to a function that returns an fp value on the floating
1711     // point stack, we must guarantee the value is popped from the stack, so
1712     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1713     // if the return value is not used. We use the FpPOP_RETVAL instruction
1714     // instead.
1715     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1716       // If we prefer to use the value in xmm registers, copy it out as f80 and
1717       // use a truncate to move it from fp stack reg to xmm reg.
1718       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1719       SDValue Ops[] = { Chain, InFlag };
1720       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1721                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1722       Val = Chain.getValue(0);
1723
1724       // Round the f80 to the right size, which also moves it to the appropriate
1725       // xmm register.
1726       if (CopyVT != VA.getValVT())
1727         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1728                           // This truncation won't change the value.
1729                           DAG.getIntPtrConstant(1));
1730     } else {
1731       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1732                                  CopyVT, InFlag).getValue(1);
1733       Val = Chain.getValue(0);
1734     }
1735     InFlag = Chain.getValue(2);
1736     InVals.push_back(Val);
1737   }
1738
1739   return Chain;
1740 }
1741
1742
1743 //===----------------------------------------------------------------------===//
1744 //                C & StdCall & Fast Calling Convention implementation
1745 //===----------------------------------------------------------------------===//
1746 //  StdCall calling convention seems to be standard for many Windows' API
1747 //  routines and around. It differs from C calling convention just a little:
1748 //  callee should clean up the stack, not caller. Symbols should be also
1749 //  decorated in some fancy way :) It doesn't support any vector arguments.
1750 //  For info on fast calling convention see Fast Calling Convention (tail call)
1751 //  implementation LowerX86_32FastCCCallTo.
1752
1753 /// CallIsStructReturn - Determines whether a call uses struct return
1754 /// semantics.
1755 enum StructReturnType {
1756   NotStructReturn,
1757   RegStructReturn,
1758   StackStructReturn
1759 };
1760 static StructReturnType
1761 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1762   if (Outs.empty())
1763     return NotStructReturn;
1764
1765   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1766   if (!Flags.isSRet())
1767     return NotStructReturn;
1768   if (Flags.isInReg())
1769     return RegStructReturn;
1770   return StackStructReturn;
1771 }
1772
1773 /// ArgsAreStructReturn - Determines whether a function uses struct
1774 /// return semantics.
1775 static StructReturnType
1776 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1777   if (Ins.empty())
1778     return NotStructReturn;
1779
1780   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1781   if (!Flags.isSRet())
1782     return NotStructReturn;
1783   if (Flags.isInReg())
1784     return RegStructReturn;
1785   return StackStructReturn;
1786 }
1787
1788 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1789 /// by "Src" to address "Dst" with size and alignment information specified by
1790 /// the specific parameter attribute. The copy will be passed as a byval
1791 /// function parameter.
1792 static SDValue
1793 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1794                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1795                           DebugLoc dl) {
1796   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1797
1798   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1799                        /*isVolatile*/false, /*AlwaysInline=*/true,
1800                        MachinePointerInfo(), MachinePointerInfo());
1801 }
1802
1803 /// IsTailCallConvention - Return true if the calling convention is one that
1804 /// supports tail call optimization.
1805 static bool IsTailCallConvention(CallingConv::ID CC) {
1806   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1807 }
1808
1809 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1810   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1811     return false;
1812
1813   CallSite CS(CI);
1814   CallingConv::ID CalleeCC = CS.getCallingConv();
1815   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1816     return false;
1817
1818   return true;
1819 }
1820
1821 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1822 /// a tailcall target by changing its ABI.
1823 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1824                                    bool GuaranteedTailCallOpt) {
1825   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1826 }
1827
1828 SDValue
1829 X86TargetLowering::LowerMemArgument(SDValue Chain,
1830                                     CallingConv::ID CallConv,
1831                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1832                                     DebugLoc dl, SelectionDAG &DAG,
1833                                     const CCValAssign &VA,
1834                                     MachineFrameInfo *MFI,
1835                                     unsigned i) const {
1836   // Create the nodes corresponding to a load from this parameter slot.
1837   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1838   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1839                               getTargetMachine().Options.GuaranteedTailCallOpt);
1840   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1841   EVT ValVT;
1842
1843   // If value is passed by pointer we have address passed instead of the value
1844   // itself.
1845   if (VA.getLocInfo() == CCValAssign::Indirect)
1846     ValVT = VA.getLocVT();
1847   else
1848     ValVT = VA.getValVT();
1849
1850   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1851   // changed with more analysis.
1852   // In case of tail call optimization mark all arguments mutable. Since they
1853   // could be overwritten by lowering of arguments in case of a tail call.
1854   if (Flags.isByVal()) {
1855     unsigned Bytes = Flags.getByValSize();
1856     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1857     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1858     return DAG.getFrameIndex(FI, getPointerTy());
1859   } else {
1860     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1861                                     VA.getLocMemOffset(), isImmutable);
1862     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1863     return DAG.getLoad(ValVT, dl, Chain, FIN,
1864                        MachinePointerInfo::getFixedStack(FI),
1865                        false, false, false, 0);
1866   }
1867 }
1868
1869 SDValue
1870 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1871                                         CallingConv::ID CallConv,
1872                                         bool isVarArg,
1873                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1874                                         DebugLoc dl,
1875                                         SelectionDAG &DAG,
1876                                         SmallVectorImpl<SDValue> &InVals)
1877                                           const {
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880
1881   const Function* Fn = MF.getFunction();
1882   if (Fn->hasExternalLinkage() &&
1883       Subtarget->isTargetCygMing() &&
1884       Fn->getName() == "main")
1885     FuncInfo->setForceFramePointer(true);
1886
1887   MachineFrameInfo *MFI = MF.getFrameInfo();
1888   bool Is64Bit = Subtarget->is64Bit();
1889   bool IsWindows = Subtarget->isTargetWindows();
1890   bool IsWin64 = Subtarget->isTargetWin64();
1891
1892   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1893          "Var args not supported with calling convention fastcc or ghc");
1894
1895   // Assign locations to all of the incoming arguments.
1896   SmallVector<CCValAssign, 16> ArgLocs;
1897   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1898                  ArgLocs, *DAG.getContext());
1899
1900   // Allocate shadow area for Win64
1901   if (IsWin64) {
1902     CCInfo.AllocateStack(32, 8);
1903   }
1904
1905   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1906
1907   unsigned LastVal = ~0U;
1908   SDValue ArgValue;
1909   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1910     CCValAssign &VA = ArgLocs[i];
1911     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1912     // places.
1913     assert(VA.getValNo() != LastVal &&
1914            "Don't support value assigned to multiple locs yet");
1915     (void)LastVal;
1916     LastVal = VA.getValNo();
1917
1918     if (VA.isRegLoc()) {
1919       EVT RegVT = VA.getLocVT();
1920       const TargetRegisterClass *RC;
1921       if (RegVT == MVT::i32)
1922         RC = &X86::GR32RegClass;
1923       else if (Is64Bit && RegVT == MVT::i64)
1924         RC = &X86::GR64RegClass;
1925       else if (RegVT == MVT::f32)
1926         RC = &X86::FR32RegClass;
1927       else if (RegVT == MVT::f64)
1928         RC = &X86::FR64RegClass;
1929       else if (RegVT.is256BitVector())
1930         RC = &X86::VR256RegClass;
1931       else if (RegVT.is128BitVector())
1932         RC = &X86::VR128RegClass;
1933       else if (RegVT == MVT::x86mmx)
1934         RC = &X86::VR64RegClass;
1935       else
1936         llvm_unreachable("Unknown argument type!");
1937
1938       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1939       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1940
1941       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1942       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1943       // right size.
1944       if (VA.getLocInfo() == CCValAssign::SExt)
1945         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1946                                DAG.getValueType(VA.getValVT()));
1947       else if (VA.getLocInfo() == CCValAssign::ZExt)
1948         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1949                                DAG.getValueType(VA.getValVT()));
1950       else if (VA.getLocInfo() == CCValAssign::BCvt)
1951         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1952
1953       if (VA.isExtInLoc()) {
1954         // Handle MMX values passed in XMM regs.
1955         if (RegVT.isVector()) {
1956           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1957                                  ArgValue);
1958         } else
1959           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1960       }
1961     } else {
1962       assert(VA.isMemLoc());
1963       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1964     }
1965
1966     // If value is passed via pointer - do a load.
1967     if (VA.getLocInfo() == CCValAssign::Indirect)
1968       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1969                              MachinePointerInfo(), false, false, false, 0);
1970
1971     InVals.push_back(ArgValue);
1972   }
1973
1974   // The x86-64 ABI for returning structs by value requires that we copy
1975   // the sret argument into %rax for the return. Save the argument into
1976   // a virtual register so that we can access it from the return points.
1977   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1978     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1979     unsigned Reg = FuncInfo->getSRetReturnReg();
1980     if (!Reg) {
1981       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1982       FuncInfo->setSRetReturnReg(Reg);
1983     }
1984     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1985     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1986   }
1987
1988   unsigned StackSize = CCInfo.getNextStackOffset();
1989   // Align stack specially for tail calls.
1990   if (FuncIsMadeTailCallSafe(CallConv,
1991                              MF.getTarget().Options.GuaranteedTailCallOpt))
1992     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1993
1994   // If the function takes variable number of arguments, make a frame index for
1995   // the start of the first vararg value... for expansion of llvm.va_start.
1996   if (isVarArg) {
1997     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1998                     CallConv != CallingConv::X86_ThisCall)) {
1999       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2000     }
2001     if (Is64Bit) {
2002       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2003
2004       // FIXME: We should really autogenerate these arrays
2005       static const uint16_t GPR64ArgRegsWin64[] = {
2006         X86::RCX, X86::RDX, X86::R8,  X86::R9
2007       };
2008       static const uint16_t GPR64ArgRegs64Bit[] = {
2009         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2010       };
2011       static const uint16_t XMMArgRegs64Bit[] = {
2012         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2013         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2014       };
2015       const uint16_t *GPR64ArgRegs;
2016       unsigned NumXMMRegs = 0;
2017
2018       if (IsWin64) {
2019         // The XMM registers which might contain var arg parameters are shadowed
2020         // in their paired GPR.  So we only need to save the GPR to their home
2021         // slots.
2022         TotalNumIntRegs = 4;
2023         GPR64ArgRegs = GPR64ArgRegsWin64;
2024       } else {
2025         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2026         GPR64ArgRegs = GPR64ArgRegs64Bit;
2027
2028         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2029                                                 TotalNumXMMRegs);
2030       }
2031       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2032                                                        TotalNumIntRegs);
2033
2034       bool NoImplicitFloatOps = Fn->getFnAttributes().
2035         hasAttribute(Attributes::NoImplicitFloat);
2036       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2037              "SSE register cannot be used when SSE is disabled!");
2038       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2039                NoImplicitFloatOps) &&
2040              "SSE register cannot be used when SSE is disabled!");
2041       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2042           !Subtarget->hasSSE1())
2043         // Kernel mode asks for SSE to be disabled, so don't push them
2044         // on the stack.
2045         TotalNumXMMRegs = 0;
2046
2047       if (IsWin64) {
2048         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2049         // Get to the caller-allocated home save location.  Add 8 to account
2050         // for the return address.
2051         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2052         FuncInfo->setRegSaveFrameIndex(
2053           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2054         // Fixup to set vararg frame on shadow area (4 x i64).
2055         if (NumIntRegs < 4)
2056           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2057       } else {
2058         // For X86-64, if there are vararg parameters that are passed via
2059         // registers, then we must store them to their spots on the stack so
2060         // they may be loaded by deferencing the result of va_next.
2061         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2062         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2063         FuncInfo->setRegSaveFrameIndex(
2064           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2065                                false));
2066       }
2067
2068       // Store the integer parameter registers.
2069       SmallVector<SDValue, 8> MemOps;
2070       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2071                                         getPointerTy());
2072       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2073       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2074         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2075                                   DAG.getIntPtrConstant(Offset));
2076         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2077                                      &X86::GR64RegClass);
2078         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2079         SDValue Store =
2080           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2081                        MachinePointerInfo::getFixedStack(
2082                          FuncInfo->getRegSaveFrameIndex(), Offset),
2083                        false, false, 0);
2084         MemOps.push_back(Store);
2085         Offset += 8;
2086       }
2087
2088       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2089         // Now store the XMM (fp + vector) parameter registers.
2090         SmallVector<SDValue, 11> SaveXMMOps;
2091         SaveXMMOps.push_back(Chain);
2092
2093         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2094         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2095         SaveXMMOps.push_back(ALVal);
2096
2097         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2098                                FuncInfo->getRegSaveFrameIndex()));
2099         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2100                                FuncInfo->getVarArgsFPOffset()));
2101
2102         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2103           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2104                                        &X86::VR128RegClass);
2105           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2106           SaveXMMOps.push_back(Val);
2107         }
2108         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2109                                      MVT::Other,
2110                                      &SaveXMMOps[0], SaveXMMOps.size()));
2111       }
2112
2113       if (!MemOps.empty())
2114         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115                             &MemOps[0], MemOps.size());
2116     }
2117   }
2118
2119   // Some CCs need callee pop.
2120   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2121                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2122     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2123   } else {
2124     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2125     // If this is an sret function, the return should pop the hidden pointer.
2126     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2127         argsAreStructReturn(Ins) == StackStructReturn)
2128       FuncInfo->setBytesToPopOnReturn(4);
2129   }
2130
2131   if (!Is64Bit) {
2132     // RegSaveFrameIndex is X86-64 only.
2133     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2134     if (CallConv == CallingConv::X86_FastCall ||
2135         CallConv == CallingConv::X86_ThisCall)
2136       // fastcc functions can't have varargs.
2137       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2138   }
2139
2140   FuncInfo->setArgumentStackSize(StackSize);
2141
2142   return Chain;
2143 }
2144
2145 SDValue
2146 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2147                                     SDValue StackPtr, SDValue Arg,
2148                                     DebugLoc dl, SelectionDAG &DAG,
2149                                     const CCValAssign &VA,
2150                                     ISD::ArgFlagsTy Flags) const {
2151   unsigned LocMemOffset = VA.getLocMemOffset();
2152   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2153   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2154   if (Flags.isByVal())
2155     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2156
2157   return DAG.getStore(Chain, dl, Arg, PtrOff,
2158                       MachinePointerInfo::getStack(LocMemOffset),
2159                       false, false, 0);
2160 }
2161
2162 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2163 /// optimization is performed and it is required.
2164 SDValue
2165 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2166                                            SDValue &OutRetAddr, SDValue Chain,
2167                                            bool IsTailCall, bool Is64Bit,
2168                                            int FPDiff, DebugLoc dl) const {
2169   // Adjust the Return address stack slot.
2170   EVT VT = getPointerTy();
2171   OutRetAddr = getReturnAddressFrameIndex(DAG);
2172
2173   // Load the "old" Return address.
2174   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2175                            false, false, false, 0);
2176   return SDValue(OutRetAddr.getNode(), 1);
2177 }
2178
2179 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2180 /// optimization is performed and it is required (FPDiff!=0).
2181 static SDValue
2182 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2183                          SDValue Chain, SDValue RetAddrFrIdx,
2184                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2185   // Store the return address to the appropriate stack slot.
2186   if (!FPDiff) return Chain;
2187   // Calculate the new stack slot for the return address.
2188   int SlotSize = Is64Bit ? 8 : 4;
2189   int NewReturnAddrFI =
2190     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2191   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2192   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2193   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2194                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2195                        false, false, 0);
2196   return Chain;
2197 }
2198
2199 SDValue
2200 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2201                              SmallVectorImpl<SDValue> &InVals) const {
2202   SelectionDAG &DAG                     = CLI.DAG;
2203   DebugLoc &dl                          = CLI.DL;
2204   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2205   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2206   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2207   SDValue Chain                         = CLI.Chain;
2208   SDValue Callee                        = CLI.Callee;
2209   CallingConv::ID CallConv              = CLI.CallConv;
2210   bool &isTailCall                      = CLI.IsTailCall;
2211   bool isVarArg                         = CLI.IsVarArg;
2212
2213   MachineFunction &MF = DAG.getMachineFunction();
2214   bool Is64Bit        = Subtarget->is64Bit();
2215   bool IsWin64        = Subtarget->isTargetWin64();
2216   bool IsWindows      = Subtarget->isTargetWindows();
2217   StructReturnType SR = callIsStructReturn(Outs);
2218   bool IsSibcall      = false;
2219
2220   if (MF.getTarget().Options.DisableTailCalls)
2221     isTailCall = false;
2222
2223   if (isTailCall) {
2224     // Check if it's really possible to do a tail call.
2225     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2226                     isVarArg, SR != NotStructReturn,
2227                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2228                     Outs, OutVals, Ins, DAG);
2229
2230     // Sibcalls are automatically detected tailcalls which do not require
2231     // ABI changes.
2232     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2233       IsSibcall = true;
2234
2235     if (isTailCall)
2236       ++NumTailCalls;
2237   }
2238
2239   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2240          "Var args not supported with calling convention fastcc or ghc");
2241
2242   // Analyze operands of the call, assigning locations to each operand.
2243   SmallVector<CCValAssign, 16> ArgLocs;
2244   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2245                  ArgLocs, *DAG.getContext());
2246
2247   // Allocate shadow area for Win64
2248   if (IsWin64) {
2249     CCInfo.AllocateStack(32, 8);
2250   }
2251
2252   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2253
2254   // Get a count of how many bytes are to be pushed on the stack.
2255   unsigned NumBytes = CCInfo.getNextStackOffset();
2256   if (IsSibcall)
2257     // This is a sibcall. The memory operands are available in caller's
2258     // own caller's stack.
2259     NumBytes = 0;
2260   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2261            IsTailCallConvention(CallConv))
2262     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2263
2264   int FPDiff = 0;
2265   if (isTailCall && !IsSibcall) {
2266     // Lower arguments at fp - stackoffset + fpdiff.
2267     unsigned NumBytesCallerPushed =
2268       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2269     FPDiff = NumBytesCallerPushed - NumBytes;
2270
2271     // Set the delta of movement of the returnaddr stackslot.
2272     // But only set if delta is greater than previous delta.
2273     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2274       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2275   }
2276
2277   if (!IsSibcall)
2278     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2279
2280   SDValue RetAddrFrIdx;
2281   // Load return address for tail calls.
2282   if (isTailCall && FPDiff)
2283     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2284                                     Is64Bit, FPDiff, dl);
2285
2286   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2287   SmallVector<SDValue, 8> MemOpChains;
2288   SDValue StackPtr;
2289
2290   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2291   // of tail call optimization arguments are handle later.
2292   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2293     CCValAssign &VA = ArgLocs[i];
2294     EVT RegVT = VA.getLocVT();
2295     SDValue Arg = OutVals[i];
2296     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2297     bool isByVal = Flags.isByVal();
2298
2299     // Promote the value if needed.
2300     switch (VA.getLocInfo()) {
2301     default: llvm_unreachable("Unknown loc info!");
2302     case CCValAssign::Full: break;
2303     case CCValAssign::SExt:
2304       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2305       break;
2306     case CCValAssign::ZExt:
2307       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2308       break;
2309     case CCValAssign::AExt:
2310       if (RegVT.is128BitVector()) {
2311         // Special case: passing MMX values in XMM registers.
2312         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2313         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2314         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2315       } else
2316         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2317       break;
2318     case CCValAssign::BCvt:
2319       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2320       break;
2321     case CCValAssign::Indirect: {
2322       // Store the argument.
2323       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2324       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2325       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2326                            MachinePointerInfo::getFixedStack(FI),
2327                            false, false, 0);
2328       Arg = SpillSlot;
2329       break;
2330     }
2331     }
2332
2333     if (VA.isRegLoc()) {
2334       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2335       if (isVarArg && IsWin64) {
2336         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2337         // shadow reg if callee is a varargs function.
2338         unsigned ShadowReg = 0;
2339         switch (VA.getLocReg()) {
2340         case X86::XMM0: ShadowReg = X86::RCX; break;
2341         case X86::XMM1: ShadowReg = X86::RDX; break;
2342         case X86::XMM2: ShadowReg = X86::R8; break;
2343         case X86::XMM3: ShadowReg = X86::R9; break;
2344         }
2345         if (ShadowReg)
2346           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2347       }
2348     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2349       assert(VA.isMemLoc());
2350       if (StackPtr.getNode() == 0)
2351         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2352       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2353                                              dl, DAG, VA, Flags));
2354     }
2355   }
2356
2357   if (!MemOpChains.empty())
2358     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2359                         &MemOpChains[0], MemOpChains.size());
2360
2361   if (Subtarget->isPICStyleGOT()) {
2362     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2363     // GOT pointer.
2364     if (!isTailCall) {
2365       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2366                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2367     } else {
2368       // If we are tail calling and generating PIC/GOT style code load the
2369       // address of the callee into ECX. The value in ecx is used as target of
2370       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2371       // for tail calls on PIC/GOT architectures. Normally we would just put the
2372       // address of GOT into ebx and then call target@PLT. But for tail calls
2373       // ebx would be restored (since ebx is callee saved) before jumping to the
2374       // target@PLT.
2375
2376       // Note: The actual moving to ECX is done further down.
2377       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2378       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2379           !G->getGlobal()->hasProtectedVisibility())
2380         Callee = LowerGlobalAddress(Callee, DAG);
2381       else if (isa<ExternalSymbolSDNode>(Callee))
2382         Callee = LowerExternalSymbol(Callee, DAG);
2383     }
2384   }
2385
2386   if (Is64Bit && isVarArg && !IsWin64) {
2387     // From AMD64 ABI document:
2388     // For calls that may call functions that use varargs or stdargs
2389     // (prototype-less calls or calls to functions containing ellipsis (...) in
2390     // the declaration) %al is used as hidden argument to specify the number
2391     // of SSE registers used. The contents of %al do not need to match exactly
2392     // the number of registers, but must be an ubound on the number of SSE
2393     // registers used and is in the range 0 - 8 inclusive.
2394
2395     // Count the number of XMM registers allocated.
2396     static const uint16_t XMMArgRegs[] = {
2397       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2398       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2399     };
2400     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2401     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2402            && "SSE registers cannot be used when SSE is disabled");
2403
2404     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2405                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2406   }
2407
2408   // For tail calls lower the arguments to the 'real' stack slot.
2409   if (isTailCall) {
2410     // Force all the incoming stack arguments to be loaded from the stack
2411     // before any new outgoing arguments are stored to the stack, because the
2412     // outgoing stack slots may alias the incoming argument stack slots, and
2413     // the alias isn't otherwise explicit. This is slightly more conservative
2414     // than necessary, because it means that each store effectively depends
2415     // on every argument instead of just those arguments it would clobber.
2416     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2417
2418     SmallVector<SDValue, 8> MemOpChains2;
2419     SDValue FIN;
2420     int FI = 0;
2421     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2422       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2423         CCValAssign &VA = ArgLocs[i];
2424         if (VA.isRegLoc())
2425           continue;
2426         assert(VA.isMemLoc());
2427         SDValue Arg = OutVals[i];
2428         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2429         // Create frame index.
2430         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2431         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2432         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2433         FIN = DAG.getFrameIndex(FI, getPointerTy());
2434
2435         if (Flags.isByVal()) {
2436           // Copy relative to framepointer.
2437           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2438           if (StackPtr.getNode() == 0)
2439             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2440                                           getPointerTy());
2441           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2442
2443           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2444                                                            ArgChain,
2445                                                            Flags, DAG, dl));
2446         } else {
2447           // Store relative to framepointer.
2448           MemOpChains2.push_back(
2449             DAG.getStore(ArgChain, dl, Arg, FIN,
2450                          MachinePointerInfo::getFixedStack(FI),
2451                          false, false, 0));
2452         }
2453       }
2454     }
2455
2456     if (!MemOpChains2.empty())
2457       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2458                           &MemOpChains2[0], MemOpChains2.size());
2459
2460     // Store the return address to the appropriate stack slot.
2461     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2462                                      FPDiff, dl);
2463   }
2464
2465   // Build a sequence of copy-to-reg nodes chained together with token chain
2466   // and flag operands which copy the outgoing args into registers.
2467   SDValue InFlag;
2468   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2469     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2470                              RegsToPass[i].second, InFlag);
2471     InFlag = Chain.getValue(1);
2472   }
2473
2474   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2475     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2476     // In the 64-bit large code model, we have to make all calls
2477     // through a register, since the call instruction's 32-bit
2478     // pc-relative offset may not be large enough to hold the whole
2479     // address.
2480   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2481     // If the callee is a GlobalAddress node (quite common, every direct call
2482     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2483     // it.
2484
2485     // We should use extra load for direct calls to dllimported functions in
2486     // non-JIT mode.
2487     const GlobalValue *GV = G->getGlobal();
2488     if (!GV->hasDLLImportLinkage()) {
2489       unsigned char OpFlags = 0;
2490       bool ExtraLoad = false;
2491       unsigned WrapperKind = ISD::DELETED_NODE;
2492
2493       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2494       // external symbols most go through the PLT in PIC mode.  If the symbol
2495       // has hidden or protected visibility, or if it is static or local, then
2496       // we don't need to use the PLT - we can directly call it.
2497       if (Subtarget->isTargetELF() &&
2498           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2499           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2500         OpFlags = X86II::MO_PLT;
2501       } else if (Subtarget->isPICStyleStubAny() &&
2502                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2503                  (!Subtarget->getTargetTriple().isMacOSX() ||
2504                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2505         // PC-relative references to external symbols should go through $stub,
2506         // unless we're building with the leopard linker or later, which
2507         // automatically synthesizes these stubs.
2508         OpFlags = X86II::MO_DARWIN_STUB;
2509       } else if (Subtarget->isPICStyleRIPRel() &&
2510                  isa<Function>(GV) &&
2511                  cast<Function>(GV)->getFnAttributes().
2512                    hasAttribute(Attributes::NonLazyBind)) {
2513         // If the function is marked as non-lazy, generate an indirect call
2514         // which loads from the GOT directly. This avoids runtime overhead
2515         // at the cost of eager binding (and one extra byte of encoding).
2516         OpFlags = X86II::MO_GOTPCREL;
2517         WrapperKind = X86ISD::WrapperRIP;
2518         ExtraLoad = true;
2519       }
2520
2521       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2522                                           G->getOffset(), OpFlags);
2523
2524       // Add a wrapper if needed.
2525       if (WrapperKind != ISD::DELETED_NODE)
2526         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2527       // Add extra indirection if needed.
2528       if (ExtraLoad)
2529         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2530                              MachinePointerInfo::getGOT(),
2531                              false, false, false, 0);
2532     }
2533   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2534     unsigned char OpFlags = 0;
2535
2536     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2537     // external symbols should go through the PLT.
2538     if (Subtarget->isTargetELF() &&
2539         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2540       OpFlags = X86II::MO_PLT;
2541     } else if (Subtarget->isPICStyleStubAny() &&
2542                (!Subtarget->getTargetTriple().isMacOSX() ||
2543                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2544       // PC-relative references to external symbols should go through $stub,
2545       // unless we're building with the leopard linker or later, which
2546       // automatically synthesizes these stubs.
2547       OpFlags = X86II::MO_DARWIN_STUB;
2548     }
2549
2550     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2551                                          OpFlags);
2552   }
2553
2554   // Returns a chain & a flag for retval copy to use.
2555   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2556   SmallVector<SDValue, 8> Ops;
2557
2558   if (!IsSibcall && isTailCall) {
2559     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2560                            DAG.getIntPtrConstant(0, true), InFlag);
2561     InFlag = Chain.getValue(1);
2562   }
2563
2564   Ops.push_back(Chain);
2565   Ops.push_back(Callee);
2566
2567   if (isTailCall)
2568     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2569
2570   // Add argument registers to the end of the list so that they are known live
2571   // into the call.
2572   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2573     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2574                                   RegsToPass[i].second.getValueType()));
2575
2576   // Add a register mask operand representing the call-preserved registers.
2577   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2578   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2579   assert(Mask && "Missing call preserved mask for calling convention");
2580   Ops.push_back(DAG.getRegisterMask(Mask));
2581
2582   if (InFlag.getNode())
2583     Ops.push_back(InFlag);
2584
2585   if (isTailCall) {
2586     // We used to do:
2587     //// If this is the first return lowered for this function, add the regs
2588     //// to the liveout set for the function.
2589     // This isn't right, although it's probably harmless on x86; liveouts
2590     // should be computed from returns not tail calls.  Consider a void
2591     // function making a tail call to a function returning int.
2592     return DAG.getNode(X86ISD::TC_RETURN, dl,
2593                        NodeTys, &Ops[0], Ops.size());
2594   }
2595
2596   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2597   InFlag = Chain.getValue(1);
2598
2599   // Create the CALLSEQ_END node.
2600   unsigned NumBytesForCalleeToPush;
2601   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2602                        getTargetMachine().Options.GuaranteedTailCallOpt))
2603     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2604   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2605            SR == StackStructReturn)
2606     // If this is a call to a struct-return function, the callee
2607     // pops the hidden struct pointer, so we have to push it back.
2608     // This is common for Darwin/X86, Linux & Mingw32 targets.
2609     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2610     NumBytesForCalleeToPush = 4;
2611   else
2612     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2613
2614   // Returns a flag for retval copy to use.
2615   if (!IsSibcall) {
2616     Chain = DAG.getCALLSEQ_END(Chain,
2617                                DAG.getIntPtrConstant(NumBytes, true),
2618                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2619                                                      true),
2620                                InFlag);
2621     InFlag = Chain.getValue(1);
2622   }
2623
2624   // Handle result values, copying them out of physregs into vregs that we
2625   // return.
2626   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2627                          Ins, dl, DAG, InVals);
2628 }
2629
2630
2631 //===----------------------------------------------------------------------===//
2632 //                Fast Calling Convention (tail call) implementation
2633 //===----------------------------------------------------------------------===//
2634
2635 //  Like std call, callee cleans arguments, convention except that ECX is
2636 //  reserved for storing the tail called function address. Only 2 registers are
2637 //  free for argument passing (inreg). Tail call optimization is performed
2638 //  provided:
2639 //                * tailcallopt is enabled
2640 //                * caller/callee are fastcc
2641 //  On X86_64 architecture with GOT-style position independent code only local
2642 //  (within module) calls are supported at the moment.
2643 //  To keep the stack aligned according to platform abi the function
2644 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2645 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2646 //  If a tail called function callee has more arguments than the caller the
2647 //  caller needs to make sure that there is room to move the RETADDR to. This is
2648 //  achieved by reserving an area the size of the argument delta right after the
2649 //  original REtADDR, but before the saved framepointer or the spilled registers
2650 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2651 //  stack layout:
2652 //    arg1
2653 //    arg2
2654 //    RETADDR
2655 //    [ new RETADDR
2656 //      move area ]
2657 //    (possible EBP)
2658 //    ESI
2659 //    EDI
2660 //    local1 ..
2661
2662 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2663 /// for a 16 byte align requirement.
2664 unsigned
2665 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2666                                                SelectionDAG& DAG) const {
2667   MachineFunction &MF = DAG.getMachineFunction();
2668   const TargetMachine &TM = MF.getTarget();
2669   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2670   unsigned StackAlignment = TFI.getStackAlignment();
2671   uint64_t AlignMask = StackAlignment - 1;
2672   int64_t Offset = StackSize;
2673   uint64_t SlotSize = TD->getPointerSize(0);
2674   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2675     // Number smaller than 12 so just add the difference.
2676     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2677   } else {
2678     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2679     Offset = ((~AlignMask) & Offset) + StackAlignment +
2680       (StackAlignment-SlotSize);
2681   }
2682   return Offset;
2683 }
2684
2685 /// MatchingStackOffset - Return true if the given stack call argument is
2686 /// already available in the same position (relatively) of the caller's
2687 /// incoming argument stack.
2688 static
2689 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2690                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2691                          const X86InstrInfo *TII) {
2692   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2693   int FI = INT_MAX;
2694   if (Arg.getOpcode() == ISD::CopyFromReg) {
2695     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2696     if (!TargetRegisterInfo::isVirtualRegister(VR))
2697       return false;
2698     MachineInstr *Def = MRI->getVRegDef(VR);
2699     if (!Def)
2700       return false;
2701     if (!Flags.isByVal()) {
2702       if (!TII->isLoadFromStackSlot(Def, FI))
2703         return false;
2704     } else {
2705       unsigned Opcode = Def->getOpcode();
2706       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2707           Def->getOperand(1).isFI()) {
2708         FI = Def->getOperand(1).getIndex();
2709         Bytes = Flags.getByValSize();
2710       } else
2711         return false;
2712     }
2713   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2714     if (Flags.isByVal())
2715       // ByVal argument is passed in as a pointer but it's now being
2716       // dereferenced. e.g.
2717       // define @foo(%struct.X* %A) {
2718       //   tail call @bar(%struct.X* byval %A)
2719       // }
2720       return false;
2721     SDValue Ptr = Ld->getBasePtr();
2722     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2723     if (!FINode)
2724       return false;
2725     FI = FINode->getIndex();
2726   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2727     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2728     FI = FINode->getIndex();
2729     Bytes = Flags.getByValSize();
2730   } else
2731     return false;
2732
2733   assert(FI != INT_MAX);
2734   if (!MFI->isFixedObjectIndex(FI))
2735     return false;
2736   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2737 }
2738
2739 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2740 /// for tail call optimization. Targets which want to do tail call
2741 /// optimization should implement this function.
2742 bool
2743 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2744                                                      CallingConv::ID CalleeCC,
2745                                                      bool isVarArg,
2746                                                      bool isCalleeStructRet,
2747                                                      bool isCallerStructRet,
2748                                                      Type *RetTy,
2749                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2750                                     const SmallVectorImpl<SDValue> &OutVals,
2751                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2752                                                      SelectionDAG& DAG) const {
2753   if (!IsTailCallConvention(CalleeCC) &&
2754       CalleeCC != CallingConv::C)
2755     return false;
2756
2757   // If -tailcallopt is specified, make fastcc functions tail-callable.
2758   const MachineFunction &MF = DAG.getMachineFunction();
2759   const Function *CallerF = DAG.getMachineFunction().getFunction();
2760
2761   // If the function return type is x86_fp80 and the callee return type is not,
2762   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2763   // perform a tailcall optimization here.
2764   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2765     return false;
2766
2767   CallingConv::ID CallerCC = CallerF->getCallingConv();
2768   bool CCMatch = CallerCC == CalleeCC;
2769
2770   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2771     if (IsTailCallConvention(CalleeCC) && CCMatch)
2772       return true;
2773     return false;
2774   }
2775
2776   // Look for obvious safe cases to perform tail call optimization that do not
2777   // require ABI changes. This is what gcc calls sibcall.
2778
2779   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2780   // emit a special epilogue.
2781   if (RegInfo->needsStackRealignment(MF))
2782     return false;
2783
2784   // Also avoid sibcall optimization if either caller or callee uses struct
2785   // return semantics.
2786   if (isCalleeStructRet || isCallerStructRet)
2787     return false;
2788
2789   // An stdcall caller is expected to clean up its arguments; the callee
2790   // isn't going to do that.
2791   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2792     return false;
2793
2794   // Do not sibcall optimize vararg calls unless all arguments are passed via
2795   // registers.
2796   if (isVarArg && !Outs.empty()) {
2797
2798     // Optimizing for varargs on Win64 is unlikely to be safe without
2799     // additional testing.
2800     if (Subtarget->isTargetWin64())
2801       return false;
2802
2803     SmallVector<CCValAssign, 16> ArgLocs;
2804     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2805                    getTargetMachine(), ArgLocs, *DAG.getContext());
2806
2807     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2808     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2809       if (!ArgLocs[i].isRegLoc())
2810         return false;
2811   }
2812
2813   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2814   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2815   // this into a sibcall.
2816   bool Unused = false;
2817   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2818     if (!Ins[i].Used) {
2819       Unused = true;
2820       break;
2821     }
2822   }
2823   if (Unused) {
2824     SmallVector<CCValAssign, 16> RVLocs;
2825     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2826                    getTargetMachine(), RVLocs, *DAG.getContext());
2827     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2828     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2829       CCValAssign &VA = RVLocs[i];
2830       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2831         return false;
2832     }
2833   }
2834
2835   // If the calling conventions do not match, then we'd better make sure the
2836   // results are returned in the same way as what the caller expects.
2837   if (!CCMatch) {
2838     SmallVector<CCValAssign, 16> RVLocs1;
2839     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2840                     getTargetMachine(), RVLocs1, *DAG.getContext());
2841     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2842
2843     SmallVector<CCValAssign, 16> RVLocs2;
2844     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2845                     getTargetMachine(), RVLocs2, *DAG.getContext());
2846     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2847
2848     if (RVLocs1.size() != RVLocs2.size())
2849       return false;
2850     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2851       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2852         return false;
2853       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2854         return false;
2855       if (RVLocs1[i].isRegLoc()) {
2856         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2857           return false;
2858       } else {
2859         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2860           return false;
2861       }
2862     }
2863   }
2864
2865   // If the callee takes no arguments then go on to check the results of the
2866   // call.
2867   if (!Outs.empty()) {
2868     // Check if stack adjustment is needed. For now, do not do this if any
2869     // argument is passed on the stack.
2870     SmallVector<CCValAssign, 16> ArgLocs;
2871     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2872                    getTargetMachine(), ArgLocs, *DAG.getContext());
2873
2874     // Allocate shadow area for Win64
2875     if (Subtarget->isTargetWin64()) {
2876       CCInfo.AllocateStack(32, 8);
2877     }
2878
2879     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2880     if (CCInfo.getNextStackOffset()) {
2881       MachineFunction &MF = DAG.getMachineFunction();
2882       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2883         return false;
2884
2885       // Check if the arguments are already laid out in the right way as
2886       // the caller's fixed stack objects.
2887       MachineFrameInfo *MFI = MF.getFrameInfo();
2888       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2889       const X86InstrInfo *TII =
2890         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2891       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892         CCValAssign &VA = ArgLocs[i];
2893         SDValue Arg = OutVals[i];
2894         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2895         if (VA.getLocInfo() == CCValAssign::Indirect)
2896           return false;
2897         if (!VA.isRegLoc()) {
2898           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2899                                    MFI, MRI, TII))
2900             return false;
2901         }
2902       }
2903     }
2904
2905     // If the tailcall address may be in a register, then make sure it's
2906     // possible to register allocate for it. In 32-bit, the call address can
2907     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2908     // callee-saved registers are restored. These happen to be the same
2909     // registers used to pass 'inreg' arguments so watch out for those.
2910     if (!Subtarget->is64Bit() &&
2911         !isa<GlobalAddressSDNode>(Callee) &&
2912         !isa<ExternalSymbolSDNode>(Callee)) {
2913       unsigned NumInRegs = 0;
2914       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2915         CCValAssign &VA = ArgLocs[i];
2916         if (!VA.isRegLoc())
2917           continue;
2918         unsigned Reg = VA.getLocReg();
2919         switch (Reg) {
2920         default: break;
2921         case X86::EAX: case X86::EDX: case X86::ECX:
2922           if (++NumInRegs == 3)
2923             return false;
2924           break;
2925         }
2926       }
2927     }
2928   }
2929
2930   return true;
2931 }
2932
2933 FastISel *
2934 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2935                                   const TargetLibraryInfo *libInfo) const {
2936   return X86::createFastISel(funcInfo, libInfo);
2937 }
2938
2939
2940 //===----------------------------------------------------------------------===//
2941 //                           Other Lowering Hooks
2942 //===----------------------------------------------------------------------===//
2943
2944 static bool MayFoldLoad(SDValue Op) {
2945   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2946 }
2947
2948 static bool MayFoldIntoStore(SDValue Op) {
2949   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2950 }
2951
2952 static bool isTargetShuffle(unsigned Opcode) {
2953   switch(Opcode) {
2954   default: return false;
2955   case X86ISD::PSHUFD:
2956   case X86ISD::PSHUFHW:
2957   case X86ISD::PSHUFLW:
2958   case X86ISD::SHUFP:
2959   case X86ISD::PALIGN:
2960   case X86ISD::MOVLHPS:
2961   case X86ISD::MOVLHPD:
2962   case X86ISD::MOVHLPS:
2963   case X86ISD::MOVLPS:
2964   case X86ISD::MOVLPD:
2965   case X86ISD::MOVSHDUP:
2966   case X86ISD::MOVSLDUP:
2967   case X86ISD::MOVDDUP:
2968   case X86ISD::MOVSS:
2969   case X86ISD::MOVSD:
2970   case X86ISD::UNPCKL:
2971   case X86ISD::UNPCKH:
2972   case X86ISD::VPERMILP:
2973   case X86ISD::VPERM2X128:
2974   case X86ISD::VPERMI:
2975     return true;
2976   }
2977 }
2978
2979 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2980                                     SDValue V1, SelectionDAG &DAG) {
2981   switch(Opc) {
2982   default: llvm_unreachable("Unknown x86 shuffle node");
2983   case X86ISD::MOVSHDUP:
2984   case X86ISD::MOVSLDUP:
2985   case X86ISD::MOVDDUP:
2986     return DAG.getNode(Opc, dl, VT, V1);
2987   }
2988 }
2989
2990 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2991                                     SDValue V1, unsigned TargetMask,
2992                                     SelectionDAG &DAG) {
2993   switch(Opc) {
2994   default: llvm_unreachable("Unknown x86 shuffle node");
2995   case X86ISD::PSHUFD:
2996   case X86ISD::PSHUFHW:
2997   case X86ISD::PSHUFLW:
2998   case X86ISD::VPERMILP:
2999   case X86ISD::VPERMI:
3000     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3001   }
3002 }
3003
3004 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3005                                     SDValue V1, SDValue V2, unsigned TargetMask,
3006                                     SelectionDAG &DAG) {
3007   switch(Opc) {
3008   default: llvm_unreachable("Unknown x86 shuffle node");
3009   case X86ISD::PALIGN:
3010   case X86ISD::SHUFP:
3011   case X86ISD::VPERM2X128:
3012     return DAG.getNode(Opc, dl, VT, V1, V2,
3013                        DAG.getConstant(TargetMask, MVT::i8));
3014   }
3015 }
3016
3017 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3018                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3019   switch(Opc) {
3020   default: llvm_unreachable("Unknown x86 shuffle node");
3021   case X86ISD::MOVLHPS:
3022   case X86ISD::MOVLHPD:
3023   case X86ISD::MOVHLPS:
3024   case X86ISD::MOVLPS:
3025   case X86ISD::MOVLPD:
3026   case X86ISD::MOVSS:
3027   case X86ISD::MOVSD:
3028   case X86ISD::UNPCKL:
3029   case X86ISD::UNPCKH:
3030     return DAG.getNode(Opc, dl, VT, V1, V2);
3031   }
3032 }
3033
3034 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3035   MachineFunction &MF = DAG.getMachineFunction();
3036   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3037   int ReturnAddrIndex = FuncInfo->getRAIndex();
3038
3039   if (ReturnAddrIndex == 0) {
3040     // Set up a frame object for the return address.
3041     uint64_t SlotSize = TD->getPointerSize(0);
3042     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3043                                                            false);
3044     FuncInfo->setRAIndex(ReturnAddrIndex);
3045   }
3046
3047   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3048 }
3049
3050
3051 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3052                                        bool hasSymbolicDisplacement) {
3053   // Offset should fit into 32 bit immediate field.
3054   if (!isInt<32>(Offset))
3055     return false;
3056
3057   // If we don't have a symbolic displacement - we don't have any extra
3058   // restrictions.
3059   if (!hasSymbolicDisplacement)
3060     return true;
3061
3062   // FIXME: Some tweaks might be needed for medium code model.
3063   if (M != CodeModel::Small && M != CodeModel::Kernel)
3064     return false;
3065
3066   // For small code model we assume that latest object is 16MB before end of 31
3067   // bits boundary. We may also accept pretty large negative constants knowing
3068   // that all objects are in the positive half of address space.
3069   if (M == CodeModel::Small && Offset < 16*1024*1024)
3070     return true;
3071
3072   // For kernel code model we know that all object resist in the negative half
3073   // of 32bits address space. We may not accept negative offsets, since they may
3074   // be just off and we may accept pretty large positive ones.
3075   if (M == CodeModel::Kernel && Offset > 0)
3076     return true;
3077
3078   return false;
3079 }
3080
3081 /// isCalleePop - Determines whether the callee is required to pop its
3082 /// own arguments. Callee pop is necessary to support tail calls.
3083 bool X86::isCalleePop(CallingConv::ID CallingConv,
3084                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3085   if (IsVarArg)
3086     return false;
3087
3088   switch (CallingConv) {
3089   default:
3090     return false;
3091   case CallingConv::X86_StdCall:
3092     return !is64Bit;
3093   case CallingConv::X86_FastCall:
3094     return !is64Bit;
3095   case CallingConv::X86_ThisCall:
3096     return !is64Bit;
3097   case CallingConv::Fast:
3098     return TailCallOpt;
3099   case CallingConv::GHC:
3100     return TailCallOpt;
3101   }
3102 }
3103
3104 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3105 /// specific condition code, returning the condition code and the LHS/RHS of the
3106 /// comparison to make.
3107 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3108                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3109   if (!isFP) {
3110     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3111       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3112         // X > -1   -> X == 0, jump !sign.
3113         RHS = DAG.getConstant(0, RHS.getValueType());
3114         return X86::COND_NS;
3115       }
3116       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3117         // X < 0   -> X == 0, jump on sign.
3118         return X86::COND_S;
3119       }
3120       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3121         // X < 1   -> X <= 0
3122         RHS = DAG.getConstant(0, RHS.getValueType());
3123         return X86::COND_LE;
3124       }
3125     }
3126
3127     switch (SetCCOpcode) {
3128     default: llvm_unreachable("Invalid integer condition!");
3129     case ISD::SETEQ:  return X86::COND_E;
3130     case ISD::SETGT:  return X86::COND_G;
3131     case ISD::SETGE:  return X86::COND_GE;
3132     case ISD::SETLT:  return X86::COND_L;
3133     case ISD::SETLE:  return X86::COND_LE;
3134     case ISD::SETNE:  return X86::COND_NE;
3135     case ISD::SETULT: return X86::COND_B;
3136     case ISD::SETUGT: return X86::COND_A;
3137     case ISD::SETULE: return X86::COND_BE;
3138     case ISD::SETUGE: return X86::COND_AE;
3139     }
3140   }
3141
3142   // First determine if it is required or is profitable to flip the operands.
3143
3144   // If LHS is a foldable load, but RHS is not, flip the condition.
3145   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3146       !ISD::isNON_EXTLoad(RHS.getNode())) {
3147     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3148     std::swap(LHS, RHS);
3149   }
3150
3151   switch (SetCCOpcode) {
3152   default: break;
3153   case ISD::SETOLT:
3154   case ISD::SETOLE:
3155   case ISD::SETUGT:
3156   case ISD::SETUGE:
3157     std::swap(LHS, RHS);
3158     break;
3159   }
3160
3161   // On a floating point condition, the flags are set as follows:
3162   // ZF  PF  CF   op
3163   //  0 | 0 | 0 | X > Y
3164   //  0 | 0 | 1 | X < Y
3165   //  1 | 0 | 0 | X == Y
3166   //  1 | 1 | 1 | unordered
3167   switch (SetCCOpcode) {
3168   default: llvm_unreachable("Condcode should be pre-legalized away");
3169   case ISD::SETUEQ:
3170   case ISD::SETEQ:   return X86::COND_E;
3171   case ISD::SETOLT:              // flipped
3172   case ISD::SETOGT:
3173   case ISD::SETGT:   return X86::COND_A;
3174   case ISD::SETOLE:              // flipped
3175   case ISD::SETOGE:
3176   case ISD::SETGE:   return X86::COND_AE;
3177   case ISD::SETUGT:              // flipped
3178   case ISD::SETULT:
3179   case ISD::SETLT:   return X86::COND_B;
3180   case ISD::SETUGE:              // flipped
3181   case ISD::SETULE:
3182   case ISD::SETLE:   return X86::COND_BE;
3183   case ISD::SETONE:
3184   case ISD::SETNE:   return X86::COND_NE;
3185   case ISD::SETUO:   return X86::COND_P;
3186   case ISD::SETO:    return X86::COND_NP;
3187   case ISD::SETOEQ:
3188   case ISD::SETUNE:  return X86::COND_INVALID;
3189   }
3190 }
3191
3192 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3193 /// code. Current x86 isa includes the following FP cmov instructions:
3194 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3195 static bool hasFPCMov(unsigned X86CC) {
3196   switch (X86CC) {
3197   default:
3198     return false;
3199   case X86::COND_B:
3200   case X86::COND_BE:
3201   case X86::COND_E:
3202   case X86::COND_P:
3203   case X86::COND_A:
3204   case X86::COND_AE:
3205   case X86::COND_NE:
3206   case X86::COND_NP:
3207     return true;
3208   }
3209 }
3210
3211 /// isFPImmLegal - Returns true if the target can instruction select the
3212 /// specified FP immediate natively. If false, the legalizer will
3213 /// materialize the FP immediate as a load from a constant pool.
3214 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3215   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3216     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3217       return true;
3218   }
3219   return false;
3220 }
3221
3222 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3223 /// the specified range (L, H].
3224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3225   return (Val < 0) || (Val >= Low && Val < Hi);
3226 }
3227
3228 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3229 /// specified value.
3230 static bool isUndefOrEqual(int Val, int CmpVal) {
3231   if (Val < 0 || Val == CmpVal)
3232     return true;
3233   return false;
3234 }
3235
3236 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3237 /// from position Pos and ending in Pos+Size, falls within the specified
3238 /// sequential range (L, L+Pos]. or is undef.
3239 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3240                                        unsigned Pos, unsigned Size, int Low) {
3241   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3242     if (!isUndefOrEqual(Mask[i], Low))
3243       return false;
3244   return true;
3245 }
3246
3247 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3248 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3249 /// the second operand.
3250 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3251   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3252     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3253   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3254     return (Mask[0] < 2 && Mask[1] < 2);
3255   return false;
3256 }
3257
3258 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3259 /// is suitable for input to PSHUFHW.
3260 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3261   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3262     return false;
3263
3264   // Lower quadword copied in order or undef.
3265   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3266     return false;
3267
3268   // Upper quadword shuffled.
3269   for (unsigned i = 4; i != 8; ++i)
3270     if (!isUndefOrInRange(Mask[i], 4, 8))
3271       return false;
3272
3273   if (VT == MVT::v16i16) {
3274     // Lower quadword copied in order or undef.
3275     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3276       return false;
3277
3278     // Upper quadword shuffled.
3279     for (unsigned i = 12; i != 16; ++i)
3280       if (!isUndefOrInRange(Mask[i], 12, 16))
3281         return false;
3282   }
3283
3284   return true;
3285 }
3286
3287 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFLW.
3289 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3290   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3291     return false;
3292
3293   // Upper quadword copied in order.
3294   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3295     return false;
3296
3297   // Lower quadword shuffled.
3298   for (unsigned i = 0; i != 4; ++i)
3299     if (!isUndefOrInRange(Mask[i], 0, 4))
3300       return false;
3301
3302   if (VT == MVT::v16i16) {
3303     // Upper quadword copied in order.
3304     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3305       return false;
3306
3307     // Lower quadword shuffled.
3308     for (unsigned i = 8; i != 12; ++i)
3309       if (!isUndefOrInRange(Mask[i], 8, 12))
3310         return false;
3311   }
3312
3313   return true;
3314 }
3315
3316 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PALIGNR.
3318 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3319                           const X86Subtarget *Subtarget) {
3320   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3321       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3322     return false;
3323
3324   unsigned NumElts = VT.getVectorNumElements();
3325   unsigned NumLanes = VT.getSizeInBits()/128;
3326   unsigned NumLaneElts = NumElts/NumLanes;
3327
3328   // Do not handle 64-bit element shuffles with palignr.
3329   if (NumLaneElts == 2)
3330     return false;
3331
3332   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3333     unsigned i;
3334     for (i = 0; i != NumLaneElts; ++i) {
3335       if (Mask[i+l] >= 0)
3336         break;
3337     }
3338
3339     // Lane is all undef, go to next lane
3340     if (i == NumLaneElts)
3341       continue;
3342
3343     int Start = Mask[i+l];
3344
3345     // Make sure its in this lane in one of the sources
3346     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3347         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3348       return false;
3349
3350     // If not lane 0, then we must match lane 0
3351     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3352       return false;
3353
3354     // Correct second source to be contiguous with first source
3355     if (Start >= (int)NumElts)
3356       Start -= NumElts - NumLaneElts;
3357
3358     // Make sure we're shifting in the right direction.
3359     if (Start <= (int)(i+l))
3360       return false;
3361
3362     Start -= i;
3363
3364     // Check the rest of the elements to see if they are consecutive.
3365     for (++i; i != NumLaneElts; ++i) {
3366       int Idx = Mask[i+l];
3367
3368       // Make sure its in this lane
3369       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3370           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3371         return false;
3372
3373       // If not lane 0, then we must match lane 0
3374       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3375         return false;
3376
3377       if (Idx >= (int)NumElts)
3378         Idx -= NumElts - NumLaneElts;
3379
3380       if (!isUndefOrEqual(Idx, Start+i))
3381         return false;
3382
3383     }
3384   }
3385
3386   return true;
3387 }
3388
3389 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3390 /// the two vector operands have swapped position.
3391 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3392                                      unsigned NumElems) {
3393   for (unsigned i = 0; i != NumElems; ++i) {
3394     int idx = Mask[i];
3395     if (idx < 0)
3396       continue;
3397     else if (idx < (int)NumElems)
3398       Mask[i] = idx + NumElems;
3399     else
3400       Mask[i] = idx - NumElems;
3401   }
3402 }
3403
3404 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3406 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3407 /// reverse of what x86 shuffles want.
3408 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3409                         bool Commuted = false) {
3410   if (!HasAVX && VT.getSizeInBits() == 256)
3411     return false;
3412
3413   unsigned NumElems = VT.getVectorNumElements();
3414   unsigned NumLanes = VT.getSizeInBits()/128;
3415   unsigned NumLaneElems = NumElems/NumLanes;
3416
3417   if (NumLaneElems != 2 && NumLaneElems != 4)
3418     return false;
3419
3420   // VSHUFPSY divides the resulting vector into 4 chunks.
3421   // The sources are also splitted into 4 chunks, and each destination
3422   // chunk must come from a different source chunk.
3423   //
3424   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3425   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3426   //
3427   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3428   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3429   //
3430   // VSHUFPDY divides the resulting vector into 4 chunks.
3431   // The sources are also splitted into 4 chunks, and each destination
3432   // chunk must come from a different source chunk.
3433   //
3434   //  SRC1 =>      X3       X2       X1       X0
3435   //  SRC2 =>      Y3       Y2       Y1       Y0
3436   //
3437   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3438   //
3439   unsigned HalfLaneElems = NumLaneElems/2;
3440   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3441     for (unsigned i = 0; i != NumLaneElems; ++i) {
3442       int Idx = Mask[i+l];
3443       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3444       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3445         return false;
3446       // For VSHUFPSY, the mask of the second half must be the same as the
3447       // first but with the appropriate offsets. This works in the same way as
3448       // VPERMILPS works with masks.
3449       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3450         continue;
3451       if (!isUndefOrEqual(Idx, Mask[i]+l))
3452         return false;
3453     }
3454   }
3455
3456   return true;
3457 }
3458
3459 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3460 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3461 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3462   if (!VT.is128BitVector())
3463     return false;
3464
3465   unsigned NumElems = VT.getVectorNumElements();
3466
3467   if (NumElems != 4)
3468     return false;
3469
3470   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3471   return isUndefOrEqual(Mask[0], 6) &&
3472          isUndefOrEqual(Mask[1], 7) &&
3473          isUndefOrEqual(Mask[2], 2) &&
3474          isUndefOrEqual(Mask[3], 3);
3475 }
3476
3477 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3478 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3479 /// <2, 3, 2, 3>
3480 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3481   if (!VT.is128BitVector())
3482     return false;
3483
3484   unsigned NumElems = VT.getVectorNumElements();
3485
3486   if (NumElems != 4)
3487     return false;
3488
3489   return isUndefOrEqual(Mask[0], 2) &&
3490          isUndefOrEqual(Mask[1], 3) &&
3491          isUndefOrEqual(Mask[2], 2) &&
3492          isUndefOrEqual(Mask[3], 3);
3493 }
3494
3495 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3497 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3498   if (!VT.is128BitVector())
3499     return false;
3500
3501   unsigned NumElems = VT.getVectorNumElements();
3502
3503   if (NumElems != 2 && NumElems != 4)
3504     return false;
3505
3506   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3507     if (!isUndefOrEqual(Mask[i], i + NumElems))
3508       return false;
3509
3510   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3511     if (!isUndefOrEqual(Mask[i], i))
3512       return false;
3513
3514   return true;
3515 }
3516
3517 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3518 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3519 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3520   if (!VT.is128BitVector())
3521     return false;
3522
3523   unsigned NumElems = VT.getVectorNumElements();
3524
3525   if (NumElems != 2 && NumElems != 4)
3526     return false;
3527
3528   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3529     if (!isUndefOrEqual(Mask[i], i))
3530       return false;
3531
3532   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3533     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3534       return false;
3535
3536   return true;
3537 }
3538
3539 //
3540 // Some special combinations that can be optimized.
3541 //
3542 static
3543 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3544                                SelectionDAG &DAG) {
3545   EVT VT = SVOp->getValueType(0);
3546   DebugLoc dl = SVOp->getDebugLoc();
3547
3548   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3549     return SDValue();
3550
3551   ArrayRef<int> Mask = SVOp->getMask();
3552
3553   // These are the special masks that may be optimized.
3554   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3555   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3556   bool MatchEvenMask = true;
3557   bool MatchOddMask  = true;
3558   for (int i=0; i<8; ++i) {
3559     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3560       MatchEvenMask = false;
3561     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3562       MatchOddMask = false;
3563   }
3564
3565   if (!MatchEvenMask && !MatchOddMask)
3566     return SDValue();
3567
3568   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3569
3570   SDValue Op0 = SVOp->getOperand(0);
3571   SDValue Op1 = SVOp->getOperand(1);
3572
3573   if (MatchEvenMask) {
3574     // Shift the second operand right to 32 bits.
3575     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3576     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3577   } else {
3578     // Shift the first operand left to 32 bits.
3579     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3580     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3581   }
3582   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3583   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3584 }
3585
3586 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3587 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3588 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3589                          bool HasAVX2, bool V2IsSplat = false) {
3590   unsigned NumElts = VT.getVectorNumElements();
3591
3592   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3593          "Unsupported vector type for unpckh");
3594
3595   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3596       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3597     return false;
3598
3599   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3600   // independently on 128-bit lanes.
3601   unsigned NumLanes = VT.getSizeInBits()/128;
3602   unsigned NumLaneElts = NumElts/NumLanes;
3603
3604   for (unsigned l = 0; l != NumLanes; ++l) {
3605     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3606          i != (l+1)*NumLaneElts;
3607          i += 2, ++j) {
3608       int BitI  = Mask[i];
3609       int BitI1 = Mask[i+1];
3610       if (!isUndefOrEqual(BitI, j))
3611         return false;
3612       if (V2IsSplat) {
3613         if (!isUndefOrEqual(BitI1, NumElts))
3614           return false;
3615       } else {
3616         if (!isUndefOrEqual(BitI1, j + NumElts))
3617           return false;
3618       }
3619     }
3620   }
3621
3622   return true;
3623 }
3624
3625 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3626 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3627 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3628                          bool HasAVX2, bool V2IsSplat = false) {
3629   unsigned NumElts = VT.getVectorNumElements();
3630
3631   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3632          "Unsupported vector type for unpckh");
3633
3634   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3635       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3636     return false;
3637
3638   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3639   // independently on 128-bit lanes.
3640   unsigned NumLanes = VT.getSizeInBits()/128;
3641   unsigned NumLaneElts = NumElts/NumLanes;
3642
3643   for (unsigned l = 0; l != NumLanes; ++l) {
3644     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3645          i != (l+1)*NumLaneElts; i += 2, ++j) {
3646       int BitI  = Mask[i];
3647       int BitI1 = Mask[i+1];
3648       if (!isUndefOrEqual(BitI, j))
3649         return false;
3650       if (V2IsSplat) {
3651         if (isUndefOrEqual(BitI1, NumElts))
3652           return false;
3653       } else {
3654         if (!isUndefOrEqual(BitI1, j+NumElts))
3655           return false;
3656       }
3657     }
3658   }
3659   return true;
3660 }
3661
3662 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3663 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3664 /// <0, 0, 1, 1>
3665 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3666                                   bool HasAVX2) {
3667   unsigned NumElts = VT.getVectorNumElements();
3668
3669   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3670          "Unsupported vector type for unpckh");
3671
3672   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3673       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3674     return false;
3675
3676   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3677   // FIXME: Need a better way to get rid of this, there's no latency difference
3678   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3679   // the former later. We should also remove the "_undef" special mask.
3680   if (NumElts == 4 && VT.getSizeInBits() == 256)
3681     return false;
3682
3683   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3684   // independently on 128-bit lanes.
3685   unsigned NumLanes = VT.getSizeInBits()/128;
3686   unsigned NumLaneElts = NumElts/NumLanes;
3687
3688   for (unsigned l = 0; l != NumLanes; ++l) {
3689     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3690          i != (l+1)*NumLaneElts;
3691          i += 2, ++j) {
3692       int BitI  = Mask[i];
3693       int BitI1 = Mask[i+1];
3694
3695       if (!isUndefOrEqual(BitI, j))
3696         return false;
3697       if (!isUndefOrEqual(BitI1, j))
3698         return false;
3699     }
3700   }
3701
3702   return true;
3703 }
3704
3705 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3706 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3707 /// <2, 2, 3, 3>
3708 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3709   unsigned NumElts = VT.getVectorNumElements();
3710
3711   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3712          "Unsupported vector type for unpckh");
3713
3714   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3715       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3716     return false;
3717
3718   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3719   // independently on 128-bit lanes.
3720   unsigned NumLanes = VT.getSizeInBits()/128;
3721   unsigned NumLaneElts = NumElts/NumLanes;
3722
3723   for (unsigned l = 0; l != NumLanes; ++l) {
3724     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3725          i != (l+1)*NumLaneElts; i += 2, ++j) {
3726       int BitI  = Mask[i];
3727       int BitI1 = Mask[i+1];
3728       if (!isUndefOrEqual(BitI, j))
3729         return false;
3730       if (!isUndefOrEqual(BitI1, j))
3731         return false;
3732     }
3733   }
3734   return true;
3735 }
3736
3737 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3738 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3739 /// MOVSD, and MOVD, i.e. setting the lowest element.
3740 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3741   if (VT.getVectorElementType().getSizeInBits() < 32)
3742     return false;
3743   if (!VT.is128BitVector())
3744     return false;
3745
3746   unsigned NumElts = VT.getVectorNumElements();
3747
3748   if (!isUndefOrEqual(Mask[0], NumElts))
3749     return false;
3750
3751   for (unsigned i = 1; i != NumElts; ++i)
3752     if (!isUndefOrEqual(Mask[i], i))
3753       return false;
3754
3755   return true;
3756 }
3757
3758 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3759 /// as permutations between 128-bit chunks or halves. As an example: this
3760 /// shuffle bellow:
3761 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3762 /// The first half comes from the second half of V1 and the second half from the
3763 /// the second half of V2.
3764 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3765   if (!HasAVX || !VT.is256BitVector())
3766     return false;
3767
3768   // The shuffle result is divided into half A and half B. In total the two
3769   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3770   // B must come from C, D, E or F.
3771   unsigned HalfSize = VT.getVectorNumElements()/2;
3772   bool MatchA = false, MatchB = false;
3773
3774   // Check if A comes from one of C, D, E, F.
3775   for (unsigned Half = 0; Half != 4; ++Half) {
3776     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3777       MatchA = true;
3778       break;
3779     }
3780   }
3781
3782   // Check if B comes from one of C, D, E, F.
3783   for (unsigned Half = 0; Half != 4; ++Half) {
3784     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3785       MatchB = true;
3786       break;
3787     }
3788   }
3789
3790   return MatchA && MatchB;
3791 }
3792
3793 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3794 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3795 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3796   EVT VT = SVOp->getValueType(0);
3797
3798   unsigned HalfSize = VT.getVectorNumElements()/2;
3799
3800   unsigned FstHalf = 0, SndHalf = 0;
3801   for (unsigned i = 0; i < HalfSize; ++i) {
3802     if (SVOp->getMaskElt(i) > 0) {
3803       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3804       break;
3805     }
3806   }
3807   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3808     if (SVOp->getMaskElt(i) > 0) {
3809       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3810       break;
3811     }
3812   }
3813
3814   return (FstHalf | (SndHalf << 4));
3815 }
3816
3817 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3819 /// Note that VPERMIL mask matching is different depending whether theunderlying
3820 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3821 /// to the same elements of the low, but to the higher half of the source.
3822 /// In VPERMILPD the two lanes could be shuffled independently of each other
3823 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3824 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3825   if (!HasAVX)
3826     return false;
3827
3828   unsigned NumElts = VT.getVectorNumElements();
3829   // Only match 256-bit with 32/64-bit types
3830   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3831     return false;
3832
3833   unsigned NumLanes = VT.getSizeInBits()/128;
3834   unsigned LaneSize = NumElts/NumLanes;
3835   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3836     for (unsigned i = 0; i != LaneSize; ++i) {
3837       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3838         return false;
3839       if (NumElts != 8 || l == 0)
3840         continue;
3841       // VPERMILPS handling
3842       if (Mask[i] < 0)
3843         continue;
3844       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3845         return false;
3846     }
3847   }
3848
3849   return true;
3850 }
3851
3852 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3853 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3854 /// element of vector 2 and the other elements to come from vector 1 in order.
3855 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3856                                bool V2IsSplat = false, bool V2IsUndef = false) {
3857   if (!VT.is128BitVector())
3858     return false;
3859
3860   unsigned NumOps = VT.getVectorNumElements();
3861   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3862     return false;
3863
3864   if (!isUndefOrEqual(Mask[0], 0))
3865     return false;
3866
3867   for (unsigned i = 1; i != NumOps; ++i)
3868     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3869           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3870           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3871       return false;
3872
3873   return true;
3874 }
3875
3876 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3878 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3879 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3880                            const X86Subtarget *Subtarget) {
3881   if (!Subtarget->hasSSE3())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3887       (VT.getSizeInBits() == 256 && NumElems != 8))
3888     return false;
3889
3890   // "i+1" is the value the indexed mask element must have
3891   for (unsigned i = 0; i != NumElems; i += 2)
3892     if (!isUndefOrEqual(Mask[i], i+1) ||
3893         !isUndefOrEqual(Mask[i+1], i+1))
3894       return false;
3895
3896   return true;
3897 }
3898
3899 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3901 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3902 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3903                            const X86Subtarget *Subtarget) {
3904   if (!Subtarget->hasSSE3())
3905     return false;
3906
3907   unsigned NumElems = VT.getVectorNumElements();
3908
3909   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3910       (VT.getSizeInBits() == 256 && NumElems != 8))
3911     return false;
3912
3913   // "i" is the value the indexed mask element must have
3914   for (unsigned i = 0; i != NumElems; i += 2)
3915     if (!isUndefOrEqual(Mask[i], i) ||
3916         !isUndefOrEqual(Mask[i+1], i))
3917       return false;
3918
3919   return true;
3920 }
3921
3922 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3923 /// specifies a shuffle of elements that is suitable for input to 256-bit
3924 /// version of MOVDDUP.
3925 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3926   if (!HasAVX || !VT.is256BitVector())
3927     return false;
3928
3929   unsigned NumElts = VT.getVectorNumElements();
3930   if (NumElts != 4)
3931     return false;
3932
3933   for (unsigned i = 0; i != NumElts/2; ++i)
3934     if (!isUndefOrEqual(Mask[i], 0))
3935       return false;
3936   for (unsigned i = NumElts/2; i != NumElts; ++i)
3937     if (!isUndefOrEqual(Mask[i], NumElts/2))
3938       return false;
3939   return true;
3940 }
3941
3942 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3943 /// specifies a shuffle of elements that is suitable for input to 128-bit
3944 /// version of MOVDDUP.
3945 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned e = VT.getVectorNumElements() / 2;
3950   for (unsigned i = 0; i != e; ++i)
3951     if (!isUndefOrEqual(Mask[i], i))
3952       return false;
3953   for (unsigned i = 0; i != e; ++i)
3954     if (!isUndefOrEqual(Mask[e+i], i))
3955       return false;
3956   return true;
3957 }
3958
3959 /// isVEXTRACTF128Index - Return true if the specified
3960 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3961 /// suitable for input to VEXTRACTF128.
3962 bool X86::isVEXTRACTF128Index(SDNode *N) {
3963   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3964     return false;
3965
3966   // The index should be aligned on a 128-bit boundary.
3967   uint64_t Index =
3968     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3969
3970   unsigned VL = N->getValueType(0).getVectorNumElements();
3971   unsigned VBits = N->getValueType(0).getSizeInBits();
3972   unsigned ElSize = VBits / VL;
3973   bool Result = (Index * ElSize) % 128 == 0;
3974
3975   return Result;
3976 }
3977
3978 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3979 /// operand specifies a subvector insert that is suitable for input to
3980 /// VINSERTF128.
3981 bool X86::isVINSERTF128Index(SDNode *N) {
3982   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3983     return false;
3984
3985   // The index should be aligned on a 128-bit boundary.
3986   uint64_t Index =
3987     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3988
3989   unsigned VL = N->getValueType(0).getVectorNumElements();
3990   unsigned VBits = N->getValueType(0).getSizeInBits();
3991   unsigned ElSize = VBits / VL;
3992   bool Result = (Index * ElSize) % 128 == 0;
3993
3994   return Result;
3995 }
3996
3997 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3998 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3999 /// Handles 128-bit and 256-bit.
4000 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4001   EVT VT = N->getValueType(0);
4002
4003   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4004          "Unsupported vector type for PSHUF/SHUFP");
4005
4006   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4007   // independently on 128-bit lanes.
4008   unsigned NumElts = VT.getVectorNumElements();
4009   unsigned NumLanes = VT.getSizeInBits()/128;
4010   unsigned NumLaneElts = NumElts/NumLanes;
4011
4012   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4013          "Only supports 2 or 4 elements per lane");
4014
4015   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4016   unsigned Mask = 0;
4017   for (unsigned i = 0; i != NumElts; ++i) {
4018     int Elt = N->getMaskElt(i);
4019     if (Elt < 0) continue;
4020     Elt &= NumLaneElts - 1;
4021     unsigned ShAmt = (i << Shift) % 8;
4022     Mask |= Elt << ShAmt;
4023   }
4024
4025   return Mask;
4026 }
4027
4028 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4029 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4030 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4031   EVT VT = N->getValueType(0);
4032
4033   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4034          "Unsupported vector type for PSHUFHW");
4035
4036   unsigned NumElts = VT.getVectorNumElements();
4037
4038   unsigned Mask = 0;
4039   for (unsigned l = 0; l != NumElts; l += 8) {
4040     // 8 nodes per lane, but we only care about the last 4.
4041     for (unsigned i = 0; i < 4; ++i) {
4042       int Elt = N->getMaskElt(l+i+4);
4043       if (Elt < 0) continue;
4044       Elt &= 0x3; // only 2-bits.
4045       Mask |= Elt << (i * 2);
4046     }
4047   }
4048
4049   return Mask;
4050 }
4051
4052 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4053 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4054 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4055   EVT VT = N->getValueType(0);
4056
4057   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4058          "Unsupported vector type for PSHUFHW");
4059
4060   unsigned NumElts = VT.getVectorNumElements();
4061
4062   unsigned Mask = 0;
4063   for (unsigned l = 0; l != NumElts; l += 8) {
4064     // 8 nodes per lane, but we only care about the first 4.
4065     for (unsigned i = 0; i < 4; ++i) {
4066       int Elt = N->getMaskElt(l+i);
4067       if (Elt < 0) continue;
4068       Elt &= 0x3; // only 2-bits
4069       Mask |= Elt << (i * 2);
4070     }
4071   }
4072
4073   return Mask;
4074 }
4075
4076 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4077 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4078 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4079   EVT VT = SVOp->getValueType(0);
4080   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4081
4082   unsigned NumElts = VT.getVectorNumElements();
4083   unsigned NumLanes = VT.getSizeInBits()/128;
4084   unsigned NumLaneElts = NumElts/NumLanes;
4085
4086   int Val = 0;
4087   unsigned i;
4088   for (i = 0; i != NumElts; ++i) {
4089     Val = SVOp->getMaskElt(i);
4090     if (Val >= 0)
4091       break;
4092   }
4093   if (Val >= (int)NumElts)
4094     Val -= NumElts - NumLaneElts;
4095
4096   assert(Val - i > 0 && "PALIGNR imm should be positive");
4097   return (Val - i) * EltSize;
4098 }
4099
4100 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4101 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4102 /// instructions.
4103 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4104   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4105     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4106
4107   uint64_t Index =
4108     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4109
4110   EVT VecVT = N->getOperand(0).getValueType();
4111   EVT ElVT = VecVT.getVectorElementType();
4112
4113   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4114   return Index / NumElemsPerChunk;
4115 }
4116
4117 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4118 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4119 /// instructions.
4120 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4121   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4122     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4123
4124   uint64_t Index =
4125     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4126
4127   EVT VecVT = N->getValueType(0);
4128   EVT ElVT = VecVT.getVectorElementType();
4129
4130   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4131   return Index / NumElemsPerChunk;
4132 }
4133
4134 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4135 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4136 /// Handles 256-bit.
4137 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4138   EVT VT = N->getValueType(0);
4139
4140   unsigned NumElts = VT.getVectorNumElements();
4141
4142   assert((VT.is256BitVector() && NumElts == 4) &&
4143          "Unsupported vector type for VPERMQ/VPERMPD");
4144
4145   unsigned Mask = 0;
4146   for (unsigned i = 0; i != NumElts; ++i) {
4147     int Elt = N->getMaskElt(i);
4148     if (Elt < 0)
4149       continue;
4150     Mask |= Elt << (i*2);
4151   }
4152
4153   return Mask;
4154 }
4155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4156 /// constant +0.0.
4157 bool X86::isZeroNode(SDValue Elt) {
4158   return ((isa<ConstantSDNode>(Elt) &&
4159            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4160           (isa<ConstantFPSDNode>(Elt) &&
4161            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4162 }
4163
4164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4165 /// their permute mask.
4166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4167                                     SelectionDAG &DAG) {
4168   EVT VT = SVOp->getValueType(0);
4169   unsigned NumElems = VT.getVectorNumElements();
4170   SmallVector<int, 8> MaskVec;
4171
4172   for (unsigned i = 0; i != NumElems; ++i) {
4173     int Idx = SVOp->getMaskElt(i);
4174     if (Idx >= 0) {
4175       if (Idx < (int)NumElems)
4176         Idx += NumElems;
4177       else
4178         Idx -= NumElems;
4179     }
4180     MaskVec.push_back(Idx);
4181   }
4182   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4183                               SVOp->getOperand(0), &MaskVec[0]);
4184 }
4185
4186 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4187 /// match movhlps. The lower half elements should come from upper half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order).
4190 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4191   if (!VT.is128BitVector())
4192     return false;
4193   if (VT.getVectorNumElements() != 4)
4194     return false;
4195   for (unsigned i = 0, e = 2; i != e; ++i)
4196     if (!isUndefOrEqual(Mask[i], i+2))
4197       return false;
4198   for (unsigned i = 2; i != 4; ++i)
4199     if (!isUndefOrEqual(Mask[i], i+4))
4200       return false;
4201   return true;
4202 }
4203
4204 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4205 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4206 /// required.
4207 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4208   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4209     return false;
4210   N = N->getOperand(0).getNode();
4211   if (!ISD::isNON_EXTLoad(N))
4212     return false;
4213   if (LD)
4214     *LD = cast<LoadSDNode>(N);
4215   return true;
4216 }
4217
4218 // Test whether the given value is a vector value which will be legalized
4219 // into a load.
4220 static bool WillBeConstantPoolLoad(SDNode *N) {
4221   if (N->getOpcode() != ISD::BUILD_VECTOR)
4222     return false;
4223
4224   // Check for any non-constant elements.
4225   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4226     switch (N->getOperand(i).getNode()->getOpcode()) {
4227     case ISD::UNDEF:
4228     case ISD::ConstantFP:
4229     case ISD::Constant:
4230       break;
4231     default:
4232       return false;
4233     }
4234
4235   // Vectors of all-zeros and all-ones are materialized with special
4236   // instructions rather than being loaded.
4237   return !ISD::isBuildVectorAllZeros(N) &&
4238          !ISD::isBuildVectorAllOnes(N);
4239 }
4240
4241 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4242 /// match movlp{s|d}. The lower half elements should come from lower half of
4243 /// V1 (and in order), and the upper half elements should come from the upper
4244 /// half of V2 (and in order). And since V1 will become the source of the
4245 /// MOVLP, it must be either a vector load or a scalar load to vector.
4246 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4247                                ArrayRef<int> Mask, EVT VT) {
4248   if (!VT.is128BitVector())
4249     return false;
4250
4251   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4252     return false;
4253   // Is V2 is a vector load, don't do this transformation. We will try to use
4254   // load folding shufps op.
4255   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4256     return false;
4257
4258   unsigned NumElems = VT.getVectorNumElements();
4259
4260   if (NumElems != 2 && NumElems != 4)
4261     return false;
4262   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4263     if (!isUndefOrEqual(Mask[i], i))
4264       return false;
4265   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4266     if (!isUndefOrEqual(Mask[i], i+NumElems))
4267       return false;
4268   return true;
4269 }
4270
4271 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4272 /// all the same.
4273 static bool isSplatVector(SDNode *N) {
4274   if (N->getOpcode() != ISD::BUILD_VECTOR)
4275     return false;
4276
4277   SDValue SplatValue = N->getOperand(0);
4278   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4279     if (N->getOperand(i) != SplatValue)
4280       return false;
4281   return true;
4282 }
4283
4284 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4285 /// to an zero vector.
4286 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4287 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4288   SDValue V1 = N->getOperand(0);
4289   SDValue V2 = N->getOperand(1);
4290   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4291   for (unsigned i = 0; i != NumElems; ++i) {
4292     int Idx = N->getMaskElt(i);
4293     if (Idx >= (int)NumElems) {
4294       unsigned Opc = V2.getOpcode();
4295       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4296         continue;
4297       if (Opc != ISD::BUILD_VECTOR ||
4298           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4299         return false;
4300     } else if (Idx >= 0) {
4301       unsigned Opc = V1.getOpcode();
4302       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4303         continue;
4304       if (Opc != ISD::BUILD_VECTOR ||
4305           !X86::isZeroNode(V1.getOperand(Idx)))
4306         return false;
4307     }
4308   }
4309   return true;
4310 }
4311
4312 /// getZeroVector - Returns a vector of specified type with all zero elements.
4313 ///
4314 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4315                              SelectionDAG &DAG, DebugLoc dl) {
4316   assert(VT.isVector() && "Expected a vector type");
4317   unsigned Size = VT.getSizeInBits();
4318
4319   // Always build SSE zero vectors as <4 x i32> bitcasted
4320   // to their dest type. This ensures they get CSE'd.
4321   SDValue Vec;
4322   if (Size == 128) {  // SSE
4323     if (Subtarget->hasSSE2()) {  // SSE2
4324       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4325       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4326     } else { // SSE1
4327       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4328       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4329     }
4330   } else if (Size == 256) { // AVX
4331     if (Subtarget->hasAVX2()) { // AVX2
4332       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4333       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4335     } else {
4336       // 256-bit logic and arithmetic instructions in AVX are all
4337       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4338       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4339       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4340       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4341     }
4342   } else
4343     llvm_unreachable("Unexpected vector type");
4344
4345   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4346 }
4347
4348 /// getOnesVector - Returns a vector of specified type with all bits set.
4349 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4350 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4351 /// Then bitcast to their original type, ensuring they get CSE'd.
4352 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4353                              DebugLoc dl) {
4354   assert(VT.isVector() && "Expected a vector type");
4355   unsigned Size = VT.getSizeInBits();
4356
4357   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4358   SDValue Vec;
4359   if (Size == 256) {
4360     if (HasAVX2) { // AVX2
4361       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4362       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4363     } else { // AVX
4364       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4365       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4366     }
4367   } else if (Size == 128) {
4368     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4369   } else
4370     llvm_unreachable("Unexpected vector type");
4371
4372   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4373 }
4374
4375 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4376 /// that point to V2 points to its first element.
4377 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4378   for (unsigned i = 0; i != NumElems; ++i) {
4379     if (Mask[i] > (int)NumElems) {
4380       Mask[i] = NumElems;
4381     }
4382   }
4383 }
4384
4385 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4386 /// operation of specified width.
4387 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4388                        SDValue V2) {
4389   unsigned NumElems = VT.getVectorNumElements();
4390   SmallVector<int, 8> Mask;
4391   Mask.push_back(NumElems);
4392   for (unsigned i = 1; i != NumElems; ++i)
4393     Mask.push_back(i);
4394   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4395 }
4396
4397 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4398 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4399                           SDValue V2) {
4400   unsigned NumElems = VT.getVectorNumElements();
4401   SmallVector<int, 8> Mask;
4402   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4403     Mask.push_back(i);
4404     Mask.push_back(i + NumElems);
4405   }
4406   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4407 }
4408
4409 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4410 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4411                           SDValue V2) {
4412   unsigned NumElems = VT.getVectorNumElements();
4413   SmallVector<int, 8> Mask;
4414   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4415     Mask.push_back(i + Half);
4416     Mask.push_back(i + NumElems + Half);
4417   }
4418   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4419 }
4420
4421 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4422 // a generic shuffle instruction because the target has no such instructions.
4423 // Generate shuffles which repeat i16 and i8 several times until they can be
4424 // represented by v4f32 and then be manipulated by target suported shuffles.
4425 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4426   EVT VT = V.getValueType();
4427   int NumElems = VT.getVectorNumElements();
4428   DebugLoc dl = V.getDebugLoc();
4429
4430   while (NumElems > 4) {
4431     if (EltNo < NumElems/2) {
4432       V = getUnpackl(DAG, dl, VT, V, V);
4433     } else {
4434       V = getUnpackh(DAG, dl, VT, V, V);
4435       EltNo -= NumElems/2;
4436     }
4437     NumElems >>= 1;
4438   }
4439   return V;
4440 }
4441
4442 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4443 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4444   EVT VT = V.getValueType();
4445   DebugLoc dl = V.getDebugLoc();
4446   unsigned Size = VT.getSizeInBits();
4447
4448   if (Size == 128) {
4449     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4450     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4451     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4452                              &SplatMask[0]);
4453   } else if (Size == 256) {
4454     // To use VPERMILPS to splat scalars, the second half of indicies must
4455     // refer to the higher part, which is a duplication of the lower one,
4456     // because VPERMILPS can only handle in-lane permutations.
4457     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4458                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4459
4460     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4461     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4462                              &SplatMask[0]);
4463   } else
4464     llvm_unreachable("Vector size not supported");
4465
4466   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4467 }
4468
4469 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4470 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4471   EVT SrcVT = SV->getValueType(0);
4472   SDValue V1 = SV->getOperand(0);
4473   DebugLoc dl = SV->getDebugLoc();
4474
4475   int EltNo = SV->getSplatIndex();
4476   int NumElems = SrcVT.getVectorNumElements();
4477   unsigned Size = SrcVT.getSizeInBits();
4478
4479   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4480           "Unknown how to promote splat for type");
4481
4482   // Extract the 128-bit part containing the splat element and update
4483   // the splat element index when it refers to the higher register.
4484   if (Size == 256) {
4485     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4486     if (EltNo >= NumElems/2)
4487       EltNo -= NumElems/2;
4488   }
4489
4490   // All i16 and i8 vector types can't be used directly by a generic shuffle
4491   // instruction because the target has no such instruction. Generate shuffles
4492   // which repeat i16 and i8 several times until they fit in i32, and then can
4493   // be manipulated by target suported shuffles.
4494   EVT EltVT = SrcVT.getVectorElementType();
4495   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4496     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4497
4498   // Recreate the 256-bit vector and place the same 128-bit vector
4499   // into the low and high part. This is necessary because we want
4500   // to use VPERM* to shuffle the vectors
4501   if (Size == 256) {
4502     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4503   }
4504
4505   return getLegalSplat(DAG, V1, EltNo);
4506 }
4507
4508 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4509 /// vector of zero or undef vector.  This produces a shuffle where the low
4510 /// element of V2 is swizzled into the zero/undef vector, landing at element
4511 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4512 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4513                                            bool IsZero,
4514                                            const X86Subtarget *Subtarget,
4515                                            SelectionDAG &DAG) {
4516   EVT VT = V2.getValueType();
4517   SDValue V1 = IsZero
4518     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4519   unsigned NumElems = VT.getVectorNumElements();
4520   SmallVector<int, 16> MaskVec;
4521   for (unsigned i = 0; i != NumElems; ++i)
4522     // If this is the insertion idx, put the low elt of V2 here.
4523     MaskVec.push_back(i == Idx ? NumElems : i);
4524   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4525 }
4526
4527 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4528 /// target specific opcode. Returns true if the Mask could be calculated.
4529 /// Sets IsUnary to true if only uses one source.
4530 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4531                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4532   unsigned NumElems = VT.getVectorNumElements();
4533   SDValue ImmN;
4534
4535   IsUnary = false;
4536   switch(N->getOpcode()) {
4537   case X86ISD::SHUFP:
4538     ImmN = N->getOperand(N->getNumOperands()-1);
4539     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4540     break;
4541   case X86ISD::UNPCKH:
4542     DecodeUNPCKHMask(VT, Mask);
4543     break;
4544   case X86ISD::UNPCKL:
4545     DecodeUNPCKLMask(VT, Mask);
4546     break;
4547   case X86ISD::MOVHLPS:
4548     DecodeMOVHLPSMask(NumElems, Mask);
4549     break;
4550   case X86ISD::MOVLHPS:
4551     DecodeMOVLHPSMask(NumElems, Mask);
4552     break;
4553   case X86ISD::PSHUFD:
4554   case X86ISD::VPERMILP:
4555     ImmN = N->getOperand(N->getNumOperands()-1);
4556     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4557     IsUnary = true;
4558     break;
4559   case X86ISD::PSHUFHW:
4560     ImmN = N->getOperand(N->getNumOperands()-1);
4561     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4562     IsUnary = true;
4563     break;
4564   case X86ISD::PSHUFLW:
4565     ImmN = N->getOperand(N->getNumOperands()-1);
4566     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4567     IsUnary = true;
4568     break;
4569   case X86ISD::VPERMI:
4570     ImmN = N->getOperand(N->getNumOperands()-1);
4571     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4572     IsUnary = true;
4573     break;
4574   case X86ISD::MOVSS:
4575   case X86ISD::MOVSD: {
4576     // The index 0 always comes from the first element of the second source,
4577     // this is why MOVSS and MOVSD are used in the first place. The other
4578     // elements come from the other positions of the first source vector
4579     Mask.push_back(NumElems);
4580     for (unsigned i = 1; i != NumElems; ++i) {
4581       Mask.push_back(i);
4582     }
4583     break;
4584   }
4585   case X86ISD::VPERM2X128:
4586     ImmN = N->getOperand(N->getNumOperands()-1);
4587     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4588     if (Mask.empty()) return false;
4589     break;
4590   case X86ISD::MOVDDUP:
4591   case X86ISD::MOVLHPD:
4592   case X86ISD::MOVLPD:
4593   case X86ISD::MOVLPS:
4594   case X86ISD::MOVSHDUP:
4595   case X86ISD::MOVSLDUP:
4596   case X86ISD::PALIGN:
4597     // Not yet implemented
4598     return false;
4599   default: llvm_unreachable("unknown target shuffle node");
4600   }
4601
4602   return true;
4603 }
4604
4605 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4606 /// element of the result of the vector shuffle.
4607 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4608                                    unsigned Depth) {
4609   if (Depth == 6)
4610     return SDValue();  // Limit search depth.
4611
4612   SDValue V = SDValue(N, 0);
4613   EVT VT = V.getValueType();
4614   unsigned Opcode = V.getOpcode();
4615
4616   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4617   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4618     int Elt = SV->getMaskElt(Index);
4619
4620     if (Elt < 0)
4621       return DAG.getUNDEF(VT.getVectorElementType());
4622
4623     unsigned NumElems = VT.getVectorNumElements();
4624     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4625                                          : SV->getOperand(1);
4626     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4627   }
4628
4629   // Recurse into target specific vector shuffles to find scalars.
4630   if (isTargetShuffle(Opcode)) {
4631     MVT ShufVT = V.getValueType().getSimpleVT();
4632     unsigned NumElems = ShufVT.getVectorNumElements();
4633     SmallVector<int, 16> ShuffleMask;
4634     SDValue ImmN;
4635     bool IsUnary;
4636
4637     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4638       return SDValue();
4639
4640     int Elt = ShuffleMask[Index];
4641     if (Elt < 0)
4642       return DAG.getUNDEF(ShufVT.getVectorElementType());
4643
4644     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4645                                          : N->getOperand(1);
4646     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4647                                Depth+1);
4648   }
4649
4650   // Actual nodes that may contain scalar elements
4651   if (Opcode == ISD::BITCAST) {
4652     V = V.getOperand(0);
4653     EVT SrcVT = V.getValueType();
4654     unsigned NumElems = VT.getVectorNumElements();
4655
4656     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4657       return SDValue();
4658   }
4659
4660   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4661     return (Index == 0) ? V.getOperand(0)
4662                         : DAG.getUNDEF(VT.getVectorElementType());
4663
4664   if (V.getOpcode() == ISD::BUILD_VECTOR)
4665     return V.getOperand(Index);
4666
4667   return SDValue();
4668 }
4669
4670 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4671 /// shuffle operation which come from a consecutively from a zero. The
4672 /// search can start in two different directions, from left or right.
4673 static
4674 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4675                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4676   unsigned i;
4677   for (i = 0; i != NumElems; ++i) {
4678     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4679     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4680     if (!(Elt.getNode() &&
4681          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4682       break;
4683   }
4684
4685   return i;
4686 }
4687
4688 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4689 /// correspond consecutively to elements from one of the vector operands,
4690 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4691 static
4692 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4693                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4694                               unsigned NumElems, unsigned &OpNum) {
4695   bool SeenV1 = false;
4696   bool SeenV2 = false;
4697
4698   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4699     int Idx = SVOp->getMaskElt(i);
4700     // Ignore undef indicies
4701     if (Idx < 0)
4702       continue;
4703
4704     if (Idx < (int)NumElems)
4705       SeenV1 = true;
4706     else
4707       SeenV2 = true;
4708
4709     // Only accept consecutive elements from the same vector
4710     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4711       return false;
4712   }
4713
4714   OpNum = SeenV1 ? 0 : 1;
4715   return true;
4716 }
4717
4718 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4719 /// logical left shift of a vector.
4720 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4721                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4722   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4723   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4724               false /* check zeros from right */, DAG);
4725   unsigned OpSrc;
4726
4727   if (!NumZeros)
4728     return false;
4729
4730   // Considering the elements in the mask that are not consecutive zeros,
4731   // check if they consecutively come from only one of the source vectors.
4732   //
4733   //               V1 = {X, A, B, C}     0
4734   //                         \  \  \    /
4735   //   vector_shuffle V1, V2 <1, 2, 3, X>
4736   //
4737   if (!isShuffleMaskConsecutive(SVOp,
4738             0,                   // Mask Start Index
4739             NumElems-NumZeros,   // Mask End Index(exclusive)
4740             NumZeros,            // Where to start looking in the src vector
4741             NumElems,            // Number of elements in vector
4742             OpSrc))              // Which source operand ?
4743     return false;
4744
4745   isLeft = false;
4746   ShAmt = NumZeros;
4747   ShVal = SVOp->getOperand(OpSrc);
4748   return true;
4749 }
4750
4751 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4752 /// logical left shift of a vector.
4753 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4754                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4755   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4756   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4757               true /* check zeros from left */, DAG);
4758   unsigned OpSrc;
4759
4760   if (!NumZeros)
4761     return false;
4762
4763   // Considering the elements in the mask that are not consecutive zeros,
4764   // check if they consecutively come from only one of the source vectors.
4765   //
4766   //                           0    { A, B, X, X } = V2
4767   //                          / \    /  /
4768   //   vector_shuffle V1, V2 <X, X, 4, 5>
4769   //
4770   if (!isShuffleMaskConsecutive(SVOp,
4771             NumZeros,     // Mask Start Index
4772             NumElems,     // Mask End Index(exclusive)
4773             0,            // Where to start looking in the src vector
4774             NumElems,     // Number of elements in vector
4775             OpSrc))       // Which source operand ?
4776     return false;
4777
4778   isLeft = true;
4779   ShAmt = NumZeros;
4780   ShVal = SVOp->getOperand(OpSrc);
4781   return true;
4782 }
4783
4784 /// isVectorShift - Returns true if the shuffle can be implemented as a
4785 /// logical left or right shift of a vector.
4786 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788   // Although the logic below support any bitwidth size, there are no
4789   // shift instructions which handle more than 128-bit vectors.
4790   if (!SVOp->getValueType(0).is128BitVector())
4791     return false;
4792
4793   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4794       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4795     return true;
4796
4797   return false;
4798 }
4799
4800 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4801 ///
4802 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4803                                        unsigned NumNonZero, unsigned NumZero,
4804                                        SelectionDAG &DAG,
4805                                        const X86Subtarget* Subtarget,
4806                                        const TargetLowering &TLI) {
4807   if (NumNonZero > 8)
4808     return SDValue();
4809
4810   DebugLoc dl = Op.getDebugLoc();
4811   SDValue V(0, 0);
4812   bool First = true;
4813   for (unsigned i = 0; i < 16; ++i) {
4814     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4815     if (ThisIsNonZero && First) {
4816       if (NumZero)
4817         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4818       else
4819         V = DAG.getUNDEF(MVT::v8i16);
4820       First = false;
4821     }
4822
4823     if ((i & 1) != 0) {
4824       SDValue ThisElt(0, 0), LastElt(0, 0);
4825       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4826       if (LastIsNonZero) {
4827         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4828                               MVT::i16, Op.getOperand(i-1));
4829       }
4830       if (ThisIsNonZero) {
4831         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4832         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4833                               ThisElt, DAG.getConstant(8, MVT::i8));
4834         if (LastIsNonZero)
4835           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4836       } else
4837         ThisElt = LastElt;
4838
4839       if (ThisElt.getNode())
4840         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4841                         DAG.getIntPtrConstant(i/2));
4842     }
4843   }
4844
4845   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4846 }
4847
4848 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4849 ///
4850 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4851                                      unsigned NumNonZero, unsigned NumZero,
4852                                      SelectionDAG &DAG,
4853                                      const X86Subtarget* Subtarget,
4854                                      const TargetLowering &TLI) {
4855   if (NumNonZero > 4)
4856     return SDValue();
4857
4858   DebugLoc dl = Op.getDebugLoc();
4859   SDValue V(0, 0);
4860   bool First = true;
4861   for (unsigned i = 0; i < 8; ++i) {
4862     bool isNonZero = (NonZeros & (1 << i)) != 0;
4863     if (isNonZero) {
4864       if (First) {
4865         if (NumZero)
4866           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4867         else
4868           V = DAG.getUNDEF(MVT::v8i16);
4869         First = false;
4870       }
4871       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4872                       MVT::v8i16, V, Op.getOperand(i),
4873                       DAG.getIntPtrConstant(i));
4874     }
4875   }
4876
4877   return V;
4878 }
4879
4880 /// getVShift - Return a vector logical shift node.
4881 ///
4882 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4883                          unsigned NumBits, SelectionDAG &DAG,
4884                          const TargetLowering &TLI, DebugLoc dl) {
4885   assert(VT.is128BitVector() && "Unknown type for VShift");
4886   EVT ShVT = MVT::v2i64;
4887   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4888   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4889   return DAG.getNode(ISD::BITCAST, dl, VT,
4890                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4891                              DAG.getConstant(NumBits,
4892                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4893 }
4894
4895 SDValue
4896 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4897                                           SelectionDAG &DAG) const {
4898
4899   // Check if the scalar load can be widened into a vector load. And if
4900   // the address is "base + cst" see if the cst can be "absorbed" into
4901   // the shuffle mask.
4902   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4903     SDValue Ptr = LD->getBasePtr();
4904     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4905       return SDValue();
4906     EVT PVT = LD->getValueType(0);
4907     if (PVT != MVT::i32 && PVT != MVT::f32)
4908       return SDValue();
4909
4910     int FI = -1;
4911     int64_t Offset = 0;
4912     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4913       FI = FINode->getIndex();
4914       Offset = 0;
4915     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4916                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4917       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4918       Offset = Ptr.getConstantOperandVal(1);
4919       Ptr = Ptr.getOperand(0);
4920     } else {
4921       return SDValue();
4922     }
4923
4924     // FIXME: 256-bit vector instructions don't require a strict alignment,
4925     // improve this code to support it better.
4926     unsigned RequiredAlign = VT.getSizeInBits()/8;
4927     SDValue Chain = LD->getChain();
4928     // Make sure the stack object alignment is at least 16 or 32.
4929     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4930     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4931       if (MFI->isFixedObjectIndex(FI)) {
4932         // Can't change the alignment. FIXME: It's possible to compute
4933         // the exact stack offset and reference FI + adjust offset instead.
4934         // If someone *really* cares about this. That's the way to implement it.
4935         return SDValue();
4936       } else {
4937         MFI->setObjectAlignment(FI, RequiredAlign);
4938       }
4939     }
4940
4941     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4942     // Ptr + (Offset & ~15).
4943     if (Offset < 0)
4944       return SDValue();
4945     if ((Offset % RequiredAlign) & 3)
4946       return SDValue();
4947     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4948     if (StartOffset)
4949       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4950                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4951
4952     int EltNo = (Offset - StartOffset) >> 2;
4953     unsigned NumElems = VT.getVectorNumElements();
4954
4955     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4956     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4957                              LD->getPointerInfo().getWithOffset(StartOffset),
4958                              false, false, false, 0);
4959
4960     SmallVector<int, 8> Mask;
4961     for (unsigned i = 0; i != NumElems; ++i)
4962       Mask.push_back(EltNo);
4963
4964     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4965   }
4966
4967   return SDValue();
4968 }
4969
4970 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4971 /// vector of type 'VT', see if the elements can be replaced by a single large
4972 /// load which has the same value as a build_vector whose operands are 'elts'.
4973 ///
4974 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4975 ///
4976 /// FIXME: we'd also like to handle the case where the last elements are zero
4977 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4978 /// There's even a handy isZeroNode for that purpose.
4979 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4980                                         DebugLoc &DL, SelectionDAG &DAG) {
4981   EVT EltVT = VT.getVectorElementType();
4982   unsigned NumElems = Elts.size();
4983
4984   LoadSDNode *LDBase = NULL;
4985   unsigned LastLoadedElt = -1U;
4986
4987   // For each element in the initializer, see if we've found a load or an undef.
4988   // If we don't find an initial load element, or later load elements are
4989   // non-consecutive, bail out.
4990   for (unsigned i = 0; i < NumElems; ++i) {
4991     SDValue Elt = Elts[i];
4992
4993     if (!Elt.getNode() ||
4994         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4995       return SDValue();
4996     if (!LDBase) {
4997       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4998         return SDValue();
4999       LDBase = cast<LoadSDNode>(Elt.getNode());
5000       LastLoadedElt = i;
5001       continue;
5002     }
5003     if (Elt.getOpcode() == ISD::UNDEF)
5004       continue;
5005
5006     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5007     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5008       return SDValue();
5009     LastLoadedElt = i;
5010   }
5011
5012   // If we have found an entire vector of loads and undefs, then return a large
5013   // load of the entire vector width starting at the base pointer.  If we found
5014   // consecutive loads for the low half, generate a vzext_load node.
5015   if (LastLoadedElt == NumElems - 1) {
5016     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5017       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5018                          LDBase->getPointerInfo(),
5019                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5020                          LDBase->isInvariant(), 0);
5021     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5022                        LDBase->getPointerInfo(),
5023                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5024                        LDBase->isInvariant(), LDBase->getAlignment());
5025   }
5026   if (NumElems == 4 && LastLoadedElt == 1 &&
5027       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5028     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5029     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5030     SDValue ResNode =
5031         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5032                                 LDBase->getPointerInfo(),
5033                                 LDBase->getAlignment(),
5034                                 false/*isVolatile*/, true/*ReadMem*/,
5035                                 false/*WriteMem*/);
5036
5037     // Make sure the newly-created LOAD is in the same position as LDBase in
5038     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5039     // update uses of LDBase's output chain to use the TokenFactor.
5040     if (LDBase->hasAnyUseOfValue(1)) {
5041       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5042                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5043       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5044       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5045                              SDValue(ResNode.getNode(), 1));
5046     }
5047
5048     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5049   }
5050   return SDValue();
5051 }
5052
5053 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5054 /// to generate a splat value for the following cases:
5055 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5056 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5057 /// a scalar load, or a constant.
5058 /// The VBROADCAST node is returned when a pattern is found,
5059 /// or SDValue() otherwise.
5060 SDValue
5061 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5062   if (!Subtarget->hasAVX())
5063     return SDValue();
5064
5065   EVT VT = Op.getValueType();
5066   DebugLoc dl = Op.getDebugLoc();
5067
5068   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5069          "Unsupported vector type for broadcast.");
5070
5071   SDValue Ld;
5072   bool ConstSplatVal;
5073
5074   switch (Op.getOpcode()) {
5075     default:
5076       // Unknown pattern found.
5077       return SDValue();
5078
5079     case ISD::BUILD_VECTOR: {
5080       // The BUILD_VECTOR node must be a splat.
5081       if (!isSplatVector(Op.getNode()))
5082         return SDValue();
5083
5084       Ld = Op.getOperand(0);
5085       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5086                      Ld.getOpcode() == ISD::ConstantFP);
5087
5088       // The suspected load node has several users. Make sure that all
5089       // of its users are from the BUILD_VECTOR node.
5090       // Constants may have multiple users.
5091       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5092         return SDValue();
5093       break;
5094     }
5095
5096     case ISD::VECTOR_SHUFFLE: {
5097       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5098
5099       // Shuffles must have a splat mask where the first element is
5100       // broadcasted.
5101       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5102         return SDValue();
5103
5104       SDValue Sc = Op.getOperand(0);
5105       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5106           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5107
5108         if (!Subtarget->hasAVX2())
5109           return SDValue();
5110
5111         // Use the register form of the broadcast instruction available on AVX2.
5112         if (VT.is256BitVector())
5113           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5114         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5115       }
5116
5117       Ld = Sc.getOperand(0);
5118       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5119                        Ld.getOpcode() == ISD::ConstantFP);
5120
5121       // The scalar_to_vector node and the suspected
5122       // load node must have exactly one user.
5123       // Constants may have multiple users.
5124       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5125         return SDValue();
5126       break;
5127     }
5128   }
5129
5130   bool Is256 = VT.is256BitVector();
5131
5132   // Handle the broadcasting a single constant scalar from the constant pool
5133   // into a vector. On Sandybridge it is still better to load a constant vector
5134   // from the constant pool and not to broadcast it from a scalar.
5135   if (ConstSplatVal && Subtarget->hasAVX2()) {
5136     EVT CVT = Ld.getValueType();
5137     assert(!CVT.isVector() && "Must not broadcast a vector type");
5138     unsigned ScalarSize = CVT.getSizeInBits();
5139
5140     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5141       const Constant *C = 0;
5142       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5143         C = CI->getConstantIntValue();
5144       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5145         C = CF->getConstantFPValue();
5146
5147       assert(C && "Invalid constant type");
5148
5149       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5150       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5151       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5152                        MachinePointerInfo::getConstantPool(),
5153                        false, false, false, Alignment);
5154
5155       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5156     }
5157   }
5158
5159   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5160   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5161
5162   // Handle AVX2 in-register broadcasts.
5163   if (!IsLoad && Subtarget->hasAVX2() &&
5164       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5165     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5166
5167   // The scalar source must be a normal load.
5168   if (!IsLoad)
5169     return SDValue();
5170
5171   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5172     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5173
5174   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5175   // double since there is no vbroadcastsd xmm
5176   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5177     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5178       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5179   }
5180
5181   // Unsupported broadcast.
5182   return SDValue();
5183 }
5184
5185 SDValue
5186 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5187   EVT VT = Op.getValueType();
5188
5189   // Skip if insert_vec_elt is not supported.
5190   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5191     return SDValue();
5192
5193   DebugLoc DL = Op.getDebugLoc();
5194   unsigned NumElems = Op.getNumOperands();
5195
5196   SDValue VecIn1;
5197   SDValue VecIn2;
5198   SmallVector<unsigned, 4> InsertIndices;
5199   SmallVector<int, 8> Mask(NumElems, -1);
5200
5201   for (unsigned i = 0; i != NumElems; ++i) {
5202     unsigned Opc = Op.getOperand(i).getOpcode();
5203
5204     if (Opc == ISD::UNDEF)
5205       continue;
5206
5207     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5208       // Quit if more than 1 elements need inserting.
5209       if (InsertIndices.size() > 1)
5210         return SDValue();
5211
5212       InsertIndices.push_back(i);
5213       continue;
5214     }
5215
5216     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5217     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5218
5219     // Quit if extracted from vector of different type.
5220     if (ExtractedFromVec.getValueType() != VT)
5221       return SDValue();
5222
5223     // Quit if non-constant index.
5224     if (!isa<ConstantSDNode>(ExtIdx))
5225       return SDValue();
5226
5227     if (VecIn1.getNode() == 0)
5228       VecIn1 = ExtractedFromVec;
5229     else if (VecIn1 != ExtractedFromVec) {
5230       if (VecIn2.getNode() == 0)
5231         VecIn2 = ExtractedFromVec;
5232       else if (VecIn2 != ExtractedFromVec)
5233         // Quit if more than 2 vectors to shuffle
5234         return SDValue();
5235     }
5236
5237     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5238
5239     if (ExtractedFromVec == VecIn1)
5240       Mask[i] = Idx;
5241     else if (ExtractedFromVec == VecIn2)
5242       Mask[i] = Idx + NumElems;
5243   }
5244
5245   if (VecIn1.getNode() == 0)
5246     return SDValue();
5247
5248   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5249   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5250   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5251     unsigned Idx = InsertIndices[i];
5252     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5253                      DAG.getIntPtrConstant(Idx));
5254   }
5255
5256   return NV;
5257 }
5258
5259 SDValue
5260 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5261   DebugLoc dl = Op.getDebugLoc();
5262
5263   EVT VT = Op.getValueType();
5264   EVT ExtVT = VT.getVectorElementType();
5265   unsigned NumElems = Op.getNumOperands();
5266
5267   // Vectors containing all zeros can be matched by pxor and xorps later
5268   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5269     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5270     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5271     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5272       return Op;
5273
5274     return getZeroVector(VT, Subtarget, DAG, dl);
5275   }
5276
5277   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5278   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5279   // vpcmpeqd on 256-bit vectors.
5280   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5281     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5282       return Op;
5283
5284     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5285   }
5286
5287   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5288   if (Broadcast.getNode())
5289     return Broadcast;
5290
5291   unsigned EVTBits = ExtVT.getSizeInBits();
5292
5293   unsigned NumZero  = 0;
5294   unsigned NumNonZero = 0;
5295   unsigned NonZeros = 0;
5296   bool IsAllConstants = true;
5297   SmallSet<SDValue, 8> Values;
5298   for (unsigned i = 0; i < NumElems; ++i) {
5299     SDValue Elt = Op.getOperand(i);
5300     if (Elt.getOpcode() == ISD::UNDEF)
5301       continue;
5302     Values.insert(Elt);
5303     if (Elt.getOpcode() != ISD::Constant &&
5304         Elt.getOpcode() != ISD::ConstantFP)
5305       IsAllConstants = false;
5306     if (X86::isZeroNode(Elt))
5307       NumZero++;
5308     else {
5309       NonZeros |= (1 << i);
5310       NumNonZero++;
5311     }
5312   }
5313
5314   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5315   if (NumNonZero == 0)
5316     return DAG.getUNDEF(VT);
5317
5318   // Special case for single non-zero, non-undef, element.
5319   if (NumNonZero == 1) {
5320     unsigned Idx = CountTrailingZeros_32(NonZeros);
5321     SDValue Item = Op.getOperand(Idx);
5322
5323     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5324     // the value are obviously zero, truncate the value to i32 and do the
5325     // insertion that way.  Only do this if the value is non-constant or if the
5326     // value is a constant being inserted into element 0.  It is cheaper to do
5327     // a constant pool load than it is to do a movd + shuffle.
5328     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5329         (!IsAllConstants || Idx == 0)) {
5330       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5331         // Handle SSE only.
5332         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5333         EVT VecVT = MVT::v4i32;
5334         unsigned VecElts = 4;
5335
5336         // Truncate the value (which may itself be a constant) to i32, and
5337         // convert it to a vector with movd (S2V+shuffle to zero extend).
5338         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5339         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5340         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5341
5342         // Now we have our 32-bit value zero extended in the low element of
5343         // a vector.  If Idx != 0, swizzle it into place.
5344         if (Idx != 0) {
5345           SmallVector<int, 4> Mask;
5346           Mask.push_back(Idx);
5347           for (unsigned i = 1; i != VecElts; ++i)
5348             Mask.push_back(i);
5349           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5350                                       &Mask[0]);
5351         }
5352         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5353       }
5354     }
5355
5356     // If we have a constant or non-constant insertion into the low element of
5357     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5358     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5359     // depending on what the source datatype is.
5360     if (Idx == 0) {
5361       if (NumZero == 0)
5362         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5363
5364       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5365           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5366         if (VT.is256BitVector()) {
5367           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5368           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5369                              Item, DAG.getIntPtrConstant(0));
5370         }
5371         assert(VT.is128BitVector() && "Expected an SSE value type!");
5372         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5373         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5374         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5375       }
5376
5377       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5378         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5379         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5380         if (VT.is256BitVector()) {
5381           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5382           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5383         } else {
5384           assert(VT.is128BitVector() && "Expected an SSE value type!");
5385           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5386         }
5387         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5388       }
5389     }
5390
5391     // Is it a vector logical left shift?
5392     if (NumElems == 2 && Idx == 1 &&
5393         X86::isZeroNode(Op.getOperand(0)) &&
5394         !X86::isZeroNode(Op.getOperand(1))) {
5395       unsigned NumBits = VT.getSizeInBits();
5396       return getVShift(true, VT,
5397                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5398                                    VT, Op.getOperand(1)),
5399                        NumBits/2, DAG, *this, dl);
5400     }
5401
5402     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5403       return SDValue();
5404
5405     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5406     // is a non-constant being inserted into an element other than the low one,
5407     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5408     // movd/movss) to move this into the low element, then shuffle it into
5409     // place.
5410     if (EVTBits == 32) {
5411       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5412
5413       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5414       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5415       SmallVector<int, 8> MaskVec;
5416       for (unsigned i = 0; i != NumElems; ++i)
5417         MaskVec.push_back(i == Idx ? 0 : 1);
5418       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5419     }
5420   }
5421
5422   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5423   if (Values.size() == 1) {
5424     if (EVTBits == 32) {
5425       // Instead of a shuffle like this:
5426       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5427       // Check if it's possible to issue this instead.
5428       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5429       unsigned Idx = CountTrailingZeros_32(NonZeros);
5430       SDValue Item = Op.getOperand(Idx);
5431       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5432         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5433     }
5434     return SDValue();
5435   }
5436
5437   // A vector full of immediates; various special cases are already
5438   // handled, so this is best done with a single constant-pool load.
5439   if (IsAllConstants)
5440     return SDValue();
5441
5442   // For AVX-length vectors, build the individual 128-bit pieces and use
5443   // shuffles to put them in place.
5444   if (VT.is256BitVector()) {
5445     SmallVector<SDValue, 32> V;
5446     for (unsigned i = 0; i != NumElems; ++i)
5447       V.push_back(Op.getOperand(i));
5448
5449     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5450
5451     // Build both the lower and upper subvector.
5452     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5453     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5454                                 NumElems/2);
5455
5456     // Recreate the wider vector with the lower and upper part.
5457     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5458   }
5459
5460   // Let legalizer expand 2-wide build_vectors.
5461   if (EVTBits == 64) {
5462     if (NumNonZero == 1) {
5463       // One half is zero or undef.
5464       unsigned Idx = CountTrailingZeros_32(NonZeros);
5465       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5466                                  Op.getOperand(Idx));
5467       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5468     }
5469     return SDValue();
5470   }
5471
5472   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5473   if (EVTBits == 8 && NumElems == 16) {
5474     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5475                                         Subtarget, *this);
5476     if (V.getNode()) return V;
5477   }
5478
5479   if (EVTBits == 16 && NumElems == 8) {
5480     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5481                                       Subtarget, *this);
5482     if (V.getNode()) return V;
5483   }
5484
5485   // If element VT is == 32 bits, turn it into a number of shuffles.
5486   SmallVector<SDValue, 8> V(NumElems);
5487   if (NumElems == 4 && NumZero > 0) {
5488     for (unsigned i = 0; i < 4; ++i) {
5489       bool isZero = !(NonZeros & (1 << i));
5490       if (isZero)
5491         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5492       else
5493         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5494     }
5495
5496     for (unsigned i = 0; i < 2; ++i) {
5497       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5498         default: break;
5499         case 0:
5500           V[i] = V[i*2];  // Must be a zero vector.
5501           break;
5502         case 1:
5503           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5504           break;
5505         case 2:
5506           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5507           break;
5508         case 3:
5509           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5510           break;
5511       }
5512     }
5513
5514     bool Reverse1 = (NonZeros & 0x3) == 2;
5515     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5516     int MaskVec[] = {
5517       Reverse1 ? 1 : 0,
5518       Reverse1 ? 0 : 1,
5519       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5520       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5521     };
5522     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5523   }
5524
5525   if (Values.size() > 1 && VT.is128BitVector()) {
5526     // Check for a build vector of consecutive loads.
5527     for (unsigned i = 0; i < NumElems; ++i)
5528       V[i] = Op.getOperand(i);
5529
5530     // Check for elements which are consecutive loads.
5531     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5532     if (LD.getNode())
5533       return LD;
5534
5535     // Check for a build vector from mostly shuffle plus few inserting.
5536     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5537     if (Sh.getNode())
5538       return Sh;
5539
5540     // For SSE 4.1, use insertps to put the high elements into the low element.
5541     if (getSubtarget()->hasSSE41()) {
5542       SDValue Result;
5543       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5544         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5545       else
5546         Result = DAG.getUNDEF(VT);
5547
5548       for (unsigned i = 1; i < NumElems; ++i) {
5549         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5550         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5551                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5552       }
5553       return Result;
5554     }
5555
5556     // Otherwise, expand into a number of unpckl*, start by extending each of
5557     // our (non-undef) elements to the full vector width with the element in the
5558     // bottom slot of the vector (which generates no code for SSE).
5559     for (unsigned i = 0; i < NumElems; ++i) {
5560       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5561         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5562       else
5563         V[i] = DAG.getUNDEF(VT);
5564     }
5565
5566     // Next, we iteratively mix elements, e.g. for v4f32:
5567     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5568     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5569     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5570     unsigned EltStride = NumElems >> 1;
5571     while (EltStride != 0) {
5572       for (unsigned i = 0; i < EltStride; ++i) {
5573         // If V[i+EltStride] is undef and this is the first round of mixing,
5574         // then it is safe to just drop this shuffle: V[i] is already in the
5575         // right place, the one element (since it's the first round) being
5576         // inserted as undef can be dropped.  This isn't safe for successive
5577         // rounds because they will permute elements within both vectors.
5578         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5579             EltStride == NumElems/2)
5580           continue;
5581
5582         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5583       }
5584       EltStride >>= 1;
5585     }
5586     return V[0];
5587   }
5588   return SDValue();
5589 }
5590
5591 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5592 // to create 256-bit vectors from two other 128-bit ones.
5593 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5594   DebugLoc dl = Op.getDebugLoc();
5595   EVT ResVT = Op.getValueType();
5596
5597   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5598
5599   SDValue V1 = Op.getOperand(0);
5600   SDValue V2 = Op.getOperand(1);
5601   unsigned NumElems = ResVT.getVectorNumElements();
5602
5603   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5604 }
5605
5606 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5607   assert(Op.getNumOperands() == 2);
5608
5609   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5610   // from two other 128-bit ones.
5611   return LowerAVXCONCAT_VECTORS(Op, DAG);
5612 }
5613
5614 // Try to lower a shuffle node into a simple blend instruction.
5615 static SDValue
5616 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5617                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5618   SDValue V1 = SVOp->getOperand(0);
5619   SDValue V2 = SVOp->getOperand(1);
5620   DebugLoc dl = SVOp->getDebugLoc();
5621   MVT VT = SVOp->getValueType(0).getSimpleVT();
5622   unsigned NumElems = VT.getVectorNumElements();
5623
5624   if (!Subtarget->hasSSE41())
5625     return SDValue();
5626
5627   unsigned ISDNo = 0;
5628   MVT OpTy;
5629
5630   switch (VT.SimpleTy) {
5631   default: return SDValue();
5632   case MVT::v8i16:
5633     ISDNo = X86ISD::BLENDPW;
5634     OpTy = MVT::v8i16;
5635     break;
5636   case MVT::v4i32:
5637   case MVT::v4f32:
5638     ISDNo = X86ISD::BLENDPS;
5639     OpTy = MVT::v4f32;
5640     break;
5641   case MVT::v2i64:
5642   case MVT::v2f64:
5643     ISDNo = X86ISD::BLENDPD;
5644     OpTy = MVT::v2f64;
5645     break;
5646   case MVT::v8i32:
5647   case MVT::v8f32:
5648     if (!Subtarget->hasAVX())
5649       return SDValue();
5650     ISDNo = X86ISD::BLENDPS;
5651     OpTy = MVT::v8f32;
5652     break;
5653   case MVT::v4i64:
5654   case MVT::v4f64:
5655     if (!Subtarget->hasAVX())
5656       return SDValue();
5657     ISDNo = X86ISD::BLENDPD;
5658     OpTy = MVT::v4f64;
5659     break;
5660   }
5661   assert(ISDNo && "Invalid Op Number");
5662
5663   unsigned MaskVals = 0;
5664
5665   for (unsigned i = 0; i != NumElems; ++i) {
5666     int EltIdx = SVOp->getMaskElt(i);
5667     if (EltIdx == (int)i || EltIdx < 0)
5668       MaskVals |= (1<<i);
5669     else if (EltIdx == (int)(i + NumElems))
5670       continue; // Bit is set to zero;
5671     else
5672       return SDValue();
5673   }
5674
5675   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5676   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5677   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5678                              DAG.getConstant(MaskVals, MVT::i32));
5679   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5680 }
5681
5682 // v8i16 shuffles - Prefer shuffles in the following order:
5683 // 1. [all]   pshuflw, pshufhw, optional move
5684 // 2. [ssse3] 1 x pshufb
5685 // 3. [ssse3] 2 x pshufb + 1 x por
5686 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5687 static SDValue
5688 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5689                          SelectionDAG &DAG) {
5690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5691   SDValue V1 = SVOp->getOperand(0);
5692   SDValue V2 = SVOp->getOperand(1);
5693   DebugLoc dl = SVOp->getDebugLoc();
5694   SmallVector<int, 8> MaskVals;
5695
5696   // Determine if more than 1 of the words in each of the low and high quadwords
5697   // of the result come from the same quadword of one of the two inputs.  Undef
5698   // mask values count as coming from any quadword, for better codegen.
5699   unsigned LoQuad[] = { 0, 0, 0, 0 };
5700   unsigned HiQuad[] = { 0, 0, 0, 0 };
5701   std::bitset<4> InputQuads;
5702   for (unsigned i = 0; i < 8; ++i) {
5703     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5704     int EltIdx = SVOp->getMaskElt(i);
5705     MaskVals.push_back(EltIdx);
5706     if (EltIdx < 0) {
5707       ++Quad[0];
5708       ++Quad[1];
5709       ++Quad[2];
5710       ++Quad[3];
5711       continue;
5712     }
5713     ++Quad[EltIdx / 4];
5714     InputQuads.set(EltIdx / 4);
5715   }
5716
5717   int BestLoQuad = -1;
5718   unsigned MaxQuad = 1;
5719   for (unsigned i = 0; i < 4; ++i) {
5720     if (LoQuad[i] > MaxQuad) {
5721       BestLoQuad = i;
5722       MaxQuad = LoQuad[i];
5723     }
5724   }
5725
5726   int BestHiQuad = -1;
5727   MaxQuad = 1;
5728   for (unsigned i = 0; i < 4; ++i) {
5729     if (HiQuad[i] > MaxQuad) {
5730       BestHiQuad = i;
5731       MaxQuad = HiQuad[i];
5732     }
5733   }
5734
5735   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5736   // of the two input vectors, shuffle them into one input vector so only a
5737   // single pshufb instruction is necessary. If There are more than 2 input
5738   // quads, disable the next transformation since it does not help SSSE3.
5739   bool V1Used = InputQuads[0] || InputQuads[1];
5740   bool V2Used = InputQuads[2] || InputQuads[3];
5741   if (Subtarget->hasSSSE3()) {
5742     if (InputQuads.count() == 2 && V1Used && V2Used) {
5743       BestLoQuad = InputQuads[0] ? 0 : 1;
5744       BestHiQuad = InputQuads[2] ? 2 : 3;
5745     }
5746     if (InputQuads.count() > 2) {
5747       BestLoQuad = -1;
5748       BestHiQuad = -1;
5749     }
5750   }
5751
5752   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5753   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5754   // words from all 4 input quadwords.
5755   SDValue NewV;
5756   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5757     int MaskV[] = {
5758       BestLoQuad < 0 ? 0 : BestLoQuad,
5759       BestHiQuad < 0 ? 1 : BestHiQuad
5760     };
5761     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5762                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5763                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5764     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5765
5766     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5767     // source words for the shuffle, to aid later transformations.
5768     bool AllWordsInNewV = true;
5769     bool InOrder[2] = { true, true };
5770     for (unsigned i = 0; i != 8; ++i) {
5771       int idx = MaskVals[i];
5772       if (idx != (int)i)
5773         InOrder[i/4] = false;
5774       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5775         continue;
5776       AllWordsInNewV = false;
5777       break;
5778     }
5779
5780     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5781     if (AllWordsInNewV) {
5782       for (int i = 0; i != 8; ++i) {
5783         int idx = MaskVals[i];
5784         if (idx < 0)
5785           continue;
5786         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5787         if ((idx != i) && idx < 4)
5788           pshufhw = false;
5789         if ((idx != i) && idx > 3)
5790           pshuflw = false;
5791       }
5792       V1 = NewV;
5793       V2Used = false;
5794       BestLoQuad = 0;
5795       BestHiQuad = 1;
5796     }
5797
5798     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5799     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5800     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5801       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5802       unsigned TargetMask = 0;
5803       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5804                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5805       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5806       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5807                              getShufflePSHUFLWImmediate(SVOp);
5808       V1 = NewV.getOperand(0);
5809       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5810     }
5811   }
5812
5813   // If we have SSSE3, and all words of the result are from 1 input vector,
5814   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5815   // is present, fall back to case 4.
5816   if (Subtarget->hasSSSE3()) {
5817     SmallVector<SDValue,16> pshufbMask;
5818
5819     // If we have elements from both input vectors, set the high bit of the
5820     // shuffle mask element to zero out elements that come from V2 in the V1
5821     // mask, and elements that come from V1 in the V2 mask, so that the two
5822     // results can be OR'd together.
5823     bool TwoInputs = V1Used && V2Used;
5824     for (unsigned i = 0; i != 8; ++i) {
5825       int EltIdx = MaskVals[i] * 2;
5826       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5827       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5828       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5829       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5830     }
5831     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5832     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5833                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5834                                  MVT::v16i8, &pshufbMask[0], 16));
5835     if (!TwoInputs)
5836       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5837
5838     // Calculate the shuffle mask for the second input, shuffle it, and
5839     // OR it with the first shuffled input.
5840     pshufbMask.clear();
5841     for (unsigned i = 0; i != 8; ++i) {
5842       int EltIdx = MaskVals[i] * 2;
5843       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5844       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5845       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5846       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5847     }
5848     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5849     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5850                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5851                                  MVT::v16i8, &pshufbMask[0], 16));
5852     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5853     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5854   }
5855
5856   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5857   // and update MaskVals with new element order.
5858   std::bitset<8> InOrder;
5859   if (BestLoQuad >= 0) {
5860     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5861     for (int i = 0; i != 4; ++i) {
5862       int idx = MaskVals[i];
5863       if (idx < 0) {
5864         InOrder.set(i);
5865       } else if ((idx / 4) == BestLoQuad) {
5866         MaskV[i] = idx & 3;
5867         InOrder.set(i);
5868       }
5869     }
5870     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5871                                 &MaskV[0]);
5872
5873     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5874       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5875       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5876                                   NewV.getOperand(0),
5877                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5878     }
5879   }
5880
5881   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5882   // and update MaskVals with the new element order.
5883   if (BestHiQuad >= 0) {
5884     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5885     for (unsigned i = 4; i != 8; ++i) {
5886       int idx = MaskVals[i];
5887       if (idx < 0) {
5888         InOrder.set(i);
5889       } else if ((idx / 4) == BestHiQuad) {
5890         MaskV[i] = (idx & 3) + 4;
5891         InOrder.set(i);
5892       }
5893     }
5894     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5895                                 &MaskV[0]);
5896
5897     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5898       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5899       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5900                                   NewV.getOperand(0),
5901                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5902     }
5903   }
5904
5905   // In case BestHi & BestLo were both -1, which means each quadword has a word
5906   // from each of the four input quadwords, calculate the InOrder bitvector now
5907   // before falling through to the insert/extract cleanup.
5908   if (BestLoQuad == -1 && BestHiQuad == -1) {
5909     NewV = V1;
5910     for (int i = 0; i != 8; ++i)
5911       if (MaskVals[i] < 0 || MaskVals[i] == i)
5912         InOrder.set(i);
5913   }
5914
5915   // The other elements are put in the right place using pextrw and pinsrw.
5916   for (unsigned i = 0; i != 8; ++i) {
5917     if (InOrder[i])
5918       continue;
5919     int EltIdx = MaskVals[i];
5920     if (EltIdx < 0)
5921       continue;
5922     SDValue ExtOp = (EltIdx < 8) ?
5923       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5924                   DAG.getIntPtrConstant(EltIdx)) :
5925       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5926                   DAG.getIntPtrConstant(EltIdx - 8));
5927     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5928                        DAG.getIntPtrConstant(i));
5929   }
5930   return NewV;
5931 }
5932
5933 // v16i8 shuffles - Prefer shuffles in the following order:
5934 // 1. [ssse3] 1 x pshufb
5935 // 2. [ssse3] 2 x pshufb + 1 x por
5936 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5937 static
5938 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5939                                  SelectionDAG &DAG,
5940                                  const X86TargetLowering &TLI) {
5941   SDValue V1 = SVOp->getOperand(0);
5942   SDValue V2 = SVOp->getOperand(1);
5943   DebugLoc dl = SVOp->getDebugLoc();
5944   ArrayRef<int> MaskVals = SVOp->getMask();
5945
5946   // If we have SSSE3, case 1 is generated when all result bytes come from
5947   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5948   // present, fall back to case 3.
5949
5950   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5951   if (TLI.getSubtarget()->hasSSSE3()) {
5952     SmallVector<SDValue,16> pshufbMask;
5953
5954     // If all result elements are from one input vector, then only translate
5955     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5956     //
5957     // Otherwise, we have elements from both input vectors, and must zero out
5958     // elements that come from V2 in the first mask, and V1 in the second mask
5959     // so that we can OR them together.
5960     for (unsigned i = 0; i != 16; ++i) {
5961       int EltIdx = MaskVals[i];
5962       if (EltIdx < 0 || EltIdx >= 16)
5963         EltIdx = 0x80;
5964       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5965     }
5966     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5967                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5968                                  MVT::v16i8, &pshufbMask[0], 16));
5969
5970     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5971     // the 2nd operand if it's undefined or zero.
5972     if (V2.getOpcode() == ISD::UNDEF ||
5973         ISD::isBuildVectorAllZeros(V2.getNode()))
5974       return V1;
5975
5976     // Calculate the shuffle mask for the second input, shuffle it, and
5977     // OR it with the first shuffled input.
5978     pshufbMask.clear();
5979     for (unsigned i = 0; i != 16; ++i) {
5980       int EltIdx = MaskVals[i];
5981       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5982       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5983     }
5984     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5985                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5986                                  MVT::v16i8, &pshufbMask[0], 16));
5987     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5988   }
5989
5990   // No SSSE3 - Calculate in place words and then fix all out of place words
5991   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5992   // the 16 different words that comprise the two doublequadword input vectors.
5993   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5994   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5995   SDValue NewV = V1;
5996   for (int i = 0; i != 8; ++i) {
5997     int Elt0 = MaskVals[i*2];
5998     int Elt1 = MaskVals[i*2+1];
5999
6000     // This word of the result is all undef, skip it.
6001     if (Elt0 < 0 && Elt1 < 0)
6002       continue;
6003
6004     // This word of the result is already in the correct place, skip it.
6005     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6006       continue;
6007
6008     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6009     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6010     SDValue InsElt;
6011
6012     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6013     // using a single extract together, load it and store it.
6014     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6015       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6016                            DAG.getIntPtrConstant(Elt1 / 2));
6017       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6018                         DAG.getIntPtrConstant(i));
6019       continue;
6020     }
6021
6022     // If Elt1 is defined, extract it from the appropriate source.  If the
6023     // source byte is not also odd, shift the extracted word left 8 bits
6024     // otherwise clear the bottom 8 bits if we need to do an or.
6025     if (Elt1 >= 0) {
6026       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6027                            DAG.getIntPtrConstant(Elt1 / 2));
6028       if ((Elt1 & 1) == 0)
6029         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6030                              DAG.getConstant(8,
6031                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6032       else if (Elt0 >= 0)
6033         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6034                              DAG.getConstant(0xFF00, MVT::i16));
6035     }
6036     // If Elt0 is defined, extract it from the appropriate source.  If the
6037     // source byte is not also even, shift the extracted word right 8 bits. If
6038     // Elt1 was also defined, OR the extracted values together before
6039     // inserting them in the result.
6040     if (Elt0 >= 0) {
6041       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6042                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6043       if ((Elt0 & 1) != 0)
6044         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6045                               DAG.getConstant(8,
6046                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6047       else if (Elt1 >= 0)
6048         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6049                              DAG.getConstant(0x00FF, MVT::i16));
6050       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6051                          : InsElt0;
6052     }
6053     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6054                        DAG.getIntPtrConstant(i));
6055   }
6056   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6057 }
6058
6059 // v32i8 shuffles - Translate to VPSHUFB if possible.
6060 static
6061 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6062                                  const X86Subtarget *Subtarget,
6063                                  SelectionDAG &DAG) {
6064   EVT VT = SVOp->getValueType(0);
6065   SDValue V1 = SVOp->getOperand(0);
6066   SDValue V2 = SVOp->getOperand(1);
6067   DebugLoc dl = SVOp->getDebugLoc();
6068   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6069
6070   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6071   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6072   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6073
6074   // VPSHUFB may be generated if
6075   // (1) one of input vector is undefined or zeroinitializer.
6076   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6077   // And (2) the mask indexes don't cross the 128-bit lane.
6078   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6079       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6080     return SDValue();
6081
6082   if (V1IsAllZero && !V2IsAllZero) {
6083     CommuteVectorShuffleMask(MaskVals, 32);
6084     V1 = V2;
6085   }
6086   SmallVector<SDValue, 32> pshufbMask;
6087   for (unsigned i = 0; i != 32; i++) {
6088     int EltIdx = MaskVals[i];
6089     if (EltIdx < 0 || EltIdx >= 32)
6090       EltIdx = 0x80;
6091     else {
6092       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6093         // Cross lane is not allowed.
6094         return SDValue();
6095       EltIdx &= 0xf;
6096     }
6097     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6098   }
6099   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6100                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6101                                   MVT::v32i8, &pshufbMask[0], 32));
6102 }
6103
6104 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6105 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6106 /// done when every pair / quad of shuffle mask elements point to elements in
6107 /// the right sequence. e.g.
6108 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6109 static
6110 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6111                                  SelectionDAG &DAG, DebugLoc dl) {
6112   MVT VT = SVOp->getValueType(0).getSimpleVT();
6113   unsigned NumElems = VT.getVectorNumElements();
6114   MVT NewVT;
6115   unsigned Scale;
6116   switch (VT.SimpleTy) {
6117   default: llvm_unreachable("Unexpected!");
6118   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6119   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6120   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6121   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6122   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6123   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6124   }
6125
6126   SmallVector<int, 8> MaskVec;
6127   for (unsigned i = 0; i != NumElems; i += Scale) {
6128     int StartIdx = -1;
6129     for (unsigned j = 0; j != Scale; ++j) {
6130       int EltIdx = SVOp->getMaskElt(i+j);
6131       if (EltIdx < 0)
6132         continue;
6133       if (StartIdx < 0)
6134         StartIdx = (EltIdx / Scale);
6135       if (EltIdx != (int)(StartIdx*Scale + j))
6136         return SDValue();
6137     }
6138     MaskVec.push_back(StartIdx);
6139   }
6140
6141   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6142   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6143   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6144 }
6145
6146 /// getVZextMovL - Return a zero-extending vector move low node.
6147 ///
6148 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6149                             SDValue SrcOp, SelectionDAG &DAG,
6150                             const X86Subtarget *Subtarget, DebugLoc dl) {
6151   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6152     LoadSDNode *LD = NULL;
6153     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6154       LD = dyn_cast<LoadSDNode>(SrcOp);
6155     if (!LD) {
6156       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6157       // instead.
6158       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6159       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6160           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6161           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6162           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6163         // PR2108
6164         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6165         return DAG.getNode(ISD::BITCAST, dl, VT,
6166                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6167                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6168                                                    OpVT,
6169                                                    SrcOp.getOperand(0)
6170                                                           .getOperand(0))));
6171       }
6172     }
6173   }
6174
6175   return DAG.getNode(ISD::BITCAST, dl, VT,
6176                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6177                                  DAG.getNode(ISD::BITCAST, dl,
6178                                              OpVT, SrcOp)));
6179 }
6180
6181 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6182 /// which could not be matched by any known target speficic shuffle
6183 static SDValue
6184 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6185
6186   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6187   if (NewOp.getNode())
6188     return NewOp;
6189
6190   EVT VT = SVOp->getValueType(0);
6191
6192   unsigned NumElems = VT.getVectorNumElements();
6193   unsigned NumLaneElems = NumElems / 2;
6194
6195   DebugLoc dl = SVOp->getDebugLoc();
6196   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6197   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6198   SDValue Output[2];
6199
6200   SmallVector<int, 16> Mask;
6201   for (unsigned l = 0; l < 2; ++l) {
6202     // Build a shuffle mask for the output, discovering on the fly which
6203     // input vectors to use as shuffle operands (recorded in InputUsed).
6204     // If building a suitable shuffle vector proves too hard, then bail
6205     // out with UseBuildVector set.
6206     bool UseBuildVector = false;
6207     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6208     unsigned LaneStart = l * NumLaneElems;
6209     for (unsigned i = 0; i != NumLaneElems; ++i) {
6210       // The mask element.  This indexes into the input.
6211       int Idx = SVOp->getMaskElt(i+LaneStart);
6212       if (Idx < 0) {
6213         // the mask element does not index into any input vector.
6214         Mask.push_back(-1);
6215         continue;
6216       }
6217
6218       // The input vector this mask element indexes into.
6219       int Input = Idx / NumLaneElems;
6220
6221       // Turn the index into an offset from the start of the input vector.
6222       Idx -= Input * NumLaneElems;
6223
6224       // Find or create a shuffle vector operand to hold this input.
6225       unsigned OpNo;
6226       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6227         if (InputUsed[OpNo] == Input)
6228           // This input vector is already an operand.
6229           break;
6230         if (InputUsed[OpNo] < 0) {
6231           // Create a new operand for this input vector.
6232           InputUsed[OpNo] = Input;
6233           break;
6234         }
6235       }
6236
6237       if (OpNo >= array_lengthof(InputUsed)) {
6238         // More than two input vectors used!  Give up on trying to create a
6239         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6240         UseBuildVector = true;
6241         break;
6242       }
6243
6244       // Add the mask index for the new shuffle vector.
6245       Mask.push_back(Idx + OpNo * NumLaneElems);
6246     }
6247
6248     if (UseBuildVector) {
6249       SmallVector<SDValue, 16> SVOps;
6250       for (unsigned i = 0; i != NumLaneElems; ++i) {
6251         // The mask element.  This indexes into the input.
6252         int Idx = SVOp->getMaskElt(i+LaneStart);
6253         if (Idx < 0) {
6254           SVOps.push_back(DAG.getUNDEF(EltVT));
6255           continue;
6256         }
6257
6258         // The input vector this mask element indexes into.
6259         int Input = Idx / NumElems;
6260
6261         // Turn the index into an offset from the start of the input vector.
6262         Idx -= Input * NumElems;
6263
6264         // Extract the vector element by hand.
6265         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6266                                     SVOp->getOperand(Input),
6267                                     DAG.getIntPtrConstant(Idx)));
6268       }
6269
6270       // Construct the output using a BUILD_VECTOR.
6271       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6272                               SVOps.size());
6273     } else if (InputUsed[0] < 0) {
6274       // No input vectors were used! The result is undefined.
6275       Output[l] = DAG.getUNDEF(NVT);
6276     } else {
6277       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6278                                         (InputUsed[0] % 2) * NumLaneElems,
6279                                         DAG, dl);
6280       // If only one input was used, use an undefined vector for the other.
6281       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6282         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6283                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6284       // At least one input vector was used. Create a new shuffle vector.
6285       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6286     }
6287
6288     Mask.clear();
6289   }
6290
6291   // Concatenate the result back
6292   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6293 }
6294
6295 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6296 /// 4 elements, and match them with several different shuffle types.
6297 static SDValue
6298 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6299   SDValue V1 = SVOp->getOperand(0);
6300   SDValue V2 = SVOp->getOperand(1);
6301   DebugLoc dl = SVOp->getDebugLoc();
6302   EVT VT = SVOp->getValueType(0);
6303
6304   assert(VT.is128BitVector() && "Unsupported vector size");
6305
6306   std::pair<int, int> Locs[4];
6307   int Mask1[] = { -1, -1, -1, -1 };
6308   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6309
6310   unsigned NumHi = 0;
6311   unsigned NumLo = 0;
6312   for (unsigned i = 0; i != 4; ++i) {
6313     int Idx = PermMask[i];
6314     if (Idx < 0) {
6315       Locs[i] = std::make_pair(-1, -1);
6316     } else {
6317       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6318       if (Idx < 4) {
6319         Locs[i] = std::make_pair(0, NumLo);
6320         Mask1[NumLo] = Idx;
6321         NumLo++;
6322       } else {
6323         Locs[i] = std::make_pair(1, NumHi);
6324         if (2+NumHi < 4)
6325           Mask1[2+NumHi] = Idx;
6326         NumHi++;
6327       }
6328     }
6329   }
6330
6331   if (NumLo <= 2 && NumHi <= 2) {
6332     // If no more than two elements come from either vector. This can be
6333     // implemented with two shuffles. First shuffle gather the elements.
6334     // The second shuffle, which takes the first shuffle as both of its
6335     // vector operands, put the elements into the right order.
6336     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6337
6338     int Mask2[] = { -1, -1, -1, -1 };
6339
6340     for (unsigned i = 0; i != 4; ++i)
6341       if (Locs[i].first != -1) {
6342         unsigned Idx = (i < 2) ? 0 : 4;
6343         Idx += Locs[i].first * 2 + Locs[i].second;
6344         Mask2[i] = Idx;
6345       }
6346
6347     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6348   }
6349
6350   if (NumLo == 3 || NumHi == 3) {
6351     // Otherwise, we must have three elements from one vector, call it X, and
6352     // one element from the other, call it Y.  First, use a shufps to build an
6353     // intermediate vector with the one element from Y and the element from X
6354     // that will be in the same half in the final destination (the indexes don't
6355     // matter). Then, use a shufps to build the final vector, taking the half
6356     // containing the element from Y from the intermediate, and the other half
6357     // from X.
6358     if (NumHi == 3) {
6359       // Normalize it so the 3 elements come from V1.
6360       CommuteVectorShuffleMask(PermMask, 4);
6361       std::swap(V1, V2);
6362     }
6363
6364     // Find the element from V2.
6365     unsigned HiIndex;
6366     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6367       int Val = PermMask[HiIndex];
6368       if (Val < 0)
6369         continue;
6370       if (Val >= 4)
6371         break;
6372     }
6373
6374     Mask1[0] = PermMask[HiIndex];
6375     Mask1[1] = -1;
6376     Mask1[2] = PermMask[HiIndex^1];
6377     Mask1[3] = -1;
6378     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6379
6380     if (HiIndex >= 2) {
6381       Mask1[0] = PermMask[0];
6382       Mask1[1] = PermMask[1];
6383       Mask1[2] = HiIndex & 1 ? 6 : 4;
6384       Mask1[3] = HiIndex & 1 ? 4 : 6;
6385       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6386     }
6387
6388     Mask1[0] = HiIndex & 1 ? 2 : 0;
6389     Mask1[1] = HiIndex & 1 ? 0 : 2;
6390     Mask1[2] = PermMask[2];
6391     Mask1[3] = PermMask[3];
6392     if (Mask1[2] >= 0)
6393       Mask1[2] += 4;
6394     if (Mask1[3] >= 0)
6395       Mask1[3] += 4;
6396     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6397   }
6398
6399   // Break it into (shuffle shuffle_hi, shuffle_lo).
6400   int LoMask[] = { -1, -1, -1, -1 };
6401   int HiMask[] = { -1, -1, -1, -1 };
6402
6403   int *MaskPtr = LoMask;
6404   unsigned MaskIdx = 0;
6405   unsigned LoIdx = 0;
6406   unsigned HiIdx = 2;
6407   for (unsigned i = 0; i != 4; ++i) {
6408     if (i == 2) {
6409       MaskPtr = HiMask;
6410       MaskIdx = 1;
6411       LoIdx = 0;
6412       HiIdx = 2;
6413     }
6414     int Idx = PermMask[i];
6415     if (Idx < 0) {
6416       Locs[i] = std::make_pair(-1, -1);
6417     } else if (Idx < 4) {
6418       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6419       MaskPtr[LoIdx] = Idx;
6420       LoIdx++;
6421     } else {
6422       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6423       MaskPtr[HiIdx] = Idx;
6424       HiIdx++;
6425     }
6426   }
6427
6428   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6429   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6430   int MaskOps[] = { -1, -1, -1, -1 };
6431   for (unsigned i = 0; i != 4; ++i)
6432     if (Locs[i].first != -1)
6433       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6434   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6435 }
6436
6437 static bool MayFoldVectorLoad(SDValue V) {
6438   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6439     V = V.getOperand(0);
6440   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6441     V = V.getOperand(0);
6442   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6443       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6444     // BUILD_VECTOR (load), undef
6445     V = V.getOperand(0);
6446   if (MayFoldLoad(V))
6447     return true;
6448   return false;
6449 }
6450
6451 // FIXME: the version above should always be used. Since there's
6452 // a bug where several vector shuffles can't be folded because the
6453 // DAG is not updated during lowering and a node claims to have two
6454 // uses while it only has one, use this version, and let isel match
6455 // another instruction if the load really happens to have more than
6456 // one use. Remove this version after this bug get fixed.
6457 // rdar://8434668, PR8156
6458 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6459   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6460     V = V.getOperand(0);
6461   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6462     V = V.getOperand(0);
6463   if (ISD::isNormalLoad(V.getNode()))
6464     return true;
6465   return false;
6466 }
6467
6468 static
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471
6472   // Canonizalize to v2f64.
6473   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6476                                           V1, DAG));
6477 }
6478
6479 static
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6481                         bool HasSSE2) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6487
6488   if (HasSSE2 && VT == MVT::v2f64)
6489     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6490
6491   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492   return DAG.getNode(ISD::BITCAST, dl, VT,
6493                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6496 }
6497
6498 static
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503
6504   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505          "unsupported shuffle type");
6506
6507   if (V2.getOpcode() == ISD::UNDEF)
6508     V2 = V1;
6509
6510   // v4i32 or v4f32
6511   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6512 }
6513
6514 static
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516   SDValue V1 = Op.getOperand(0);
6517   SDValue V2 = Op.getOperand(1);
6518   EVT VT = Op.getValueType();
6519   unsigned NumElems = VT.getVectorNumElements();
6520
6521   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522   // operand of these instructions is only memory, so check if there's a
6523   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6524   // same masks.
6525   bool CanFoldLoad = false;
6526
6527   // Trivial case, when V2 comes from a load.
6528   if (MayFoldVectorLoad(V2))
6529     CanFoldLoad = true;
6530
6531   // When V1 is a load, it can be folded later into a store in isel, example:
6532   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6533   //    turns into:
6534   //  (MOVLPSmr addr:$src1, VR128:$src2)
6535   // So, recognize this potential and also use MOVLPS or MOVLPD
6536   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6537     CanFoldLoad = true;
6538
6539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6540   if (CanFoldLoad) {
6541     if (HasSSE2 && NumElems == 2)
6542       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6543
6544     if (NumElems == 4)
6545       // If we don't care about the second element, proceed to use movss.
6546       if (SVOp->getMaskElt(1) != -1)
6547         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6548   }
6549
6550   // movl and movlp will both match v2i64, but v2i64 is never matched by
6551   // movl earlier because we make it strict to avoid messing with the movlp load
6552   // folding logic (see the code above getMOVLP call). Match it here then,
6553   // this is horrible, but will stay like this until we move all shuffle
6554   // matching to x86 specific nodes. Note that for the 1st condition all
6555   // types are matched with movsd.
6556   if (HasSSE2) {
6557     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558     // as to remove this logic from here, as much as possible
6559     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6562   }
6563
6564   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6565
6566   // Invert the operand order and use SHUFPS to match it.
6567   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568                               getShuffleSHUFImmediate(SVOp), DAG);
6569 }
6570
6571 // Reduce a vector shuffle to zext.
6572 SDValue
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574   // PMOVZX is only available from SSE41.
6575   if (!Subtarget->hasSSE41())
6576     return SDValue();
6577
6578   EVT VT = Op.getValueType();
6579
6580   // Only AVX2 support 256-bit vector integer extending.
6581   if (!Subtarget->hasAVX2() && VT.is256BitVector())
6582     return SDValue();
6583
6584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585   DebugLoc DL = Op.getDebugLoc();
6586   SDValue V1 = Op.getOperand(0);
6587   SDValue V2 = Op.getOperand(1);
6588   unsigned NumElems = VT.getVectorNumElements();
6589
6590   // Extending is an unary operation and the element type of the source vector
6591   // won't be equal to or larger than i64.
6592   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593       VT.getVectorElementType() == MVT::i64)
6594     return SDValue();
6595
6596   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598   while ((1 << Shift) < NumElems) {
6599     if (SVOp->getMaskElt(1 << Shift) == 1)
6600       break;
6601     Shift += 1;
6602     // The maximal ratio is 8, i.e. from i8 to i64.
6603     if (Shift > 3)
6604       return SDValue();
6605   }
6606
6607   // Check the shuffle mask.
6608   unsigned Mask = (1U << Shift) - 1;
6609   for (unsigned i = 0; i != NumElems; ++i) {
6610     int EltIdx = SVOp->getMaskElt(i);
6611     if ((i & Mask) != 0 && EltIdx != -1)
6612       return SDValue();
6613     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6614       return SDValue();
6615   }
6616
6617   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6620
6621   if (!isTypeLegal(NVT))
6622     return SDValue();
6623
6624   // Simplify the operand as it's prepared to be fed into shuffle.
6625   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626   if (V1.getOpcode() == ISD::BITCAST &&
6627       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6629       V1.getOperand(0)
6630         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633     ConstantSDNode *CIdx =
6634       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6635     // If it's foldable, i.e. normal load with single use, we will let code
6636     // selection to fold it. Otherwise, we will short the conversion sequence.
6637     if (CIdx && CIdx->getZExtValue() == 0 &&
6638         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6639       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6640   }
6641
6642   return DAG.getNode(ISD::BITCAST, DL, VT,
6643                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6644 }
6645
6646 SDValue
6647 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6648   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6649   EVT VT = Op.getValueType();
6650   DebugLoc dl = Op.getDebugLoc();
6651   SDValue V1 = Op.getOperand(0);
6652   SDValue V2 = Op.getOperand(1);
6653
6654   if (isZeroShuffle(SVOp))
6655     return getZeroVector(VT, Subtarget, DAG, dl);
6656
6657   // Handle splat operations
6658   if (SVOp->isSplat()) {
6659     unsigned NumElem = VT.getVectorNumElements();
6660     int Size = VT.getSizeInBits();
6661
6662     // Use vbroadcast whenever the splat comes from a foldable load
6663     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6664     if (Broadcast.getNode())
6665       return Broadcast;
6666
6667     // Handle splats by matching through known shuffle masks
6668     if ((Size == 128 && NumElem <= 4) ||
6669         (Size == 256 && NumElem < 8))
6670       return SDValue();
6671
6672     // All remaning splats are promoted to target supported vector shuffles.
6673     return PromoteSplat(SVOp, DAG);
6674   }
6675
6676   // Check integer expanding shuffles.
6677   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6678   if (NewOp.getNode())
6679     return NewOp;
6680
6681   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6682   // do it!
6683   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6684       VT == MVT::v16i16 || VT == MVT::v32i8) {
6685     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6686     if (NewOp.getNode())
6687       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6688   } else if ((VT == MVT::v4i32 ||
6689              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6690     // FIXME: Figure out a cleaner way to do this.
6691     // Try to make use of movq to zero out the top part.
6692     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6693       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694       if (NewOp.getNode()) {
6695         EVT NewVT = NewOp.getValueType();
6696         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6697                                NewVT, true, false))
6698           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6699                               DAG, Subtarget, dl);
6700       }
6701     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6703       if (NewOp.getNode()) {
6704         EVT NewVT = NewOp.getValueType();
6705         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6706           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6707                               DAG, Subtarget, dl);
6708       }
6709     }
6710   }
6711   return SDValue();
6712 }
6713
6714 SDValue
6715 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6717   SDValue V1 = Op.getOperand(0);
6718   SDValue V2 = Op.getOperand(1);
6719   EVT VT = Op.getValueType();
6720   DebugLoc dl = Op.getDebugLoc();
6721   unsigned NumElems = VT.getVectorNumElements();
6722   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6723   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6724   bool V1IsSplat = false;
6725   bool V2IsSplat = false;
6726   bool HasSSE2 = Subtarget->hasSSE2();
6727   bool HasAVX    = Subtarget->hasAVX();
6728   bool HasAVX2   = Subtarget->hasAVX2();
6729   MachineFunction &MF = DAG.getMachineFunction();
6730   bool OptForSize = MF.getFunction()->getFnAttributes().
6731     hasAttribute(Attributes::OptimizeForSize);
6732
6733   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6734
6735   if (V1IsUndef && V2IsUndef)
6736     return DAG.getUNDEF(VT);
6737
6738   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6739
6740   // Vector shuffle lowering takes 3 steps:
6741   //
6742   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6743   //    narrowing and commutation of operands should be handled.
6744   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6745   //    shuffle nodes.
6746   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6747   //    so the shuffle can be broken into other shuffles and the legalizer can
6748   //    try the lowering again.
6749   //
6750   // The general idea is that no vector_shuffle operation should be left to
6751   // be matched during isel, all of them must be converted to a target specific
6752   // node here.
6753
6754   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6755   // narrowing and commutation of operands should be handled. The actual code
6756   // doesn't include all of those, work in progress...
6757   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6758   if (NewOp.getNode())
6759     return NewOp;
6760
6761   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6762
6763   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6764   // unpckh_undef). Only use pshufd if speed is more important than size.
6765   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6766     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6767   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6768     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6769
6770   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6771       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6772     return getMOVDDup(Op, dl, V1, DAG);
6773
6774   if (isMOVHLPS_v_undef_Mask(M, VT))
6775     return getMOVHighToLow(Op, dl, DAG);
6776
6777   // Use to match splats
6778   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6779       (VT == MVT::v2f64 || VT == MVT::v2i64))
6780     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6781
6782   if (isPSHUFDMask(M, VT)) {
6783     // The actual implementation will match the mask in the if above and then
6784     // during isel it can match several different instructions, not only pshufd
6785     // as its name says, sad but true, emulate the behavior for now...
6786     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6787       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6788
6789     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6790
6791     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6792       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6793
6794     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6795       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6796
6797     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6798                                 TargetMask, DAG);
6799   }
6800
6801   // Check if this can be converted into a logical shift.
6802   bool isLeft = false;
6803   unsigned ShAmt = 0;
6804   SDValue ShVal;
6805   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6806   if (isShift && ShVal.hasOneUse()) {
6807     // If the shifted value has multiple uses, it may be cheaper to use
6808     // v_set0 + movlhps or movhlps, etc.
6809     EVT EltVT = VT.getVectorElementType();
6810     ShAmt *= EltVT.getSizeInBits();
6811     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6812   }
6813
6814   if (isMOVLMask(M, VT)) {
6815     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6816       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6817     if (!isMOVLPMask(M, VT)) {
6818       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6819         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6820
6821       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6822         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6823     }
6824   }
6825
6826   // FIXME: fold these into legal mask.
6827   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6828     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6829
6830   if (isMOVHLPSMask(M, VT))
6831     return getMOVHighToLow(Op, dl, DAG);
6832
6833   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6834     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6835
6836   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6837     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6838
6839   if (isMOVLPMask(M, VT))
6840     return getMOVLP(Op, dl, DAG, HasSSE2);
6841
6842   if (ShouldXformToMOVHLPS(M, VT) ||
6843       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6844     return CommuteVectorShuffle(SVOp, DAG);
6845
6846   if (isShift) {
6847     // No better options. Use a vshldq / vsrldq.
6848     EVT EltVT = VT.getVectorElementType();
6849     ShAmt *= EltVT.getSizeInBits();
6850     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6851   }
6852
6853   bool Commuted = false;
6854   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6855   // 1,1,1,1 -> v8i16 though.
6856   V1IsSplat = isSplatVector(V1.getNode());
6857   V2IsSplat = isSplatVector(V2.getNode());
6858
6859   // Canonicalize the splat or undef, if present, to be on the RHS.
6860   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6861     CommuteVectorShuffleMask(M, NumElems);
6862     std::swap(V1, V2);
6863     std::swap(V1IsSplat, V2IsSplat);
6864     Commuted = true;
6865   }
6866
6867   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6868     // Shuffling low element of v1 into undef, just return v1.
6869     if (V2IsUndef)
6870       return V1;
6871     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6872     // the instruction selector will not match, so get a canonical MOVL with
6873     // swapped operands to undo the commute.
6874     return getMOVL(DAG, dl, VT, V2, V1);
6875   }
6876
6877   if (isUNPCKLMask(M, VT, HasAVX2))
6878     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6879
6880   if (isUNPCKHMask(M, VT, HasAVX2))
6881     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6882
6883   if (V2IsSplat) {
6884     // Normalize mask so all entries that point to V2 points to its first
6885     // element then try to match unpck{h|l} again. If match, return a
6886     // new vector_shuffle with the corrected mask.p
6887     SmallVector<int, 8> NewMask(M.begin(), M.end());
6888     NormalizeMask(NewMask, NumElems);
6889     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6890       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6891     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6892       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6893   }
6894
6895   if (Commuted) {
6896     // Commute is back and try unpck* again.
6897     // FIXME: this seems wrong.
6898     CommuteVectorShuffleMask(M, NumElems);
6899     std::swap(V1, V2);
6900     std::swap(V1IsSplat, V2IsSplat);
6901     Commuted = false;
6902
6903     if (isUNPCKLMask(M, VT, HasAVX2))
6904       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6905
6906     if (isUNPCKHMask(M, VT, HasAVX2))
6907       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6908   }
6909
6910   // Normalize the node to match x86 shuffle ops if needed
6911   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6912     return CommuteVectorShuffle(SVOp, DAG);
6913
6914   // The checks below are all present in isShuffleMaskLegal, but they are
6915   // inlined here right now to enable us to directly emit target specific
6916   // nodes, and remove one by one until they don't return Op anymore.
6917
6918   if (isPALIGNRMask(M, VT, Subtarget))
6919     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6920                                 getShufflePALIGNRImmediate(SVOp),
6921                                 DAG);
6922
6923   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6924       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6925     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6926       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6927   }
6928
6929   if (isPSHUFHWMask(M, VT, HasAVX2))
6930     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6931                                 getShufflePSHUFHWImmediate(SVOp),
6932                                 DAG);
6933
6934   if (isPSHUFLWMask(M, VT, HasAVX2))
6935     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6936                                 getShufflePSHUFLWImmediate(SVOp),
6937                                 DAG);
6938
6939   if (isSHUFPMask(M, VT, HasAVX))
6940     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6941                                 getShuffleSHUFImmediate(SVOp), DAG);
6942
6943   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6944     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6945   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6946     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6947
6948   //===--------------------------------------------------------------------===//
6949   // Generate target specific nodes for 128 or 256-bit shuffles only
6950   // supported in the AVX instruction set.
6951   //
6952
6953   // Handle VMOVDDUPY permutations
6954   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6955     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6956
6957   // Handle VPERMILPS/D* permutations
6958   if (isVPERMILPMask(M, VT, HasAVX)) {
6959     if (HasAVX2 && VT == MVT::v8i32)
6960       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6961                                   getShuffleSHUFImmediate(SVOp), DAG);
6962     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6963                                 getShuffleSHUFImmediate(SVOp), DAG);
6964   }
6965
6966   // Handle VPERM2F128/VPERM2I128 permutations
6967   if (isVPERM2X128Mask(M, VT, HasAVX))
6968     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6969                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6970
6971   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6972   if (BlendOp.getNode())
6973     return BlendOp;
6974
6975   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6976     SmallVector<SDValue, 8> permclMask;
6977     for (unsigned i = 0; i != 8; ++i) {
6978       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6979     }
6980     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6981                                &permclMask[0], 8);
6982     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6983     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6984                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6985   }
6986
6987   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6988     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6989                                 getShuffleCLImmediate(SVOp), DAG);
6990
6991
6992   //===--------------------------------------------------------------------===//
6993   // Since no target specific shuffle was selected for this generic one,
6994   // lower it into other known shuffles. FIXME: this isn't true yet, but
6995   // this is the plan.
6996   //
6997
6998   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6999   if (VT == MVT::v8i16) {
7000     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7001     if (NewOp.getNode())
7002       return NewOp;
7003   }
7004
7005   if (VT == MVT::v16i8) {
7006     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7007     if (NewOp.getNode())
7008       return NewOp;
7009   }
7010
7011   if (VT == MVT::v32i8) {
7012     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7013     if (NewOp.getNode())
7014       return NewOp;
7015   }
7016
7017   // Handle all 128-bit wide vectors with 4 elements, and match them with
7018   // several different shuffle types.
7019   if (NumElems == 4 && VT.is128BitVector())
7020     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7021
7022   // Handle general 256-bit shuffles
7023   if (VT.is256BitVector())
7024     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7025
7026   return SDValue();
7027 }
7028
7029 SDValue
7030 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7031                                                 SelectionDAG &DAG) const {
7032   EVT VT = Op.getValueType();
7033   DebugLoc dl = Op.getDebugLoc();
7034
7035   if (!Op.getOperand(0).getValueType().is128BitVector())
7036     return SDValue();
7037
7038   if (VT.getSizeInBits() == 8) {
7039     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7040                                   Op.getOperand(0), Op.getOperand(1));
7041     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7042                                   DAG.getValueType(VT));
7043     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7044   }
7045
7046   if (VT.getSizeInBits() == 16) {
7047     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7049     if (Idx == 0)
7050       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7051                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7052                                      DAG.getNode(ISD::BITCAST, dl,
7053                                                  MVT::v4i32,
7054                                                  Op.getOperand(0)),
7055                                      Op.getOperand(1)));
7056     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7057                                   Op.getOperand(0), Op.getOperand(1));
7058     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7059                                   DAG.getValueType(VT));
7060     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7061   }
7062
7063   if (VT == MVT::f32) {
7064     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7065     // the result back to FR32 register. It's only worth matching if the
7066     // result has a single use which is a store or a bitcast to i32.  And in
7067     // the case of a store, it's not worth it if the index is a constant 0,
7068     // because a MOVSSmr can be used instead, which is smaller and faster.
7069     if (!Op.hasOneUse())
7070       return SDValue();
7071     SDNode *User = *Op.getNode()->use_begin();
7072     if ((User->getOpcode() != ISD::STORE ||
7073          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7074           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7075         (User->getOpcode() != ISD::BITCAST ||
7076          User->getValueType(0) != MVT::i32))
7077       return SDValue();
7078     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7079                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7080                                               Op.getOperand(0)),
7081                                               Op.getOperand(1));
7082     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7083   }
7084
7085   if (VT == MVT::i32 || VT == MVT::i64) {
7086     // ExtractPS/pextrq works with constant index.
7087     if (isa<ConstantSDNode>(Op.getOperand(1)))
7088       return Op;
7089   }
7090   return SDValue();
7091 }
7092
7093
7094 SDValue
7095 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7096                                            SelectionDAG &DAG) const {
7097   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7098     return SDValue();
7099
7100   SDValue Vec = Op.getOperand(0);
7101   EVT VecVT = Vec.getValueType();
7102
7103   // If this is a 256-bit vector result, first extract the 128-bit vector and
7104   // then extract the element from the 128-bit vector.
7105   if (VecVT.is256BitVector()) {
7106     DebugLoc dl = Op.getNode()->getDebugLoc();
7107     unsigned NumElems = VecVT.getVectorNumElements();
7108     SDValue Idx = Op.getOperand(1);
7109     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7110
7111     // Get the 128-bit vector.
7112     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7113
7114     if (IdxVal >= NumElems/2)
7115       IdxVal -= NumElems/2;
7116     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7117                        DAG.getConstant(IdxVal, MVT::i32));
7118   }
7119
7120   assert(VecVT.is128BitVector() && "Unexpected vector length");
7121
7122   if (Subtarget->hasSSE41()) {
7123     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7124     if (Res.getNode())
7125       return Res;
7126   }
7127
7128   EVT VT = Op.getValueType();
7129   DebugLoc dl = Op.getDebugLoc();
7130   // TODO: handle v16i8.
7131   if (VT.getSizeInBits() == 16) {
7132     SDValue Vec = Op.getOperand(0);
7133     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7134     if (Idx == 0)
7135       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7136                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7137                                      DAG.getNode(ISD::BITCAST, dl,
7138                                                  MVT::v4i32, Vec),
7139                                      Op.getOperand(1)));
7140     // Transform it so it match pextrw which produces a 32-bit result.
7141     EVT EltVT = MVT::i32;
7142     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7143                                   Op.getOperand(0), Op.getOperand(1));
7144     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7145                                   DAG.getValueType(VT));
7146     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7147   }
7148
7149   if (VT.getSizeInBits() == 32) {
7150     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7151     if (Idx == 0)
7152       return Op;
7153
7154     // SHUFPS the element to the lowest double word, then movss.
7155     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7156     EVT VVT = Op.getOperand(0).getValueType();
7157     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7158                                        DAG.getUNDEF(VVT), Mask);
7159     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7160                        DAG.getIntPtrConstant(0));
7161   }
7162
7163   if (VT.getSizeInBits() == 64) {
7164     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7165     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7166     //        to match extract_elt for f64.
7167     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7168     if (Idx == 0)
7169       return Op;
7170
7171     // UNPCKHPD the element to the lowest double word, then movsd.
7172     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7173     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7174     int Mask[2] = { 1, -1 };
7175     EVT VVT = Op.getOperand(0).getValueType();
7176     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7177                                        DAG.getUNDEF(VVT), Mask);
7178     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7179                        DAG.getIntPtrConstant(0));
7180   }
7181
7182   return SDValue();
7183 }
7184
7185 SDValue
7186 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7187                                                SelectionDAG &DAG) const {
7188   EVT VT = Op.getValueType();
7189   EVT EltVT = VT.getVectorElementType();
7190   DebugLoc dl = Op.getDebugLoc();
7191
7192   SDValue N0 = Op.getOperand(0);
7193   SDValue N1 = Op.getOperand(1);
7194   SDValue N2 = Op.getOperand(2);
7195
7196   if (!VT.is128BitVector())
7197     return SDValue();
7198
7199   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7200       isa<ConstantSDNode>(N2)) {
7201     unsigned Opc;
7202     if (VT == MVT::v8i16)
7203       Opc = X86ISD::PINSRW;
7204     else if (VT == MVT::v16i8)
7205       Opc = X86ISD::PINSRB;
7206     else
7207       Opc = X86ISD::PINSRB;
7208
7209     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7210     // argument.
7211     if (N1.getValueType() != MVT::i32)
7212       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7213     if (N2.getValueType() != MVT::i32)
7214       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7215     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7216   }
7217
7218   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7219     // Bits [7:6] of the constant are the source select.  This will always be
7220     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7221     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7222     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7223     // Bits [5:4] of the constant are the destination select.  This is the
7224     //  value of the incoming immediate.
7225     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7226     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7227     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7228     // Create this as a scalar to vector..
7229     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7230     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7231   }
7232
7233   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7234     // PINSR* works with constant index.
7235     return Op;
7236   }
7237   return SDValue();
7238 }
7239
7240 SDValue
7241 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7242   EVT VT = Op.getValueType();
7243   EVT EltVT = VT.getVectorElementType();
7244
7245   DebugLoc dl = Op.getDebugLoc();
7246   SDValue N0 = Op.getOperand(0);
7247   SDValue N1 = Op.getOperand(1);
7248   SDValue N2 = Op.getOperand(2);
7249
7250   // If this is a 256-bit vector result, first extract the 128-bit vector,
7251   // insert the element into the extracted half and then place it back.
7252   if (VT.is256BitVector()) {
7253     if (!isa<ConstantSDNode>(N2))
7254       return SDValue();
7255
7256     // Get the desired 128-bit vector half.
7257     unsigned NumElems = VT.getVectorNumElements();
7258     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7259     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7260
7261     // Insert the element into the desired half.
7262     bool Upper = IdxVal >= NumElems/2;
7263     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7264                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7265
7266     // Insert the changed part back to the 256-bit vector
7267     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7268   }
7269
7270   if (Subtarget->hasSSE41())
7271     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7272
7273   if (EltVT == MVT::i8)
7274     return SDValue();
7275
7276   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7277     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7278     // as its second argument.
7279     if (N1.getValueType() != MVT::i32)
7280       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7281     if (N2.getValueType() != MVT::i32)
7282       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7283     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7284   }
7285   return SDValue();
7286 }
7287
7288 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7289   LLVMContext *Context = DAG.getContext();
7290   DebugLoc dl = Op.getDebugLoc();
7291   EVT OpVT = Op.getValueType();
7292
7293   // If this is a 256-bit vector result, first insert into a 128-bit
7294   // vector and then insert into the 256-bit vector.
7295   if (!OpVT.is128BitVector()) {
7296     // Insert into a 128-bit vector.
7297     EVT VT128 = EVT::getVectorVT(*Context,
7298                                  OpVT.getVectorElementType(),
7299                                  OpVT.getVectorNumElements() / 2);
7300
7301     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7302
7303     // Insert the 128-bit vector.
7304     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7305   }
7306
7307   if (OpVT == MVT::v1i64 &&
7308       Op.getOperand(0).getValueType() == MVT::i64)
7309     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7310
7311   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7312   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7313   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7314                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7315 }
7316
7317 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7318 // a simple subregister reference or explicit instructions to grab
7319 // upper bits of a vector.
7320 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7321                                       SelectionDAG &DAG) {
7322   if (Subtarget->hasAVX()) {
7323     DebugLoc dl = Op.getNode()->getDebugLoc();
7324     SDValue Vec = Op.getNode()->getOperand(0);
7325     SDValue Idx = Op.getNode()->getOperand(1);
7326
7327     if (Op.getNode()->getValueType(0).is128BitVector() &&
7328         Vec.getNode()->getValueType(0).is256BitVector() &&
7329         isa<ConstantSDNode>(Idx)) {
7330       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7331       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7332     }
7333   }
7334   return SDValue();
7335 }
7336
7337 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7338 // simple superregister reference or explicit instructions to insert
7339 // the upper bits of a vector.
7340 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7341                                      SelectionDAG &DAG) {
7342   if (Subtarget->hasAVX()) {
7343     DebugLoc dl = Op.getNode()->getDebugLoc();
7344     SDValue Vec = Op.getNode()->getOperand(0);
7345     SDValue SubVec = Op.getNode()->getOperand(1);
7346     SDValue Idx = Op.getNode()->getOperand(2);
7347
7348     if (Op.getNode()->getValueType(0).is256BitVector() &&
7349         SubVec.getNode()->getValueType(0).is128BitVector() &&
7350         isa<ConstantSDNode>(Idx)) {
7351       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7352       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7353     }
7354   }
7355   return SDValue();
7356 }
7357
7358 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7359 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7360 // one of the above mentioned nodes. It has to be wrapped because otherwise
7361 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7362 // be used to form addressing mode. These wrapped nodes will be selected
7363 // into MOV32ri.
7364 SDValue
7365 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7366   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7367
7368   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7369   // global base reg.
7370   unsigned char OpFlag = 0;
7371   unsigned WrapperKind = X86ISD::Wrapper;
7372   CodeModel::Model M = getTargetMachine().getCodeModel();
7373
7374   if (Subtarget->isPICStyleRIPRel() &&
7375       (M == CodeModel::Small || M == CodeModel::Kernel))
7376     WrapperKind = X86ISD::WrapperRIP;
7377   else if (Subtarget->isPICStyleGOT())
7378     OpFlag = X86II::MO_GOTOFF;
7379   else if (Subtarget->isPICStyleStubPIC())
7380     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7381
7382   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7383                                              CP->getAlignment(),
7384                                              CP->getOffset(), OpFlag);
7385   DebugLoc DL = CP->getDebugLoc();
7386   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7387   // With PIC, the address is actually $g + Offset.
7388   if (OpFlag) {
7389     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7390                          DAG.getNode(X86ISD::GlobalBaseReg,
7391                                      DebugLoc(), getPointerTy()),
7392                          Result);
7393   }
7394
7395   return Result;
7396 }
7397
7398 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7399   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7400
7401   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7402   // global base reg.
7403   unsigned char OpFlag = 0;
7404   unsigned WrapperKind = X86ISD::Wrapper;
7405   CodeModel::Model M = getTargetMachine().getCodeModel();
7406
7407   if (Subtarget->isPICStyleRIPRel() &&
7408       (M == CodeModel::Small || M == CodeModel::Kernel))
7409     WrapperKind = X86ISD::WrapperRIP;
7410   else if (Subtarget->isPICStyleGOT())
7411     OpFlag = X86II::MO_GOTOFF;
7412   else if (Subtarget->isPICStyleStubPIC())
7413     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7414
7415   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7416                                           OpFlag);
7417   DebugLoc DL = JT->getDebugLoc();
7418   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7419
7420   // With PIC, the address is actually $g + Offset.
7421   if (OpFlag)
7422     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7423                          DAG.getNode(X86ISD::GlobalBaseReg,
7424                                      DebugLoc(), getPointerTy()),
7425                          Result);
7426
7427   return Result;
7428 }
7429
7430 SDValue
7431 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7432   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7433
7434   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7435   // global base reg.
7436   unsigned char OpFlag = 0;
7437   unsigned WrapperKind = X86ISD::Wrapper;
7438   CodeModel::Model M = getTargetMachine().getCodeModel();
7439
7440   if (Subtarget->isPICStyleRIPRel() &&
7441       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7442     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7443       OpFlag = X86II::MO_GOTPCREL;
7444     WrapperKind = X86ISD::WrapperRIP;
7445   } else if (Subtarget->isPICStyleGOT()) {
7446     OpFlag = X86II::MO_GOT;
7447   } else if (Subtarget->isPICStyleStubPIC()) {
7448     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7449   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7450     OpFlag = X86II::MO_DARWIN_NONLAZY;
7451   }
7452
7453   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7454
7455   DebugLoc DL = Op.getDebugLoc();
7456   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7457
7458
7459   // With PIC, the address is actually $g + Offset.
7460   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7461       !Subtarget->is64Bit()) {
7462     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7463                          DAG.getNode(X86ISD::GlobalBaseReg,
7464                                      DebugLoc(), getPointerTy()),
7465                          Result);
7466   }
7467
7468   // For symbols that require a load from a stub to get the address, emit the
7469   // load.
7470   if (isGlobalStubReference(OpFlag))
7471     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7472                          MachinePointerInfo::getGOT(), false, false, false, 0);
7473
7474   return Result;
7475 }
7476
7477 SDValue
7478 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7479   // Create the TargetBlockAddressAddress node.
7480   unsigned char OpFlags =
7481     Subtarget->ClassifyBlockAddressReference();
7482   CodeModel::Model M = getTargetMachine().getCodeModel();
7483   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7484   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7485   DebugLoc dl = Op.getDebugLoc();
7486   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7487                                              OpFlags);
7488
7489   if (Subtarget->isPICStyleRIPRel() &&
7490       (M == CodeModel::Small || M == CodeModel::Kernel))
7491     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7492   else
7493     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7494
7495   // With PIC, the address is actually $g + Offset.
7496   if (isGlobalRelativeToPICBase(OpFlags)) {
7497     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7498                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7499                          Result);
7500   }
7501
7502   return Result;
7503 }
7504
7505 SDValue
7506 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7507                                       int64_t Offset,
7508                                       SelectionDAG &DAG) const {
7509   // Create the TargetGlobalAddress node, folding in the constant
7510   // offset if it is legal.
7511   unsigned char OpFlags =
7512     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7513   CodeModel::Model M = getTargetMachine().getCodeModel();
7514   SDValue Result;
7515   if (OpFlags == X86II::MO_NO_FLAG &&
7516       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7517     // A direct static reference to a global.
7518     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7519     Offset = 0;
7520   } else {
7521     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7522   }
7523
7524   if (Subtarget->isPICStyleRIPRel() &&
7525       (M == CodeModel::Small || M == CodeModel::Kernel))
7526     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7527   else
7528     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7529
7530   // With PIC, the address is actually $g + Offset.
7531   if (isGlobalRelativeToPICBase(OpFlags)) {
7532     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7533                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7534                          Result);
7535   }
7536
7537   // For globals that require a load from a stub to get the address, emit the
7538   // load.
7539   if (isGlobalStubReference(OpFlags))
7540     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7541                          MachinePointerInfo::getGOT(), false, false, false, 0);
7542
7543   // If there was a non-zero offset that we didn't fold, create an explicit
7544   // addition for it.
7545   if (Offset != 0)
7546     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7547                          DAG.getConstant(Offset, getPointerTy()));
7548
7549   return Result;
7550 }
7551
7552 SDValue
7553 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7554   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7555   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7556   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7557 }
7558
7559 static SDValue
7560 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7561            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7562            unsigned char OperandFlags, bool LocalDynamic = false) {
7563   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7564   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7565   DebugLoc dl = GA->getDebugLoc();
7566   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7567                                            GA->getValueType(0),
7568                                            GA->getOffset(),
7569                                            OperandFlags);
7570
7571   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7572                                            : X86ISD::TLSADDR;
7573
7574   if (InFlag) {
7575     SDValue Ops[] = { Chain,  TGA, *InFlag };
7576     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7577   } else {
7578     SDValue Ops[]  = { Chain, TGA };
7579     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7580   }
7581
7582   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7583   MFI->setAdjustsStack(true);
7584
7585   SDValue Flag = Chain.getValue(1);
7586   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7587 }
7588
7589 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7590 static SDValue
7591 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7592                                 const EVT PtrVT) {
7593   SDValue InFlag;
7594   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7595   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7596                                    DAG.getNode(X86ISD::GlobalBaseReg,
7597                                                DebugLoc(), PtrVT), InFlag);
7598   InFlag = Chain.getValue(1);
7599
7600   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7601 }
7602
7603 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7604 static SDValue
7605 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7606                                 const EVT PtrVT) {
7607   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7608                     X86::RAX, X86II::MO_TLSGD);
7609 }
7610
7611 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7612                                            SelectionDAG &DAG,
7613                                            const EVT PtrVT,
7614                                            bool is64Bit) {
7615   DebugLoc dl = GA->getDebugLoc();
7616
7617   // Get the start address of the TLS block for this module.
7618   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7619       .getInfo<X86MachineFunctionInfo>();
7620   MFI->incNumLocalDynamicTLSAccesses();
7621
7622   SDValue Base;
7623   if (is64Bit) {
7624     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7625                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7626   } else {
7627     SDValue InFlag;
7628     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7629         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7630     InFlag = Chain.getValue(1);
7631     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7632                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7633   }
7634
7635   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7636   // of Base.
7637
7638   // Build x@dtpoff.
7639   unsigned char OperandFlags = X86II::MO_DTPOFF;
7640   unsigned WrapperKind = X86ISD::Wrapper;
7641   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7642                                            GA->getValueType(0),
7643                                            GA->getOffset(), OperandFlags);
7644   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7645
7646   // Add x@dtpoff with the base.
7647   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7648 }
7649
7650 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7651 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7652                                    const EVT PtrVT, TLSModel::Model model,
7653                                    bool is64Bit, bool isPIC) {
7654   DebugLoc dl = GA->getDebugLoc();
7655
7656   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7657   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7658                                                          is64Bit ? 257 : 256));
7659
7660   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7661                                       DAG.getIntPtrConstant(0),
7662                                       MachinePointerInfo(Ptr),
7663                                       false, false, false, 0);
7664
7665   unsigned char OperandFlags = 0;
7666   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7667   // initialexec.
7668   unsigned WrapperKind = X86ISD::Wrapper;
7669   if (model == TLSModel::LocalExec) {
7670     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7671   } else if (model == TLSModel::InitialExec) {
7672     if (is64Bit) {
7673       OperandFlags = X86II::MO_GOTTPOFF;
7674       WrapperKind = X86ISD::WrapperRIP;
7675     } else {
7676       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7677     }
7678   } else {
7679     llvm_unreachable("Unexpected model");
7680   }
7681
7682   // emit "addl x@ntpoff,%eax" (local exec)
7683   // or "addl x@indntpoff,%eax" (initial exec)
7684   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7685   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7686                                            GA->getValueType(0),
7687                                            GA->getOffset(), OperandFlags);
7688   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7689
7690   if (model == TLSModel::InitialExec) {
7691     if (isPIC && !is64Bit) {
7692       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7693                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7694                            Offset);
7695     }
7696
7697     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7698                          MachinePointerInfo::getGOT(), false, false, false,
7699                          0);
7700   }
7701
7702   // The address of the thread local variable is the add of the thread
7703   // pointer with the offset of the variable.
7704   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7705 }
7706
7707 SDValue
7708 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7709
7710   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7711   const GlobalValue *GV = GA->getGlobal();
7712
7713   if (Subtarget->isTargetELF()) {
7714     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7715
7716     switch (model) {
7717       case TLSModel::GeneralDynamic:
7718         if (Subtarget->is64Bit())
7719           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7720         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7721       case TLSModel::LocalDynamic:
7722         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7723                                            Subtarget->is64Bit());
7724       case TLSModel::InitialExec:
7725       case TLSModel::LocalExec:
7726         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7727                                    Subtarget->is64Bit(),
7728                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7729     }
7730     llvm_unreachable("Unknown TLS model.");
7731   }
7732
7733   if (Subtarget->isTargetDarwin()) {
7734     // Darwin only has one model of TLS.  Lower to that.
7735     unsigned char OpFlag = 0;
7736     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7737                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7738
7739     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7740     // global base reg.
7741     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7742                   !Subtarget->is64Bit();
7743     if (PIC32)
7744       OpFlag = X86II::MO_TLVP_PIC_BASE;
7745     else
7746       OpFlag = X86II::MO_TLVP;
7747     DebugLoc DL = Op.getDebugLoc();
7748     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7749                                                 GA->getValueType(0),
7750                                                 GA->getOffset(), OpFlag);
7751     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7752
7753     // With PIC32, the address is actually $g + Offset.
7754     if (PIC32)
7755       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7756                            DAG.getNode(X86ISD::GlobalBaseReg,
7757                                        DebugLoc(), getPointerTy()),
7758                            Offset);
7759
7760     // Lowering the machine isd will make sure everything is in the right
7761     // location.
7762     SDValue Chain = DAG.getEntryNode();
7763     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7764     SDValue Args[] = { Chain, Offset };
7765     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7766
7767     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7768     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7769     MFI->setAdjustsStack(true);
7770
7771     // And our return value (tls address) is in the standard call return value
7772     // location.
7773     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7774     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7775                               Chain.getValue(1));
7776   }
7777
7778   if (Subtarget->isTargetWindows()) {
7779     // Just use the implicit TLS architecture
7780     // Need to generate someting similar to:
7781     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7782     //                                  ; from TEB
7783     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7784     //   mov     rcx, qword [rdx+rcx*8]
7785     //   mov     eax, .tls$:tlsvar
7786     //   [rax+rcx] contains the address
7787     // Windows 64bit: gs:0x58
7788     // Windows 32bit: fs:__tls_array
7789
7790     // If GV is an alias then use the aliasee for determining
7791     // thread-localness.
7792     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7793       GV = GA->resolveAliasedGlobal(false);
7794     DebugLoc dl = GA->getDebugLoc();
7795     SDValue Chain = DAG.getEntryNode();
7796
7797     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7798     // %gs:0x58 (64-bit).
7799     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7800                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7801                                                              256)
7802                                         : Type::getInt32PtrTy(*DAG.getContext(),
7803                                                               257));
7804
7805     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7806                                         Subtarget->is64Bit()
7807                                         ? DAG.getIntPtrConstant(0x58)
7808                                         : DAG.getExternalSymbol("_tls_array",
7809                                                                 getPointerTy()),
7810                                         MachinePointerInfo(Ptr),
7811                                         false, false, false, 0);
7812
7813     // Load the _tls_index variable
7814     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7815     if (Subtarget->is64Bit())
7816       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7817                            IDX, MachinePointerInfo(), MVT::i32,
7818                            false, false, 0);
7819     else
7820       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7821                         false, false, false, 0);
7822
7823     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7824                                     getPointerTy());
7825     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7826
7827     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7828     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7829                       false, false, false, 0);
7830
7831     // Get the offset of start of .tls section
7832     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7833                                              GA->getValueType(0),
7834                                              GA->getOffset(), X86II::MO_SECREL);
7835     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7836
7837     // The address of the thread local variable is the add of the thread
7838     // pointer with the offset of the variable.
7839     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7840   }
7841
7842   llvm_unreachable("TLS not implemented for this target.");
7843 }
7844
7845
7846 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7847 /// and take a 2 x i32 value to shift plus a shift amount.
7848 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7849   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7850   EVT VT = Op.getValueType();
7851   unsigned VTBits = VT.getSizeInBits();
7852   DebugLoc dl = Op.getDebugLoc();
7853   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7854   SDValue ShOpLo = Op.getOperand(0);
7855   SDValue ShOpHi = Op.getOperand(1);
7856   SDValue ShAmt  = Op.getOperand(2);
7857   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7858                                      DAG.getConstant(VTBits - 1, MVT::i8))
7859                        : DAG.getConstant(0, VT);
7860
7861   SDValue Tmp2, Tmp3;
7862   if (Op.getOpcode() == ISD::SHL_PARTS) {
7863     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7864     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7865   } else {
7866     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7867     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7868   }
7869
7870   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7871                                 DAG.getConstant(VTBits, MVT::i8));
7872   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7873                              AndNode, DAG.getConstant(0, MVT::i8));
7874
7875   SDValue Hi, Lo;
7876   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7877   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7878   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7879
7880   if (Op.getOpcode() == ISD::SHL_PARTS) {
7881     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7883   } else {
7884     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7885     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7886   }
7887
7888   SDValue Ops[2] = { Lo, Hi };
7889   return DAG.getMergeValues(Ops, 2, dl);
7890 }
7891
7892 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7893                                            SelectionDAG &DAG) const {
7894   EVT SrcVT = Op.getOperand(0).getValueType();
7895
7896   if (SrcVT.isVector())
7897     return SDValue();
7898
7899   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7900          "Unknown SINT_TO_FP to lower!");
7901
7902   // These are really Legal; return the operand so the caller accepts it as
7903   // Legal.
7904   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7905     return Op;
7906   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7907       Subtarget->is64Bit()) {
7908     return Op;
7909   }
7910
7911   DebugLoc dl = Op.getDebugLoc();
7912   unsigned Size = SrcVT.getSizeInBits()/8;
7913   MachineFunction &MF = DAG.getMachineFunction();
7914   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7915   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7916   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7917                                StackSlot,
7918                                MachinePointerInfo::getFixedStack(SSFI),
7919                                false, false, 0);
7920   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7921 }
7922
7923 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7924                                      SDValue StackSlot,
7925                                      SelectionDAG &DAG) const {
7926   // Build the FILD
7927   DebugLoc DL = Op.getDebugLoc();
7928   SDVTList Tys;
7929   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7930   if (useSSE)
7931     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7932   else
7933     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7934
7935   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7936
7937   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7938   MachineMemOperand *MMO;
7939   if (FI) {
7940     int SSFI = FI->getIndex();
7941     MMO =
7942       DAG.getMachineFunction()
7943       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7944                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7945   } else {
7946     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7947     StackSlot = StackSlot.getOperand(1);
7948   }
7949   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7950   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7951                                            X86ISD::FILD, DL,
7952                                            Tys, Ops, array_lengthof(Ops),
7953                                            SrcVT, MMO);
7954
7955   if (useSSE) {
7956     Chain = Result.getValue(1);
7957     SDValue InFlag = Result.getValue(2);
7958
7959     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7960     // shouldn't be necessary except that RFP cannot be live across
7961     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7962     MachineFunction &MF = DAG.getMachineFunction();
7963     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7964     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7965     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7966     Tys = DAG.getVTList(MVT::Other);
7967     SDValue Ops[] = {
7968       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7969     };
7970     MachineMemOperand *MMO =
7971       DAG.getMachineFunction()
7972       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7973                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7974
7975     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7976                                     Ops, array_lengthof(Ops),
7977                                     Op.getValueType(), MMO);
7978     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7979                          MachinePointerInfo::getFixedStack(SSFI),
7980                          false, false, false, 0);
7981   }
7982
7983   return Result;
7984 }
7985
7986 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7987 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7988                                                SelectionDAG &DAG) const {
7989   // This algorithm is not obvious. Here it is what we're trying to output:
7990   /*
7991      movq       %rax,  %xmm0
7992      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7993      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7994      #ifdef __SSE3__
7995        haddpd   %xmm0, %xmm0
7996      #else
7997        pshufd   $0x4e, %xmm0, %xmm1
7998        addpd    %xmm1, %xmm0
7999      #endif
8000   */
8001
8002   DebugLoc dl = Op.getDebugLoc();
8003   LLVMContext *Context = DAG.getContext();
8004
8005   // Build some magic constants.
8006   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8007   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8008   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8009
8010   SmallVector<Constant*,2> CV1;
8011   CV1.push_back(
8012         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8013   CV1.push_back(
8014         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8015   Constant *C1 = ConstantVector::get(CV1);
8016   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8017
8018   // Load the 64-bit value into an XMM register.
8019   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8020                             Op.getOperand(0));
8021   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8022                               MachinePointerInfo::getConstantPool(),
8023                               false, false, false, 16);
8024   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8025                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8026                               CLod0);
8027
8028   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8029                               MachinePointerInfo::getConstantPool(),
8030                               false, false, false, 16);
8031   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8032   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8033   SDValue Result;
8034
8035   if (Subtarget->hasSSE3()) {
8036     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8037     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8038   } else {
8039     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8040     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8041                                            S2F, 0x4E, DAG);
8042     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8043                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8044                          Sub);
8045   }
8046
8047   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8048                      DAG.getIntPtrConstant(0));
8049 }
8050
8051 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8052 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8053                                                SelectionDAG &DAG) const {
8054   DebugLoc dl = Op.getDebugLoc();
8055   // FP constant to bias correct the final result.
8056   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8057                                    MVT::f64);
8058
8059   // Load the 32-bit value into an XMM register.
8060   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8061                              Op.getOperand(0));
8062
8063   // Zero out the upper parts of the register.
8064   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8065
8066   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8067                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8068                      DAG.getIntPtrConstant(0));
8069
8070   // Or the load with the bias.
8071   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8072                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074                                                    MVT::v2f64, Load)),
8075                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8076                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8077                                                    MVT::v2f64, Bias)));
8078   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8079                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8080                    DAG.getIntPtrConstant(0));
8081
8082   // Subtract the bias.
8083   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8084
8085   // Handle final rounding.
8086   EVT DestVT = Op.getValueType();
8087
8088   if (DestVT.bitsLT(MVT::f64))
8089     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8090                        DAG.getIntPtrConstant(0));
8091   if (DestVT.bitsGT(MVT::f64))
8092     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8093
8094   // Handle final rounding.
8095   return Sub;
8096 }
8097
8098 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8099                                                SelectionDAG &DAG) const {
8100   SDValue N0 = Op.getOperand(0);
8101   EVT SVT = N0.getValueType();
8102   DebugLoc dl = Op.getDebugLoc();
8103
8104   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8105           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8106          "Custom UINT_TO_FP is not supported!");
8107
8108   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8109   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8110                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8111 }
8112
8113 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8114                                            SelectionDAG &DAG) const {
8115   SDValue N0 = Op.getOperand(0);
8116   DebugLoc dl = Op.getDebugLoc();
8117
8118   if (Op.getValueType().isVector())
8119     return lowerUINT_TO_FP_vec(Op, DAG);
8120
8121   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8122   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8123   // the optimization here.
8124   if (DAG.SignBitIsZero(N0))
8125     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8126
8127   EVT SrcVT = N0.getValueType();
8128   EVT DstVT = Op.getValueType();
8129   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8130     return LowerUINT_TO_FP_i64(Op, DAG);
8131   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8132     return LowerUINT_TO_FP_i32(Op, DAG);
8133   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8134     return SDValue();
8135
8136   // Make a 64-bit buffer, and use it to build an FILD.
8137   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8138   if (SrcVT == MVT::i32) {
8139     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8140     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8141                                      getPointerTy(), StackSlot, WordOff);
8142     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8143                                   StackSlot, MachinePointerInfo(),
8144                                   false, false, 0);
8145     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8146                                   OffsetSlot, MachinePointerInfo(),
8147                                   false, false, 0);
8148     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8149     return Fild;
8150   }
8151
8152   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8153   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8154                                StackSlot, MachinePointerInfo(),
8155                                false, false, 0);
8156   // For i64 source, we need to add the appropriate power of 2 if the input
8157   // was negative.  This is the same as the optimization in
8158   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8159   // we must be careful to do the computation in x87 extended precision, not
8160   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8161   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8162   MachineMemOperand *MMO =
8163     DAG.getMachineFunction()
8164     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8165                           MachineMemOperand::MOLoad, 8, 8);
8166
8167   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8168   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8169   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8170                                          MVT::i64, MMO);
8171
8172   APInt FF(32, 0x5F800000ULL);
8173
8174   // Check whether the sign bit is set.
8175   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8176                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8177                                  ISD::SETLT);
8178
8179   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8180   SDValue FudgePtr = DAG.getConstantPool(
8181                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8182                                          getPointerTy());
8183
8184   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8185   SDValue Zero = DAG.getIntPtrConstant(0);
8186   SDValue Four = DAG.getIntPtrConstant(4);
8187   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8188                                Zero, Four);
8189   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8190
8191   // Load the value out, extending it from f32 to f80.
8192   // FIXME: Avoid the extend by constructing the right constant pool?
8193   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8194                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8195                                  MVT::f32, false, false, 4);
8196   // Extend everything to 80 bits to force it to be done on x87.
8197   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8198   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8199 }
8200
8201 std::pair<SDValue,SDValue> X86TargetLowering::
8202 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8203   DebugLoc DL = Op.getDebugLoc();
8204
8205   EVT DstTy = Op.getValueType();
8206
8207   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8208     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8209     DstTy = MVT::i64;
8210   }
8211
8212   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8213          DstTy.getSimpleVT() >= MVT::i16 &&
8214          "Unknown FP_TO_INT to lower!");
8215
8216   // These are really Legal.
8217   if (DstTy == MVT::i32 &&
8218       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8219     return std::make_pair(SDValue(), SDValue());
8220   if (Subtarget->is64Bit() &&
8221       DstTy == MVT::i64 &&
8222       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8223     return std::make_pair(SDValue(), SDValue());
8224
8225   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8226   // stack slot, or into the FTOL runtime function.
8227   MachineFunction &MF = DAG.getMachineFunction();
8228   unsigned MemSize = DstTy.getSizeInBits()/8;
8229   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8230   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8231
8232   unsigned Opc;
8233   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8234     Opc = X86ISD::WIN_FTOL;
8235   else
8236     switch (DstTy.getSimpleVT().SimpleTy) {
8237     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8238     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8239     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8240     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8241     }
8242
8243   SDValue Chain = DAG.getEntryNode();
8244   SDValue Value = Op.getOperand(0);
8245   EVT TheVT = Op.getOperand(0).getValueType();
8246   // FIXME This causes a redundant load/store if the SSE-class value is already
8247   // in memory, such as if it is on the callstack.
8248   if (isScalarFPTypeInSSEReg(TheVT)) {
8249     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8250     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8251                          MachinePointerInfo::getFixedStack(SSFI),
8252                          false, false, 0);
8253     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8254     SDValue Ops[] = {
8255       Chain, StackSlot, DAG.getValueType(TheVT)
8256     };
8257
8258     MachineMemOperand *MMO =
8259       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8260                               MachineMemOperand::MOLoad, MemSize, MemSize);
8261     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8262                                     DstTy, MMO);
8263     Chain = Value.getValue(1);
8264     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8265     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8266   }
8267
8268   MachineMemOperand *MMO =
8269     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8270                             MachineMemOperand::MOStore, MemSize, MemSize);
8271
8272   if (Opc != X86ISD::WIN_FTOL) {
8273     // Build the FP_TO_INT*_IN_MEM
8274     SDValue Ops[] = { Chain, Value, StackSlot };
8275     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8276                                            Ops, 3, DstTy, MMO);
8277     return std::make_pair(FIST, StackSlot);
8278   } else {
8279     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8280       DAG.getVTList(MVT::Other, MVT::Glue),
8281       Chain, Value);
8282     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8283       MVT::i32, ftol.getValue(1));
8284     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8285       MVT::i32, eax.getValue(2));
8286     SDValue Ops[] = { eax, edx };
8287     SDValue pair = IsReplace
8288       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8289       : DAG.getMergeValues(Ops, 2, DL);
8290     return std::make_pair(pair, SDValue());
8291   }
8292 }
8293
8294 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8295   DebugLoc DL = Op.getDebugLoc();
8296   EVT VT = Op.getValueType();
8297   SDValue In = Op.getOperand(0);
8298   EVT SVT = In.getValueType();
8299
8300   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8301       VT.getVectorNumElements() != SVT.getVectorNumElements())
8302     return SDValue();
8303
8304   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8305
8306   // AVX2 has better support of integer extending.
8307   if (Subtarget->hasAVX2())
8308     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8309
8310   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8311   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8312   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8313                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8314
8315   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8316 }
8317
8318 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8319   DebugLoc DL = Op.getDebugLoc();
8320   EVT VT = Op.getValueType();
8321   EVT SVT = Op.getOperand(0).getValueType();
8322
8323   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8324       VT.getVectorNumElements() != SVT.getVectorNumElements())
8325     return SDValue();
8326
8327   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8328
8329   unsigned NumElems = VT.getVectorNumElements();
8330   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8331                              NumElems * 2);
8332
8333   SDValue In = Op.getOperand(0);
8334   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8335   // Prepare truncation shuffle mask
8336   for (unsigned i = 0; i != NumElems; ++i)
8337     MaskVec[i] = i * 2;
8338   SDValue V = DAG.getVectorShuffle(NVT, DL,
8339                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8340                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8341   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8342                      DAG.getIntPtrConstant(0));
8343 }
8344
8345 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8346                                            SelectionDAG &DAG) const {
8347   if (Op.getValueType().isVector()) {
8348     if (Op.getValueType() == MVT::v8i16)
8349       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8350                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8351                                      MVT::v8i32, Op.getOperand(0)));
8352     return SDValue();
8353   }
8354
8355   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8356     /*IsSigned=*/ true, /*IsReplace=*/ false);
8357   SDValue FIST = Vals.first, StackSlot = Vals.second;
8358   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8359   if (FIST.getNode() == 0) return Op;
8360
8361   if (StackSlot.getNode())
8362     // Load the result.
8363     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8364                        FIST, StackSlot, MachinePointerInfo(),
8365                        false, false, false, 0);
8366
8367   // The node is the result.
8368   return FIST;
8369 }
8370
8371 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8372                                            SelectionDAG &DAG) const {
8373   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8374     /*IsSigned=*/ false, /*IsReplace=*/ false);
8375   SDValue FIST = Vals.first, StackSlot = Vals.second;
8376   assert(FIST.getNode() && "Unexpected failure");
8377
8378   if (StackSlot.getNode())
8379     // Load the result.
8380     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8381                        FIST, StackSlot, MachinePointerInfo(),
8382                        false, false, false, 0);
8383
8384   // The node is the result.
8385   return FIST;
8386 }
8387
8388 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8389                                           SelectionDAG &DAG) const {
8390   DebugLoc DL = Op.getDebugLoc();
8391   EVT VT = Op.getValueType();
8392   SDValue In = Op.getOperand(0);
8393   EVT SVT = In.getValueType();
8394
8395   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8396
8397   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8398                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8399                                  In, DAG.getUNDEF(SVT)));
8400 }
8401
8402 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8403   LLVMContext *Context = DAG.getContext();
8404   DebugLoc dl = Op.getDebugLoc();
8405   EVT VT = Op.getValueType();
8406   EVT EltVT = VT;
8407   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8408   if (VT.isVector()) {
8409     EltVT = VT.getVectorElementType();
8410     NumElts = VT.getVectorNumElements();
8411   }
8412   Constant *C;
8413   if (EltVT == MVT::f64)
8414     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8415   else
8416     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8417   C = ConstantVector::getSplat(NumElts, C);
8418   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8419   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8420   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8421                              MachinePointerInfo::getConstantPool(),
8422                              false, false, false, Alignment);
8423   if (VT.isVector()) {
8424     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8425     return DAG.getNode(ISD::BITCAST, dl, VT,
8426                        DAG.getNode(ISD::AND, dl, ANDVT,
8427                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8428                                                Op.getOperand(0)),
8429                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8430   }
8431   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8432 }
8433
8434 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8435   LLVMContext *Context = DAG.getContext();
8436   DebugLoc dl = Op.getDebugLoc();
8437   EVT VT = Op.getValueType();
8438   EVT EltVT = VT;
8439   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8440   if (VT.isVector()) {
8441     EltVT = VT.getVectorElementType();
8442     NumElts = VT.getVectorNumElements();
8443   }
8444   Constant *C;
8445   if (EltVT == MVT::f64)
8446     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8447   else
8448     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8449   C = ConstantVector::getSplat(NumElts, C);
8450   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8451   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8452   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8453                              MachinePointerInfo::getConstantPool(),
8454                              false, false, false, Alignment);
8455   if (VT.isVector()) {
8456     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8457     return DAG.getNode(ISD::BITCAST, dl, VT,
8458                        DAG.getNode(ISD::XOR, dl, XORVT,
8459                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8460                                                Op.getOperand(0)),
8461                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8462   }
8463
8464   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8465 }
8466
8467 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8468   LLVMContext *Context = DAG.getContext();
8469   SDValue Op0 = Op.getOperand(0);
8470   SDValue Op1 = Op.getOperand(1);
8471   DebugLoc dl = Op.getDebugLoc();
8472   EVT VT = Op.getValueType();
8473   EVT SrcVT = Op1.getValueType();
8474
8475   // If second operand is smaller, extend it first.
8476   if (SrcVT.bitsLT(VT)) {
8477     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8478     SrcVT = VT;
8479   }
8480   // And if it is bigger, shrink it first.
8481   if (SrcVT.bitsGT(VT)) {
8482     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8483     SrcVT = VT;
8484   }
8485
8486   // At this point the operands and the result should have the same
8487   // type, and that won't be f80 since that is not custom lowered.
8488
8489   // First get the sign bit of second operand.
8490   SmallVector<Constant*,4> CV;
8491   if (SrcVT == MVT::f64) {
8492     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8493     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8494   } else {
8495     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8496     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8497     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8498     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8499   }
8500   Constant *C = ConstantVector::get(CV);
8501   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8502   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8503                               MachinePointerInfo::getConstantPool(),
8504                               false, false, false, 16);
8505   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8506
8507   // Shift sign bit right or left if the two operands have different types.
8508   if (SrcVT.bitsGT(VT)) {
8509     // Op0 is MVT::f32, Op1 is MVT::f64.
8510     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8511     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8512                           DAG.getConstant(32, MVT::i32));
8513     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8514     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8515                           DAG.getIntPtrConstant(0));
8516   }
8517
8518   // Clear first operand sign bit.
8519   CV.clear();
8520   if (VT == MVT::f64) {
8521     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8522     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8523   } else {
8524     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8525     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8526     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8527     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8528   }
8529   C = ConstantVector::get(CV);
8530   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8531   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8532                               MachinePointerInfo::getConstantPool(),
8533                               false, false, false, 16);
8534   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8535
8536   // Or the value with the sign bit.
8537   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8538 }
8539
8540 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8541   SDValue N0 = Op.getOperand(0);
8542   DebugLoc dl = Op.getDebugLoc();
8543   EVT VT = Op.getValueType();
8544
8545   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8546   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8547                                   DAG.getConstant(1, VT));
8548   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8549 }
8550
8551 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8552 //
8553 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8554   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8555
8556   if (!Subtarget->hasSSE41())
8557     return SDValue();
8558
8559   if (!Op->hasOneUse())
8560     return SDValue();
8561
8562   SDNode *N = Op.getNode();
8563   DebugLoc DL = N->getDebugLoc();
8564
8565   SmallVector<SDValue, 8> Opnds;
8566   DenseMap<SDValue, unsigned> VecInMap;
8567   EVT VT = MVT::Other;
8568
8569   // Recognize a special case where a vector is casted into wide integer to
8570   // test all 0s.
8571   Opnds.push_back(N->getOperand(0));
8572   Opnds.push_back(N->getOperand(1));
8573
8574   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8575     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8576     // BFS traverse all OR'd operands.
8577     if (I->getOpcode() == ISD::OR) {
8578       Opnds.push_back(I->getOperand(0));
8579       Opnds.push_back(I->getOperand(1));
8580       // Re-evaluate the number of nodes to be traversed.
8581       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8582       continue;
8583     }
8584
8585     // Quit if a non-EXTRACT_VECTOR_ELT
8586     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8587       return SDValue();
8588
8589     // Quit if without a constant index.
8590     SDValue Idx = I->getOperand(1);
8591     if (!isa<ConstantSDNode>(Idx))
8592       return SDValue();
8593
8594     SDValue ExtractedFromVec = I->getOperand(0);
8595     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8596     if (M == VecInMap.end()) {
8597       VT = ExtractedFromVec.getValueType();
8598       // Quit if not 128/256-bit vector.
8599       if (!VT.is128BitVector() && !VT.is256BitVector())
8600         return SDValue();
8601       // Quit if not the same type.
8602       if (VecInMap.begin() != VecInMap.end() &&
8603           VT != VecInMap.begin()->first.getValueType())
8604         return SDValue();
8605       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8606     }
8607     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8608   }
8609
8610   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8611          "Not extracted from 128-/256-bit vector.");
8612
8613   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8614   SmallVector<SDValue, 8> VecIns;
8615
8616   for (DenseMap<SDValue, unsigned>::const_iterator
8617         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8618     // Quit if not all elements are used.
8619     if (I->second != FullMask)
8620       return SDValue();
8621     VecIns.push_back(I->first);
8622   }
8623
8624   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8625
8626   // Cast all vectors into TestVT for PTEST.
8627   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8628     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8629
8630   // If more than one full vectors are evaluated, OR them first before PTEST.
8631   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8632     // Each iteration will OR 2 nodes and append the result until there is only
8633     // 1 node left, i.e. the final OR'd value of all vectors.
8634     SDValue LHS = VecIns[Slot];
8635     SDValue RHS = VecIns[Slot + 1];
8636     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8637   }
8638
8639   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8640                      VecIns.back(), VecIns.back());
8641 }
8642
8643 /// Emit nodes that will be selected as "test Op0,Op0", or something
8644 /// equivalent.
8645 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8646                                     SelectionDAG &DAG) const {
8647   DebugLoc dl = Op.getDebugLoc();
8648
8649   // CF and OF aren't always set the way we want. Determine which
8650   // of these we need.
8651   bool NeedCF = false;
8652   bool NeedOF = false;
8653   switch (X86CC) {
8654   default: break;
8655   case X86::COND_A: case X86::COND_AE:
8656   case X86::COND_B: case X86::COND_BE:
8657     NeedCF = true;
8658     break;
8659   case X86::COND_G: case X86::COND_GE:
8660   case X86::COND_L: case X86::COND_LE:
8661   case X86::COND_O: case X86::COND_NO:
8662     NeedOF = true;
8663     break;
8664   }
8665
8666   // See if we can use the EFLAGS value from the operand instead of
8667   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8668   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8669   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8670     // Emit a CMP with 0, which is the TEST pattern.
8671     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8672                        DAG.getConstant(0, Op.getValueType()));
8673
8674   unsigned Opcode = 0;
8675   unsigned NumOperands = 0;
8676
8677   // Truncate operations may prevent the merge of the SETCC instruction
8678   // and the arithmetic intruction before it. Attempt to truncate the operands
8679   // of the arithmetic instruction and use a reduced bit-width instruction.
8680   bool NeedTruncation = false;
8681   SDValue ArithOp = Op;
8682   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8683     SDValue Arith = Op->getOperand(0);
8684     // Both the trunc and the arithmetic op need to have one user each.
8685     if (Arith->hasOneUse())
8686       switch (Arith.getOpcode()) {
8687         default: break;
8688         case ISD::ADD:
8689         case ISD::SUB:
8690         case ISD::AND:
8691         case ISD::OR:
8692         case ISD::XOR: {
8693           NeedTruncation = true;
8694           ArithOp = Arith;
8695         }
8696       }
8697   }
8698
8699   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8700   // which may be the result of a CAST.  We use the variable 'Op', which is the
8701   // non-casted variable when we check for possible users.
8702   switch (ArithOp.getOpcode()) {
8703   case ISD::ADD:
8704     // Due to an isel shortcoming, be conservative if this add is likely to be
8705     // selected as part of a load-modify-store instruction. When the root node
8706     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8707     // uses of other nodes in the match, such as the ADD in this case. This
8708     // leads to the ADD being left around and reselected, with the result being
8709     // two adds in the output.  Alas, even if none our users are stores, that
8710     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8711     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8712     // climbing the DAG back to the root, and it doesn't seem to be worth the
8713     // effort.
8714     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8715          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8716       if (UI->getOpcode() != ISD::CopyToReg &&
8717           UI->getOpcode() != ISD::SETCC &&
8718           UI->getOpcode() != ISD::STORE)
8719         goto default_case;
8720
8721     if (ConstantSDNode *C =
8722         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8723       // An add of one will be selected as an INC.
8724       if (C->getAPIntValue() == 1) {
8725         Opcode = X86ISD::INC;
8726         NumOperands = 1;
8727         break;
8728       }
8729
8730       // An add of negative one (subtract of one) will be selected as a DEC.
8731       if (C->getAPIntValue().isAllOnesValue()) {
8732         Opcode = X86ISD::DEC;
8733         NumOperands = 1;
8734         break;
8735       }
8736     }
8737
8738     // Otherwise use a regular EFLAGS-setting add.
8739     Opcode = X86ISD::ADD;
8740     NumOperands = 2;
8741     break;
8742   case ISD::AND: {
8743     // If the primary and result isn't used, don't bother using X86ISD::AND,
8744     // because a TEST instruction will be better.
8745     bool NonFlagUse = false;
8746     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8747            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8748       SDNode *User = *UI;
8749       unsigned UOpNo = UI.getOperandNo();
8750       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8751         // Look pass truncate.
8752         UOpNo = User->use_begin().getOperandNo();
8753         User = *User->use_begin();
8754       }
8755
8756       if (User->getOpcode() != ISD::BRCOND &&
8757           User->getOpcode() != ISD::SETCC &&
8758           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8759         NonFlagUse = true;
8760         break;
8761       }
8762     }
8763
8764     if (!NonFlagUse)
8765       break;
8766   }
8767     // FALL THROUGH
8768   case ISD::SUB:
8769   case ISD::OR:
8770   case ISD::XOR:
8771     // Due to the ISEL shortcoming noted above, be conservative if this op is
8772     // likely to be selected as part of a load-modify-store instruction.
8773     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8774            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8775       if (UI->getOpcode() == ISD::STORE)
8776         goto default_case;
8777
8778     // Otherwise use a regular EFLAGS-setting instruction.
8779     switch (ArithOp.getOpcode()) {
8780     default: llvm_unreachable("unexpected operator!");
8781     case ISD::SUB: Opcode = X86ISD::SUB; break;
8782     case ISD::XOR: Opcode = X86ISD::XOR; break;
8783     case ISD::AND: Opcode = X86ISD::AND; break;
8784     case ISD::OR: {
8785       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8786         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8787         if (EFLAGS.getNode())
8788           return EFLAGS;
8789       }
8790       Opcode = X86ISD::OR;
8791       break;
8792     }
8793     }
8794
8795     NumOperands = 2;
8796     break;
8797   case X86ISD::ADD:
8798   case X86ISD::SUB:
8799   case X86ISD::INC:
8800   case X86ISD::DEC:
8801   case X86ISD::OR:
8802   case X86ISD::XOR:
8803   case X86ISD::AND:
8804     return SDValue(Op.getNode(), 1);
8805   default:
8806   default_case:
8807     break;
8808   }
8809
8810   // If we found that truncation is beneficial, perform the truncation and
8811   // update 'Op'.
8812   if (NeedTruncation) {
8813     EVT VT = Op.getValueType();
8814     SDValue WideVal = Op->getOperand(0);
8815     EVT WideVT = WideVal.getValueType();
8816     unsigned ConvertedOp = 0;
8817     // Use a target machine opcode to prevent further DAGCombine
8818     // optimizations that may separate the arithmetic operations
8819     // from the setcc node.
8820     switch (WideVal.getOpcode()) {
8821       default: break;
8822       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8823       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8824       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8825       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8826       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8827     }
8828
8829     if (ConvertedOp) {
8830       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8831       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8832         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8833         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8834         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8835       }
8836     }
8837   }
8838
8839   if (Opcode == 0)
8840     // Emit a CMP with 0, which is the TEST pattern.
8841     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8842                        DAG.getConstant(0, Op.getValueType()));
8843
8844   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8845   SmallVector<SDValue, 4> Ops;
8846   for (unsigned i = 0; i != NumOperands; ++i)
8847     Ops.push_back(Op.getOperand(i));
8848
8849   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8850   DAG.ReplaceAllUsesWith(Op, New);
8851   return SDValue(New.getNode(), 1);
8852 }
8853
8854 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8855 /// equivalent.
8856 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8857                                    SelectionDAG &DAG) const {
8858   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8859     if (C->getAPIntValue() == 0)
8860       return EmitTest(Op0, X86CC, DAG);
8861
8862   DebugLoc dl = Op0.getDebugLoc();
8863   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8864        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8865     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8866     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8867     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8868                               Op0, Op1);
8869     return SDValue(Sub.getNode(), 1);
8870   }
8871   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8872 }
8873
8874 /// Convert a comparison if required by the subtarget.
8875 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8876                                                  SelectionDAG &DAG) const {
8877   // If the subtarget does not support the FUCOMI instruction, floating-point
8878   // comparisons have to be converted.
8879   if (Subtarget->hasCMov() ||
8880       Cmp.getOpcode() != X86ISD::CMP ||
8881       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8882       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8883     return Cmp;
8884
8885   // The instruction selector will select an FUCOM instruction instead of
8886   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8887   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8888   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8889   DebugLoc dl = Cmp.getDebugLoc();
8890   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8891   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8892   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8893                             DAG.getConstant(8, MVT::i8));
8894   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8895   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8896 }
8897
8898 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8899 /// if it's possible.
8900 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8901                                      DebugLoc dl, SelectionDAG &DAG) const {
8902   SDValue Op0 = And.getOperand(0);
8903   SDValue Op1 = And.getOperand(1);
8904   if (Op0.getOpcode() == ISD::TRUNCATE)
8905     Op0 = Op0.getOperand(0);
8906   if (Op1.getOpcode() == ISD::TRUNCATE)
8907     Op1 = Op1.getOperand(0);
8908
8909   SDValue LHS, RHS;
8910   if (Op1.getOpcode() == ISD::SHL)
8911     std::swap(Op0, Op1);
8912   if (Op0.getOpcode() == ISD::SHL) {
8913     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8914       if (And00C->getZExtValue() == 1) {
8915         // If we looked past a truncate, check that it's only truncating away
8916         // known zeros.
8917         unsigned BitWidth = Op0.getValueSizeInBits();
8918         unsigned AndBitWidth = And.getValueSizeInBits();
8919         if (BitWidth > AndBitWidth) {
8920           APInt Zeros, Ones;
8921           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8922           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8923             return SDValue();
8924         }
8925         LHS = Op1;
8926         RHS = Op0.getOperand(1);
8927       }
8928   } else if (Op1.getOpcode() == ISD::Constant) {
8929     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8930     uint64_t AndRHSVal = AndRHS->getZExtValue();
8931     SDValue AndLHS = Op0;
8932
8933     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8934       LHS = AndLHS.getOperand(0);
8935       RHS = AndLHS.getOperand(1);
8936     }
8937
8938     // Use BT if the immediate can't be encoded in a TEST instruction.
8939     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8940       LHS = AndLHS;
8941       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8942     }
8943   }
8944
8945   if (LHS.getNode()) {
8946     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8947     // instruction.  Since the shift amount is in-range-or-undefined, we know
8948     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8949     // the encoding for the i16 version is larger than the i32 version.
8950     // Also promote i16 to i32 for performance / code size reason.
8951     if (LHS.getValueType() == MVT::i8 ||
8952         LHS.getValueType() == MVT::i16)
8953       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8954
8955     // If the operand types disagree, extend the shift amount to match.  Since
8956     // BT ignores high bits (like shifts) we can use anyextend.
8957     if (LHS.getValueType() != RHS.getValueType())
8958       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8959
8960     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8961     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8962     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8963                        DAG.getConstant(Cond, MVT::i8), BT);
8964   }
8965
8966   return SDValue();
8967 }
8968
8969 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8970
8971   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8972
8973   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8974   SDValue Op0 = Op.getOperand(0);
8975   SDValue Op1 = Op.getOperand(1);
8976   DebugLoc dl = Op.getDebugLoc();
8977   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8978
8979   // Optimize to BT if possible.
8980   // Lower (X & (1 << N)) == 0 to BT(X, N).
8981   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8982   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8983   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8984       Op1.getOpcode() == ISD::Constant &&
8985       cast<ConstantSDNode>(Op1)->isNullValue() &&
8986       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8987     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8988     if (NewSetCC.getNode())
8989       return NewSetCC;
8990   }
8991
8992   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8993   // these.
8994   if (Op1.getOpcode() == ISD::Constant &&
8995       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8996        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8997       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8998
8999     // If the input is a setcc, then reuse the input setcc or use a new one with
9000     // the inverted condition.
9001     if (Op0.getOpcode() == X86ISD::SETCC) {
9002       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9003       bool Invert = (CC == ISD::SETNE) ^
9004         cast<ConstantSDNode>(Op1)->isNullValue();
9005       if (!Invert) return Op0;
9006
9007       CCode = X86::GetOppositeBranchCondition(CCode);
9008       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9009                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9010     }
9011   }
9012
9013   bool isFP = Op1.getValueType().isFloatingPoint();
9014   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9015   if (X86CC == X86::COND_INVALID)
9016     return SDValue();
9017
9018   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9019   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9020   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9021                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9022 }
9023
9024 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9025 // ones, and then concatenate the result back.
9026 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9027   EVT VT = Op.getValueType();
9028
9029   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9030          "Unsupported value type for operation");
9031
9032   unsigned NumElems = VT.getVectorNumElements();
9033   DebugLoc dl = Op.getDebugLoc();
9034   SDValue CC = Op.getOperand(2);
9035
9036   // Extract the LHS vectors
9037   SDValue LHS = Op.getOperand(0);
9038   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9039   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9040
9041   // Extract the RHS vectors
9042   SDValue RHS = Op.getOperand(1);
9043   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9044   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9045
9046   // Issue the operation on the smaller types and concatenate the result back
9047   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9048   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9049   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9050                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9051                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9052 }
9053
9054
9055 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9056   SDValue Cond;
9057   SDValue Op0 = Op.getOperand(0);
9058   SDValue Op1 = Op.getOperand(1);
9059   SDValue CC = Op.getOperand(2);
9060   EVT VT = Op.getValueType();
9061   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9062   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9063   DebugLoc dl = Op.getDebugLoc();
9064
9065   if (isFP) {
9066 #ifndef NDEBUG
9067     EVT EltVT = Op0.getValueType().getVectorElementType();
9068     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9069 #endif
9070
9071     unsigned SSECC;
9072     bool Swap = false;
9073
9074     // SSE Condition code mapping:
9075     //  0 - EQ
9076     //  1 - LT
9077     //  2 - LE
9078     //  3 - UNORD
9079     //  4 - NEQ
9080     //  5 - NLT
9081     //  6 - NLE
9082     //  7 - ORD
9083     switch (SetCCOpcode) {
9084     default: llvm_unreachable("Unexpected SETCC condition");
9085     case ISD::SETOEQ:
9086     case ISD::SETEQ:  SSECC = 0; break;
9087     case ISD::SETOGT:
9088     case ISD::SETGT: Swap = true; // Fallthrough
9089     case ISD::SETLT:
9090     case ISD::SETOLT: SSECC = 1; break;
9091     case ISD::SETOGE:
9092     case ISD::SETGE: Swap = true; // Fallthrough
9093     case ISD::SETLE:
9094     case ISD::SETOLE: SSECC = 2; break;
9095     case ISD::SETUO:  SSECC = 3; break;
9096     case ISD::SETUNE:
9097     case ISD::SETNE:  SSECC = 4; break;
9098     case ISD::SETULE: Swap = true; // Fallthrough
9099     case ISD::SETUGE: SSECC = 5; break;
9100     case ISD::SETULT: Swap = true; // Fallthrough
9101     case ISD::SETUGT: SSECC = 6; break;
9102     case ISD::SETO:   SSECC = 7; break;
9103     case ISD::SETUEQ:
9104     case ISD::SETONE: SSECC = 8; break;
9105     }
9106     if (Swap)
9107       std::swap(Op0, Op1);
9108
9109     // In the two special cases we can't handle, emit two comparisons.
9110     if (SSECC == 8) {
9111       unsigned CC0, CC1;
9112       unsigned CombineOpc;
9113       if (SetCCOpcode == ISD::SETUEQ) {
9114         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9115       } else {
9116         assert(SetCCOpcode == ISD::SETONE);
9117         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9118       }
9119
9120       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9121                                  DAG.getConstant(CC0, MVT::i8));
9122       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9123                                  DAG.getConstant(CC1, MVT::i8));
9124       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9125     }
9126     // Handle all other FP comparisons here.
9127     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9128                        DAG.getConstant(SSECC, MVT::i8));
9129   }
9130
9131   // Break 256-bit integer vector compare into smaller ones.
9132   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9133     return Lower256IntVSETCC(Op, DAG);
9134
9135   // We are handling one of the integer comparisons here.  Since SSE only has
9136   // GT and EQ comparisons for integer, swapping operands and multiple
9137   // operations may be required for some comparisons.
9138   unsigned Opc;
9139   bool Swap = false, Invert = false, FlipSigns = false;
9140
9141   switch (SetCCOpcode) {
9142   default: llvm_unreachable("Unexpected SETCC condition");
9143   case ISD::SETNE:  Invert = true;
9144   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9145   case ISD::SETLT:  Swap = true;
9146   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9147   case ISD::SETGE:  Swap = true;
9148   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9149   case ISD::SETULT: Swap = true;
9150   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9151   case ISD::SETUGE: Swap = true;
9152   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9153   }
9154   if (Swap)
9155     std::swap(Op0, Op1);
9156
9157   // Check that the operation in question is available (most are plain SSE2,
9158   // but PCMPGTQ and PCMPEQQ have different requirements).
9159   if (VT == MVT::v2i64) {
9160     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9161       return SDValue();
9162     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9163       return SDValue();
9164   }
9165
9166   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9167   // bits of the inputs before performing those operations.
9168   if (FlipSigns) {
9169     EVT EltVT = VT.getVectorElementType();
9170     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9171                                       EltVT);
9172     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9173     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9174                                     SignBits.size());
9175     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9176     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9177   }
9178
9179   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9180
9181   // If the logical-not of the result is required, perform that now.
9182   if (Invert)
9183     Result = DAG.getNOT(dl, Result, VT);
9184
9185   return Result;
9186 }
9187
9188 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9189 static bool isX86LogicalCmp(SDValue Op) {
9190   unsigned Opc = Op.getNode()->getOpcode();
9191   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9192       Opc == X86ISD::SAHF)
9193     return true;
9194   if (Op.getResNo() == 1 &&
9195       (Opc == X86ISD::ADD ||
9196        Opc == X86ISD::SUB ||
9197        Opc == X86ISD::ADC ||
9198        Opc == X86ISD::SBB ||
9199        Opc == X86ISD::SMUL ||
9200        Opc == X86ISD::UMUL ||
9201        Opc == X86ISD::INC ||
9202        Opc == X86ISD::DEC ||
9203        Opc == X86ISD::OR ||
9204        Opc == X86ISD::XOR ||
9205        Opc == X86ISD::AND))
9206     return true;
9207
9208   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9209     return true;
9210
9211   return false;
9212 }
9213
9214 static bool isZero(SDValue V) {
9215   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9216   return C && C->isNullValue();
9217 }
9218
9219 static bool isAllOnes(SDValue V) {
9220   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9221   return C && C->isAllOnesValue();
9222 }
9223
9224 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9225   if (V.getOpcode() != ISD::TRUNCATE)
9226     return false;
9227
9228   SDValue VOp0 = V.getOperand(0);
9229   unsigned InBits = VOp0.getValueSizeInBits();
9230   unsigned Bits = V.getValueSizeInBits();
9231   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9232 }
9233
9234 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9235   bool addTest = true;
9236   SDValue Cond  = Op.getOperand(0);
9237   SDValue Op1 = Op.getOperand(1);
9238   SDValue Op2 = Op.getOperand(2);
9239   DebugLoc DL = Op.getDebugLoc();
9240   SDValue CC;
9241
9242   if (Cond.getOpcode() == ISD::SETCC) {
9243     SDValue NewCond = LowerSETCC(Cond, DAG);
9244     if (NewCond.getNode())
9245       Cond = NewCond;
9246   }
9247
9248   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9249   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9250   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9251   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9252   if (Cond.getOpcode() == X86ISD::SETCC &&
9253       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9254       isZero(Cond.getOperand(1).getOperand(1))) {
9255     SDValue Cmp = Cond.getOperand(1);
9256
9257     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9258
9259     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9260         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9261       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9262
9263       SDValue CmpOp0 = Cmp.getOperand(0);
9264       // Apply further optimizations for special cases
9265       // (select (x != 0), -1, 0) -> neg & sbb
9266       // (select (x == 0), 0, -1) -> neg & sbb
9267       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9268         if (YC->isNullValue() &&
9269             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9270           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9271           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9272                                     DAG.getConstant(0, CmpOp0.getValueType()),
9273                                     CmpOp0);
9274           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9275                                     DAG.getConstant(X86::COND_B, MVT::i8),
9276                                     SDValue(Neg.getNode(), 1));
9277           return Res;
9278         }
9279
9280       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9281                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9282       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9283
9284       SDValue Res =   // Res = 0 or -1.
9285         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9286                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9287
9288       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9289         Res = DAG.getNOT(DL, Res, Res.getValueType());
9290
9291       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9292       if (N2C == 0 || !N2C->isNullValue())
9293         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9294       return Res;
9295     }
9296   }
9297
9298   // Look past (and (setcc_carry (cmp ...)), 1).
9299   if (Cond.getOpcode() == ISD::AND &&
9300       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9301     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9302     if (C && C->getAPIntValue() == 1)
9303       Cond = Cond.getOperand(0);
9304   }
9305
9306   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9307   // setting operand in place of the X86ISD::SETCC.
9308   unsigned CondOpcode = Cond.getOpcode();
9309   if (CondOpcode == X86ISD::SETCC ||
9310       CondOpcode == X86ISD::SETCC_CARRY) {
9311     CC = Cond.getOperand(0);
9312
9313     SDValue Cmp = Cond.getOperand(1);
9314     unsigned Opc = Cmp.getOpcode();
9315     EVT VT = Op.getValueType();
9316
9317     bool IllegalFPCMov = false;
9318     if (VT.isFloatingPoint() && !VT.isVector() &&
9319         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9320       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9321
9322     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9323         Opc == X86ISD::BT) { // FIXME
9324       Cond = Cmp;
9325       addTest = false;
9326     }
9327   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9328              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9329              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9330               Cond.getOperand(0).getValueType() != MVT::i8)) {
9331     SDValue LHS = Cond.getOperand(0);
9332     SDValue RHS = Cond.getOperand(1);
9333     unsigned X86Opcode;
9334     unsigned X86Cond;
9335     SDVTList VTs;
9336     switch (CondOpcode) {
9337     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9338     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9339     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9340     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9341     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9342     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9343     default: llvm_unreachable("unexpected overflowing operator");
9344     }
9345     if (CondOpcode == ISD::UMULO)
9346       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9347                           MVT::i32);
9348     else
9349       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9350
9351     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9352
9353     if (CondOpcode == ISD::UMULO)
9354       Cond = X86Op.getValue(2);
9355     else
9356       Cond = X86Op.getValue(1);
9357
9358     CC = DAG.getConstant(X86Cond, MVT::i8);
9359     addTest = false;
9360   }
9361
9362   if (addTest) {
9363     // Look pass the truncate if the high bits are known zero.
9364     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9365         Cond = Cond.getOperand(0);
9366
9367     // We know the result of AND is compared against zero. Try to match
9368     // it to BT.
9369     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9370       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9371       if (NewSetCC.getNode()) {
9372         CC = NewSetCC.getOperand(0);
9373         Cond = NewSetCC.getOperand(1);
9374         addTest = false;
9375       }
9376     }
9377   }
9378
9379   if (addTest) {
9380     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9381     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9382   }
9383
9384   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9385   // a <  b ?  0 : -1 -> RES = setcc_carry
9386   // a >= b ? -1 :  0 -> RES = setcc_carry
9387   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9388   if (Cond.getOpcode() == X86ISD::SUB) {
9389     Cond = ConvertCmpIfNecessary(Cond, DAG);
9390     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9391
9392     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9393         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9394       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9395                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9396       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9397         return DAG.getNOT(DL, Res, Res.getValueType());
9398       return Res;
9399     }
9400   }
9401
9402   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9403   // widen the cmov and push the truncate through. This avoids introducing a new
9404   // branch during isel and doesn't add any extensions.
9405   if (Op.getValueType() == MVT::i8 &&
9406       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9407     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9408     if (T1.getValueType() == T2.getValueType() &&
9409         // Blacklist CopyFromReg to avoid partial register stalls.
9410         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9411       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9412       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9413       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9414     }
9415   }
9416
9417   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9418   // condition is true.
9419   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9420   SDValue Ops[] = { Op2, Op1, CC, Cond };
9421   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9422 }
9423
9424 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9425 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9426 // from the AND / OR.
9427 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9428   Opc = Op.getOpcode();
9429   if (Opc != ISD::OR && Opc != ISD::AND)
9430     return false;
9431   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9432           Op.getOperand(0).hasOneUse() &&
9433           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9434           Op.getOperand(1).hasOneUse());
9435 }
9436
9437 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9438 // 1 and that the SETCC node has a single use.
9439 static bool isXor1OfSetCC(SDValue Op) {
9440   if (Op.getOpcode() != ISD::XOR)
9441     return false;
9442   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9443   if (N1C && N1C->getAPIntValue() == 1) {
9444     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9445       Op.getOperand(0).hasOneUse();
9446   }
9447   return false;
9448 }
9449
9450 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9451   bool addTest = true;
9452   SDValue Chain = Op.getOperand(0);
9453   SDValue Cond  = Op.getOperand(1);
9454   SDValue Dest  = Op.getOperand(2);
9455   DebugLoc dl = Op.getDebugLoc();
9456   SDValue CC;
9457   bool Inverted = false;
9458
9459   if (Cond.getOpcode() == ISD::SETCC) {
9460     // Check for setcc([su]{add,sub,mul}o == 0).
9461     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9462         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9463         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9464         Cond.getOperand(0).getResNo() == 1 &&
9465         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9466          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9467          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9468          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9469          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9470          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9471       Inverted = true;
9472       Cond = Cond.getOperand(0);
9473     } else {
9474       SDValue NewCond = LowerSETCC(Cond, DAG);
9475       if (NewCond.getNode())
9476         Cond = NewCond;
9477     }
9478   }
9479 #if 0
9480   // FIXME: LowerXALUO doesn't handle these!!
9481   else if (Cond.getOpcode() == X86ISD::ADD  ||
9482            Cond.getOpcode() == X86ISD::SUB  ||
9483            Cond.getOpcode() == X86ISD::SMUL ||
9484            Cond.getOpcode() == X86ISD::UMUL)
9485     Cond = LowerXALUO(Cond, DAG);
9486 #endif
9487
9488   // Look pass (and (setcc_carry (cmp ...)), 1).
9489   if (Cond.getOpcode() == ISD::AND &&
9490       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9491     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9492     if (C && C->getAPIntValue() == 1)
9493       Cond = Cond.getOperand(0);
9494   }
9495
9496   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9497   // setting operand in place of the X86ISD::SETCC.
9498   unsigned CondOpcode = Cond.getOpcode();
9499   if (CondOpcode == X86ISD::SETCC ||
9500       CondOpcode == X86ISD::SETCC_CARRY) {
9501     CC = Cond.getOperand(0);
9502
9503     SDValue Cmp = Cond.getOperand(1);
9504     unsigned Opc = Cmp.getOpcode();
9505     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9506     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9507       Cond = Cmp;
9508       addTest = false;
9509     } else {
9510       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9511       default: break;
9512       case X86::COND_O:
9513       case X86::COND_B:
9514         // These can only come from an arithmetic instruction with overflow,
9515         // e.g. SADDO, UADDO.
9516         Cond = Cond.getNode()->getOperand(1);
9517         addTest = false;
9518         break;
9519       }
9520     }
9521   }
9522   CondOpcode = Cond.getOpcode();
9523   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9524       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9525       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9526        Cond.getOperand(0).getValueType() != MVT::i8)) {
9527     SDValue LHS = Cond.getOperand(0);
9528     SDValue RHS = Cond.getOperand(1);
9529     unsigned X86Opcode;
9530     unsigned X86Cond;
9531     SDVTList VTs;
9532     switch (CondOpcode) {
9533     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9534     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9535     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9536     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9537     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9538     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9539     default: llvm_unreachable("unexpected overflowing operator");
9540     }
9541     if (Inverted)
9542       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9543     if (CondOpcode == ISD::UMULO)
9544       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9545                           MVT::i32);
9546     else
9547       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9548
9549     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9550
9551     if (CondOpcode == ISD::UMULO)
9552       Cond = X86Op.getValue(2);
9553     else
9554       Cond = X86Op.getValue(1);
9555
9556     CC = DAG.getConstant(X86Cond, MVT::i8);
9557     addTest = false;
9558   } else {
9559     unsigned CondOpc;
9560     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9561       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9562       if (CondOpc == ISD::OR) {
9563         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9564         // two branches instead of an explicit OR instruction with a
9565         // separate test.
9566         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9567             isX86LogicalCmp(Cmp)) {
9568           CC = Cond.getOperand(0).getOperand(0);
9569           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9570                               Chain, Dest, CC, Cmp);
9571           CC = Cond.getOperand(1).getOperand(0);
9572           Cond = Cmp;
9573           addTest = false;
9574         }
9575       } else { // ISD::AND
9576         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9577         // two branches instead of an explicit AND instruction with a
9578         // separate test. However, we only do this if this block doesn't
9579         // have a fall-through edge, because this requires an explicit
9580         // jmp when the condition is false.
9581         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9582             isX86LogicalCmp(Cmp) &&
9583             Op.getNode()->hasOneUse()) {
9584           X86::CondCode CCode =
9585             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9586           CCode = X86::GetOppositeBranchCondition(CCode);
9587           CC = DAG.getConstant(CCode, MVT::i8);
9588           SDNode *User = *Op.getNode()->use_begin();
9589           // Look for an unconditional branch following this conditional branch.
9590           // We need this because we need to reverse the successors in order
9591           // to implement FCMP_OEQ.
9592           if (User->getOpcode() == ISD::BR) {
9593             SDValue FalseBB = User->getOperand(1);
9594             SDNode *NewBR =
9595               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9596             assert(NewBR == User);
9597             (void)NewBR;
9598             Dest = FalseBB;
9599
9600             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9601                                 Chain, Dest, CC, Cmp);
9602             X86::CondCode CCode =
9603               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9604             CCode = X86::GetOppositeBranchCondition(CCode);
9605             CC = DAG.getConstant(CCode, MVT::i8);
9606             Cond = Cmp;
9607             addTest = false;
9608           }
9609         }
9610       }
9611     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9612       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9613       // It should be transformed during dag combiner except when the condition
9614       // is set by a arithmetics with overflow node.
9615       X86::CondCode CCode =
9616         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9617       CCode = X86::GetOppositeBranchCondition(CCode);
9618       CC = DAG.getConstant(CCode, MVT::i8);
9619       Cond = Cond.getOperand(0).getOperand(1);
9620       addTest = false;
9621     } else if (Cond.getOpcode() == ISD::SETCC &&
9622                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9623       // For FCMP_OEQ, we can emit
9624       // two branches instead of an explicit AND instruction with a
9625       // separate test. However, we only do this if this block doesn't
9626       // have a fall-through edge, because this requires an explicit
9627       // jmp when the condition is false.
9628       if (Op.getNode()->hasOneUse()) {
9629         SDNode *User = *Op.getNode()->use_begin();
9630         // Look for an unconditional branch following this conditional branch.
9631         // We need this because we need to reverse the successors in order
9632         // to implement FCMP_OEQ.
9633         if (User->getOpcode() == ISD::BR) {
9634           SDValue FalseBB = User->getOperand(1);
9635           SDNode *NewBR =
9636             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9637           assert(NewBR == User);
9638           (void)NewBR;
9639           Dest = FalseBB;
9640
9641           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9642                                     Cond.getOperand(0), Cond.getOperand(1));
9643           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9644           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9645           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9646                               Chain, Dest, CC, Cmp);
9647           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9648           Cond = Cmp;
9649           addTest = false;
9650         }
9651       }
9652     } else if (Cond.getOpcode() == ISD::SETCC &&
9653                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9654       // For FCMP_UNE, we can emit
9655       // two branches instead of an explicit AND instruction with a
9656       // separate test. However, we only do this if this block doesn't
9657       // have a fall-through edge, because this requires an explicit
9658       // jmp when the condition is false.
9659       if (Op.getNode()->hasOneUse()) {
9660         SDNode *User = *Op.getNode()->use_begin();
9661         // Look for an unconditional branch following this conditional branch.
9662         // We need this because we need to reverse the successors in order
9663         // to implement FCMP_UNE.
9664         if (User->getOpcode() == ISD::BR) {
9665           SDValue FalseBB = User->getOperand(1);
9666           SDNode *NewBR =
9667             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9668           assert(NewBR == User);
9669           (void)NewBR;
9670
9671           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9672                                     Cond.getOperand(0), Cond.getOperand(1));
9673           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9674           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9675           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9676                               Chain, Dest, CC, Cmp);
9677           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9678           Cond = Cmp;
9679           addTest = false;
9680           Dest = FalseBB;
9681         }
9682       }
9683     }
9684   }
9685
9686   if (addTest) {
9687     // Look pass the truncate if the high bits are known zero.
9688     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9689         Cond = Cond.getOperand(0);
9690
9691     // We know the result of AND is compared against zero. Try to match
9692     // it to BT.
9693     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9694       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9695       if (NewSetCC.getNode()) {
9696         CC = NewSetCC.getOperand(0);
9697         Cond = NewSetCC.getOperand(1);
9698         addTest = false;
9699       }
9700     }
9701   }
9702
9703   if (addTest) {
9704     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9705     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9706   }
9707   Cond = ConvertCmpIfNecessary(Cond, DAG);
9708   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9709                      Chain, Dest, CC, Cond);
9710 }
9711
9712
9713 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9714 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9715 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9716 // that the guard pages used by the OS virtual memory manager are allocated in
9717 // correct sequence.
9718 SDValue
9719 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9720                                            SelectionDAG &DAG) const {
9721   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9722           getTargetMachine().Options.EnableSegmentedStacks) &&
9723          "This should be used only on Windows targets or when segmented stacks "
9724          "are being used");
9725   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9726   DebugLoc dl = Op.getDebugLoc();
9727
9728   // Get the inputs.
9729   SDValue Chain = Op.getOperand(0);
9730   SDValue Size  = Op.getOperand(1);
9731   // FIXME: Ensure alignment here
9732
9733   bool Is64Bit = Subtarget->is64Bit();
9734   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9735
9736   if (getTargetMachine().Options.EnableSegmentedStacks) {
9737     MachineFunction &MF = DAG.getMachineFunction();
9738     MachineRegisterInfo &MRI = MF.getRegInfo();
9739
9740     if (Is64Bit) {
9741       // The 64 bit implementation of segmented stacks needs to clobber both r10
9742       // r11. This makes it impossible to use it along with nested parameters.
9743       const Function *F = MF.getFunction();
9744
9745       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9746            I != E; ++I)
9747         if (I->hasNestAttr())
9748           report_fatal_error("Cannot use segmented stacks with functions that "
9749                              "have nested arguments.");
9750     }
9751
9752     const TargetRegisterClass *AddrRegClass =
9753       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9754     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9755     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9756     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9757                                 DAG.getRegister(Vreg, SPTy));
9758     SDValue Ops1[2] = { Value, Chain };
9759     return DAG.getMergeValues(Ops1, 2, dl);
9760   } else {
9761     SDValue Flag;
9762     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9763
9764     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9765     Flag = Chain.getValue(1);
9766     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9767
9768     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9769     Flag = Chain.getValue(1);
9770
9771     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9772
9773     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9774     return DAG.getMergeValues(Ops1, 2, dl);
9775   }
9776 }
9777
9778 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9779   MachineFunction &MF = DAG.getMachineFunction();
9780   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9781
9782   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9783   DebugLoc DL = Op.getDebugLoc();
9784
9785   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9786     // vastart just stores the address of the VarArgsFrameIndex slot into the
9787     // memory location argument.
9788     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9789                                    getPointerTy());
9790     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9791                         MachinePointerInfo(SV), false, false, 0);
9792   }
9793
9794   // __va_list_tag:
9795   //   gp_offset         (0 - 6 * 8)
9796   //   fp_offset         (48 - 48 + 8 * 16)
9797   //   overflow_arg_area (point to parameters coming in memory).
9798   //   reg_save_area
9799   SmallVector<SDValue, 8> MemOps;
9800   SDValue FIN = Op.getOperand(1);
9801   // Store gp_offset
9802   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9803                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9804                                                MVT::i32),
9805                                FIN, MachinePointerInfo(SV), false, false, 0);
9806   MemOps.push_back(Store);
9807
9808   // Store fp_offset
9809   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9810                     FIN, DAG.getIntPtrConstant(4));
9811   Store = DAG.getStore(Op.getOperand(0), DL,
9812                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9813                                        MVT::i32),
9814                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9815   MemOps.push_back(Store);
9816
9817   // Store ptr to overflow_arg_area
9818   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9819                     FIN, DAG.getIntPtrConstant(4));
9820   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9821                                     getPointerTy());
9822   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9823                        MachinePointerInfo(SV, 8),
9824                        false, false, 0);
9825   MemOps.push_back(Store);
9826
9827   // Store ptr to reg_save_area.
9828   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9829                     FIN, DAG.getIntPtrConstant(8));
9830   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9831                                     getPointerTy());
9832   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9833                        MachinePointerInfo(SV, 16), false, false, 0);
9834   MemOps.push_back(Store);
9835   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9836                      &MemOps[0], MemOps.size());
9837 }
9838
9839 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9840   assert(Subtarget->is64Bit() &&
9841          "LowerVAARG only handles 64-bit va_arg!");
9842   assert((Subtarget->isTargetLinux() ||
9843           Subtarget->isTargetDarwin()) &&
9844           "Unhandled target in LowerVAARG");
9845   assert(Op.getNode()->getNumOperands() == 4);
9846   SDValue Chain = Op.getOperand(0);
9847   SDValue SrcPtr = Op.getOperand(1);
9848   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9849   unsigned Align = Op.getConstantOperandVal(3);
9850   DebugLoc dl = Op.getDebugLoc();
9851
9852   EVT ArgVT = Op.getNode()->getValueType(0);
9853   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9854   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9855   uint8_t ArgMode;
9856
9857   // Decide which area this value should be read from.
9858   // TODO: Implement the AMD64 ABI in its entirety. This simple
9859   // selection mechanism works only for the basic types.
9860   if (ArgVT == MVT::f80) {
9861     llvm_unreachable("va_arg for f80 not yet implemented");
9862   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9863     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9864   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9865     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9866   } else {
9867     llvm_unreachable("Unhandled argument type in LowerVAARG");
9868   }
9869
9870   if (ArgMode == 2) {
9871     // Sanity Check: Make sure using fp_offset makes sense.
9872     assert(!getTargetMachine().Options.UseSoftFloat &&
9873            !(DAG.getMachineFunction()
9874                 .getFunction()->getFnAttributes()
9875                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9876            Subtarget->hasSSE1());
9877   }
9878
9879   // Insert VAARG_64 node into the DAG
9880   // VAARG_64 returns two values: Variable Argument Address, Chain
9881   SmallVector<SDValue, 11> InstOps;
9882   InstOps.push_back(Chain);
9883   InstOps.push_back(SrcPtr);
9884   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9885   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9886   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9887   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9888   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9889                                           VTs, &InstOps[0], InstOps.size(),
9890                                           MVT::i64,
9891                                           MachinePointerInfo(SV),
9892                                           /*Align=*/0,
9893                                           /*Volatile=*/false,
9894                                           /*ReadMem=*/true,
9895                                           /*WriteMem=*/true);
9896   Chain = VAARG.getValue(1);
9897
9898   // Load the next argument and return it
9899   return DAG.getLoad(ArgVT, dl,
9900                      Chain,
9901                      VAARG,
9902                      MachinePointerInfo(),
9903                      false, false, false, 0);
9904 }
9905
9906 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9907                            SelectionDAG &DAG) {
9908   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9909   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9910   SDValue Chain = Op.getOperand(0);
9911   SDValue DstPtr = Op.getOperand(1);
9912   SDValue SrcPtr = Op.getOperand(2);
9913   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9914   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9915   DebugLoc DL = Op.getDebugLoc();
9916
9917   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9918                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9919                        false,
9920                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9921 }
9922
9923 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9924 // may or may not be a constant. Takes immediate version of shift as input.
9925 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9926                                    SDValue SrcOp, SDValue ShAmt,
9927                                    SelectionDAG &DAG) {
9928   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9929
9930   if (isa<ConstantSDNode>(ShAmt)) {
9931     // Constant may be a TargetConstant. Use a regular constant.
9932     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9933     switch (Opc) {
9934       default: llvm_unreachable("Unknown target vector shift node");
9935       case X86ISD::VSHLI:
9936       case X86ISD::VSRLI:
9937       case X86ISD::VSRAI:
9938         return DAG.getNode(Opc, dl, VT, SrcOp,
9939                            DAG.getConstant(ShiftAmt, MVT::i32));
9940     }
9941   }
9942
9943   // Change opcode to non-immediate version
9944   switch (Opc) {
9945     default: llvm_unreachable("Unknown target vector shift node");
9946     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9947     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9948     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9949   }
9950
9951   // Need to build a vector containing shift amount
9952   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9953   SDValue ShOps[4];
9954   ShOps[0] = ShAmt;
9955   ShOps[1] = DAG.getConstant(0, MVT::i32);
9956   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9957   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9958
9959   // The return type has to be a 128-bit type with the same element
9960   // type as the input type.
9961   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9962   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9963
9964   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9965   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9966 }
9967
9968 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9969   DebugLoc dl = Op.getDebugLoc();
9970   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9971   switch (IntNo) {
9972   default: return SDValue();    // Don't custom lower most intrinsics.
9973   // Comparison intrinsics.
9974   case Intrinsic::x86_sse_comieq_ss:
9975   case Intrinsic::x86_sse_comilt_ss:
9976   case Intrinsic::x86_sse_comile_ss:
9977   case Intrinsic::x86_sse_comigt_ss:
9978   case Intrinsic::x86_sse_comige_ss:
9979   case Intrinsic::x86_sse_comineq_ss:
9980   case Intrinsic::x86_sse_ucomieq_ss:
9981   case Intrinsic::x86_sse_ucomilt_ss:
9982   case Intrinsic::x86_sse_ucomile_ss:
9983   case Intrinsic::x86_sse_ucomigt_ss:
9984   case Intrinsic::x86_sse_ucomige_ss:
9985   case Intrinsic::x86_sse_ucomineq_ss:
9986   case Intrinsic::x86_sse2_comieq_sd:
9987   case Intrinsic::x86_sse2_comilt_sd:
9988   case Intrinsic::x86_sse2_comile_sd:
9989   case Intrinsic::x86_sse2_comigt_sd:
9990   case Intrinsic::x86_sse2_comige_sd:
9991   case Intrinsic::x86_sse2_comineq_sd:
9992   case Intrinsic::x86_sse2_ucomieq_sd:
9993   case Intrinsic::x86_sse2_ucomilt_sd:
9994   case Intrinsic::x86_sse2_ucomile_sd:
9995   case Intrinsic::x86_sse2_ucomigt_sd:
9996   case Intrinsic::x86_sse2_ucomige_sd:
9997   case Intrinsic::x86_sse2_ucomineq_sd: {
9998     unsigned Opc;
9999     ISD::CondCode CC;
10000     switch (IntNo) {
10001     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10002     case Intrinsic::x86_sse_comieq_ss:
10003     case Intrinsic::x86_sse2_comieq_sd:
10004       Opc = X86ISD::COMI;
10005       CC = ISD::SETEQ;
10006       break;
10007     case Intrinsic::x86_sse_comilt_ss:
10008     case Intrinsic::x86_sse2_comilt_sd:
10009       Opc = X86ISD::COMI;
10010       CC = ISD::SETLT;
10011       break;
10012     case Intrinsic::x86_sse_comile_ss:
10013     case Intrinsic::x86_sse2_comile_sd:
10014       Opc = X86ISD::COMI;
10015       CC = ISD::SETLE;
10016       break;
10017     case Intrinsic::x86_sse_comigt_ss:
10018     case Intrinsic::x86_sse2_comigt_sd:
10019       Opc = X86ISD::COMI;
10020       CC = ISD::SETGT;
10021       break;
10022     case Intrinsic::x86_sse_comige_ss:
10023     case Intrinsic::x86_sse2_comige_sd:
10024       Opc = X86ISD::COMI;
10025       CC = ISD::SETGE;
10026       break;
10027     case Intrinsic::x86_sse_comineq_ss:
10028     case Intrinsic::x86_sse2_comineq_sd:
10029       Opc = X86ISD::COMI;
10030       CC = ISD::SETNE;
10031       break;
10032     case Intrinsic::x86_sse_ucomieq_ss:
10033     case Intrinsic::x86_sse2_ucomieq_sd:
10034       Opc = X86ISD::UCOMI;
10035       CC = ISD::SETEQ;
10036       break;
10037     case Intrinsic::x86_sse_ucomilt_ss:
10038     case Intrinsic::x86_sse2_ucomilt_sd:
10039       Opc = X86ISD::UCOMI;
10040       CC = ISD::SETLT;
10041       break;
10042     case Intrinsic::x86_sse_ucomile_ss:
10043     case Intrinsic::x86_sse2_ucomile_sd:
10044       Opc = X86ISD::UCOMI;
10045       CC = ISD::SETLE;
10046       break;
10047     case Intrinsic::x86_sse_ucomigt_ss:
10048     case Intrinsic::x86_sse2_ucomigt_sd:
10049       Opc = X86ISD::UCOMI;
10050       CC = ISD::SETGT;
10051       break;
10052     case Intrinsic::x86_sse_ucomige_ss:
10053     case Intrinsic::x86_sse2_ucomige_sd:
10054       Opc = X86ISD::UCOMI;
10055       CC = ISD::SETGE;
10056       break;
10057     case Intrinsic::x86_sse_ucomineq_ss:
10058     case Intrinsic::x86_sse2_ucomineq_sd:
10059       Opc = X86ISD::UCOMI;
10060       CC = ISD::SETNE;
10061       break;
10062     }
10063
10064     SDValue LHS = Op.getOperand(1);
10065     SDValue RHS = Op.getOperand(2);
10066     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10067     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10068     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10069     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10070                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10071     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10072   }
10073
10074   // Arithmetic intrinsics.
10075   case Intrinsic::x86_sse2_pmulu_dq:
10076   case Intrinsic::x86_avx2_pmulu_dq:
10077     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10078                        Op.getOperand(1), Op.getOperand(2));
10079
10080   // SSE3/AVX horizontal add/sub intrinsics
10081   case Intrinsic::x86_sse3_hadd_ps:
10082   case Intrinsic::x86_sse3_hadd_pd:
10083   case Intrinsic::x86_avx_hadd_ps_256:
10084   case Intrinsic::x86_avx_hadd_pd_256:
10085   case Intrinsic::x86_sse3_hsub_ps:
10086   case Intrinsic::x86_sse3_hsub_pd:
10087   case Intrinsic::x86_avx_hsub_ps_256:
10088   case Intrinsic::x86_avx_hsub_pd_256:
10089   case Intrinsic::x86_ssse3_phadd_w_128:
10090   case Intrinsic::x86_ssse3_phadd_d_128:
10091   case Intrinsic::x86_avx2_phadd_w:
10092   case Intrinsic::x86_avx2_phadd_d:
10093   case Intrinsic::x86_ssse3_phsub_w_128:
10094   case Intrinsic::x86_ssse3_phsub_d_128:
10095   case Intrinsic::x86_avx2_phsub_w:
10096   case Intrinsic::x86_avx2_phsub_d: {
10097     unsigned Opcode;
10098     switch (IntNo) {
10099     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10100     case Intrinsic::x86_sse3_hadd_ps:
10101     case Intrinsic::x86_sse3_hadd_pd:
10102     case Intrinsic::x86_avx_hadd_ps_256:
10103     case Intrinsic::x86_avx_hadd_pd_256:
10104       Opcode = X86ISD::FHADD;
10105       break;
10106     case Intrinsic::x86_sse3_hsub_ps:
10107     case Intrinsic::x86_sse3_hsub_pd:
10108     case Intrinsic::x86_avx_hsub_ps_256:
10109     case Intrinsic::x86_avx_hsub_pd_256:
10110       Opcode = X86ISD::FHSUB;
10111       break;
10112     case Intrinsic::x86_ssse3_phadd_w_128:
10113     case Intrinsic::x86_ssse3_phadd_d_128:
10114     case Intrinsic::x86_avx2_phadd_w:
10115     case Intrinsic::x86_avx2_phadd_d:
10116       Opcode = X86ISD::HADD;
10117       break;
10118     case Intrinsic::x86_ssse3_phsub_w_128:
10119     case Intrinsic::x86_ssse3_phsub_d_128:
10120     case Intrinsic::x86_avx2_phsub_w:
10121     case Intrinsic::x86_avx2_phsub_d:
10122       Opcode = X86ISD::HSUB;
10123       break;
10124     }
10125     return DAG.getNode(Opcode, dl, Op.getValueType(),
10126                        Op.getOperand(1), Op.getOperand(2));
10127   }
10128
10129   // AVX2 variable shift intrinsics
10130   case Intrinsic::x86_avx2_psllv_d:
10131   case Intrinsic::x86_avx2_psllv_q:
10132   case Intrinsic::x86_avx2_psllv_d_256:
10133   case Intrinsic::x86_avx2_psllv_q_256:
10134   case Intrinsic::x86_avx2_psrlv_d:
10135   case Intrinsic::x86_avx2_psrlv_q:
10136   case Intrinsic::x86_avx2_psrlv_d_256:
10137   case Intrinsic::x86_avx2_psrlv_q_256:
10138   case Intrinsic::x86_avx2_psrav_d:
10139   case Intrinsic::x86_avx2_psrav_d_256: {
10140     unsigned Opcode;
10141     switch (IntNo) {
10142     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10143     case Intrinsic::x86_avx2_psllv_d:
10144     case Intrinsic::x86_avx2_psllv_q:
10145     case Intrinsic::x86_avx2_psllv_d_256:
10146     case Intrinsic::x86_avx2_psllv_q_256:
10147       Opcode = ISD::SHL;
10148       break;
10149     case Intrinsic::x86_avx2_psrlv_d:
10150     case Intrinsic::x86_avx2_psrlv_q:
10151     case Intrinsic::x86_avx2_psrlv_d_256:
10152     case Intrinsic::x86_avx2_psrlv_q_256:
10153       Opcode = ISD::SRL;
10154       break;
10155     case Intrinsic::x86_avx2_psrav_d:
10156     case Intrinsic::x86_avx2_psrav_d_256:
10157       Opcode = ISD::SRA;
10158       break;
10159     }
10160     return DAG.getNode(Opcode, dl, Op.getValueType(),
10161                        Op.getOperand(1), Op.getOperand(2));
10162   }
10163
10164   case Intrinsic::x86_ssse3_pshuf_b_128:
10165   case Intrinsic::x86_avx2_pshuf_b:
10166     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10167                        Op.getOperand(1), Op.getOperand(2));
10168
10169   case Intrinsic::x86_ssse3_psign_b_128:
10170   case Intrinsic::x86_ssse3_psign_w_128:
10171   case Intrinsic::x86_ssse3_psign_d_128:
10172   case Intrinsic::x86_avx2_psign_b:
10173   case Intrinsic::x86_avx2_psign_w:
10174   case Intrinsic::x86_avx2_psign_d:
10175     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10176                        Op.getOperand(1), Op.getOperand(2));
10177
10178   case Intrinsic::x86_sse41_insertps:
10179     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10180                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10181
10182   case Intrinsic::x86_avx_vperm2f128_ps_256:
10183   case Intrinsic::x86_avx_vperm2f128_pd_256:
10184   case Intrinsic::x86_avx_vperm2f128_si_256:
10185   case Intrinsic::x86_avx2_vperm2i128:
10186     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10187                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10188
10189   case Intrinsic::x86_avx2_permd:
10190   case Intrinsic::x86_avx2_permps:
10191     // Operands intentionally swapped. Mask is last operand to intrinsic,
10192     // but second operand for node/intruction.
10193     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10194                        Op.getOperand(2), Op.getOperand(1));
10195
10196   // ptest and testp intrinsics. The intrinsic these come from are designed to
10197   // return an integer value, not just an instruction so lower it to the ptest
10198   // or testp pattern and a setcc for the result.
10199   case Intrinsic::x86_sse41_ptestz:
10200   case Intrinsic::x86_sse41_ptestc:
10201   case Intrinsic::x86_sse41_ptestnzc:
10202   case Intrinsic::x86_avx_ptestz_256:
10203   case Intrinsic::x86_avx_ptestc_256:
10204   case Intrinsic::x86_avx_ptestnzc_256:
10205   case Intrinsic::x86_avx_vtestz_ps:
10206   case Intrinsic::x86_avx_vtestc_ps:
10207   case Intrinsic::x86_avx_vtestnzc_ps:
10208   case Intrinsic::x86_avx_vtestz_pd:
10209   case Intrinsic::x86_avx_vtestc_pd:
10210   case Intrinsic::x86_avx_vtestnzc_pd:
10211   case Intrinsic::x86_avx_vtestz_ps_256:
10212   case Intrinsic::x86_avx_vtestc_ps_256:
10213   case Intrinsic::x86_avx_vtestnzc_ps_256:
10214   case Intrinsic::x86_avx_vtestz_pd_256:
10215   case Intrinsic::x86_avx_vtestc_pd_256:
10216   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10217     bool IsTestPacked = false;
10218     unsigned X86CC;
10219     switch (IntNo) {
10220     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10221     case Intrinsic::x86_avx_vtestz_ps:
10222     case Intrinsic::x86_avx_vtestz_pd:
10223     case Intrinsic::x86_avx_vtestz_ps_256:
10224     case Intrinsic::x86_avx_vtestz_pd_256:
10225       IsTestPacked = true; // Fallthrough
10226     case Intrinsic::x86_sse41_ptestz:
10227     case Intrinsic::x86_avx_ptestz_256:
10228       // ZF = 1
10229       X86CC = X86::COND_E;
10230       break;
10231     case Intrinsic::x86_avx_vtestc_ps:
10232     case Intrinsic::x86_avx_vtestc_pd:
10233     case Intrinsic::x86_avx_vtestc_ps_256:
10234     case Intrinsic::x86_avx_vtestc_pd_256:
10235       IsTestPacked = true; // Fallthrough
10236     case Intrinsic::x86_sse41_ptestc:
10237     case Intrinsic::x86_avx_ptestc_256:
10238       // CF = 1
10239       X86CC = X86::COND_B;
10240       break;
10241     case Intrinsic::x86_avx_vtestnzc_ps:
10242     case Intrinsic::x86_avx_vtestnzc_pd:
10243     case Intrinsic::x86_avx_vtestnzc_ps_256:
10244     case Intrinsic::x86_avx_vtestnzc_pd_256:
10245       IsTestPacked = true; // Fallthrough
10246     case Intrinsic::x86_sse41_ptestnzc:
10247     case Intrinsic::x86_avx_ptestnzc_256:
10248       // ZF and CF = 0
10249       X86CC = X86::COND_A;
10250       break;
10251     }
10252
10253     SDValue LHS = Op.getOperand(1);
10254     SDValue RHS = Op.getOperand(2);
10255     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10256     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10257     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10258     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10259     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10260   }
10261
10262   // SSE/AVX shift intrinsics
10263   case Intrinsic::x86_sse2_psll_w:
10264   case Intrinsic::x86_sse2_psll_d:
10265   case Intrinsic::x86_sse2_psll_q:
10266   case Intrinsic::x86_avx2_psll_w:
10267   case Intrinsic::x86_avx2_psll_d:
10268   case Intrinsic::x86_avx2_psll_q:
10269   case Intrinsic::x86_sse2_psrl_w:
10270   case Intrinsic::x86_sse2_psrl_d:
10271   case Intrinsic::x86_sse2_psrl_q:
10272   case Intrinsic::x86_avx2_psrl_w:
10273   case Intrinsic::x86_avx2_psrl_d:
10274   case Intrinsic::x86_avx2_psrl_q:
10275   case Intrinsic::x86_sse2_psra_w:
10276   case Intrinsic::x86_sse2_psra_d:
10277   case Intrinsic::x86_avx2_psra_w:
10278   case Intrinsic::x86_avx2_psra_d: {
10279     unsigned Opcode;
10280     switch (IntNo) {
10281     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10282     case Intrinsic::x86_sse2_psll_w:
10283     case Intrinsic::x86_sse2_psll_d:
10284     case Intrinsic::x86_sse2_psll_q:
10285     case Intrinsic::x86_avx2_psll_w:
10286     case Intrinsic::x86_avx2_psll_d:
10287     case Intrinsic::x86_avx2_psll_q:
10288       Opcode = X86ISD::VSHL;
10289       break;
10290     case Intrinsic::x86_sse2_psrl_w:
10291     case Intrinsic::x86_sse2_psrl_d:
10292     case Intrinsic::x86_sse2_psrl_q:
10293     case Intrinsic::x86_avx2_psrl_w:
10294     case Intrinsic::x86_avx2_psrl_d:
10295     case Intrinsic::x86_avx2_psrl_q:
10296       Opcode = X86ISD::VSRL;
10297       break;
10298     case Intrinsic::x86_sse2_psra_w:
10299     case Intrinsic::x86_sse2_psra_d:
10300     case Intrinsic::x86_avx2_psra_w:
10301     case Intrinsic::x86_avx2_psra_d:
10302       Opcode = X86ISD::VSRA;
10303       break;
10304     }
10305     return DAG.getNode(Opcode, dl, Op.getValueType(),
10306                        Op.getOperand(1), Op.getOperand(2));
10307   }
10308
10309   // SSE/AVX immediate shift intrinsics
10310   case Intrinsic::x86_sse2_pslli_w:
10311   case Intrinsic::x86_sse2_pslli_d:
10312   case Intrinsic::x86_sse2_pslli_q:
10313   case Intrinsic::x86_avx2_pslli_w:
10314   case Intrinsic::x86_avx2_pslli_d:
10315   case Intrinsic::x86_avx2_pslli_q:
10316   case Intrinsic::x86_sse2_psrli_w:
10317   case Intrinsic::x86_sse2_psrli_d:
10318   case Intrinsic::x86_sse2_psrli_q:
10319   case Intrinsic::x86_avx2_psrli_w:
10320   case Intrinsic::x86_avx2_psrli_d:
10321   case Intrinsic::x86_avx2_psrli_q:
10322   case Intrinsic::x86_sse2_psrai_w:
10323   case Intrinsic::x86_sse2_psrai_d:
10324   case Intrinsic::x86_avx2_psrai_w:
10325   case Intrinsic::x86_avx2_psrai_d: {
10326     unsigned Opcode;
10327     switch (IntNo) {
10328     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10329     case Intrinsic::x86_sse2_pslli_w:
10330     case Intrinsic::x86_sse2_pslli_d:
10331     case Intrinsic::x86_sse2_pslli_q:
10332     case Intrinsic::x86_avx2_pslli_w:
10333     case Intrinsic::x86_avx2_pslli_d:
10334     case Intrinsic::x86_avx2_pslli_q:
10335       Opcode = X86ISD::VSHLI;
10336       break;
10337     case Intrinsic::x86_sse2_psrli_w:
10338     case Intrinsic::x86_sse2_psrli_d:
10339     case Intrinsic::x86_sse2_psrli_q:
10340     case Intrinsic::x86_avx2_psrli_w:
10341     case Intrinsic::x86_avx2_psrli_d:
10342     case Intrinsic::x86_avx2_psrli_q:
10343       Opcode = X86ISD::VSRLI;
10344       break;
10345     case Intrinsic::x86_sse2_psrai_w:
10346     case Intrinsic::x86_sse2_psrai_d:
10347     case Intrinsic::x86_avx2_psrai_w:
10348     case Intrinsic::x86_avx2_psrai_d:
10349       Opcode = X86ISD::VSRAI;
10350       break;
10351     }
10352     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10353                                Op.getOperand(1), Op.getOperand(2), DAG);
10354   }
10355
10356   case Intrinsic::x86_sse42_pcmpistria128:
10357   case Intrinsic::x86_sse42_pcmpestria128:
10358   case Intrinsic::x86_sse42_pcmpistric128:
10359   case Intrinsic::x86_sse42_pcmpestric128:
10360   case Intrinsic::x86_sse42_pcmpistrio128:
10361   case Intrinsic::x86_sse42_pcmpestrio128:
10362   case Intrinsic::x86_sse42_pcmpistris128:
10363   case Intrinsic::x86_sse42_pcmpestris128:
10364   case Intrinsic::x86_sse42_pcmpistriz128:
10365   case Intrinsic::x86_sse42_pcmpestriz128: {
10366     unsigned Opcode;
10367     unsigned X86CC;
10368     switch (IntNo) {
10369     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10370     case Intrinsic::x86_sse42_pcmpistria128:
10371       Opcode = X86ISD::PCMPISTRI;
10372       X86CC = X86::COND_A;
10373       break;
10374     case Intrinsic::x86_sse42_pcmpestria128:
10375       Opcode = X86ISD::PCMPESTRI;
10376       X86CC = X86::COND_A;
10377       break;
10378     case Intrinsic::x86_sse42_pcmpistric128:
10379       Opcode = X86ISD::PCMPISTRI;
10380       X86CC = X86::COND_B;
10381       break;
10382     case Intrinsic::x86_sse42_pcmpestric128:
10383       Opcode = X86ISD::PCMPESTRI;
10384       X86CC = X86::COND_B;
10385       break;
10386     case Intrinsic::x86_sse42_pcmpistrio128:
10387       Opcode = X86ISD::PCMPISTRI;
10388       X86CC = X86::COND_O;
10389       break;
10390     case Intrinsic::x86_sse42_pcmpestrio128:
10391       Opcode = X86ISD::PCMPESTRI;
10392       X86CC = X86::COND_O;
10393       break;
10394     case Intrinsic::x86_sse42_pcmpistris128:
10395       Opcode = X86ISD::PCMPISTRI;
10396       X86CC = X86::COND_S;
10397       break;
10398     case Intrinsic::x86_sse42_pcmpestris128:
10399       Opcode = X86ISD::PCMPESTRI;
10400       X86CC = X86::COND_S;
10401       break;
10402     case Intrinsic::x86_sse42_pcmpistriz128:
10403       Opcode = X86ISD::PCMPISTRI;
10404       X86CC = X86::COND_E;
10405       break;
10406     case Intrinsic::x86_sse42_pcmpestriz128:
10407       Opcode = X86ISD::PCMPESTRI;
10408       X86CC = X86::COND_E;
10409       break;
10410     }
10411     SmallVector<SDValue, 5> NewOps;
10412     NewOps.append(Op->op_begin()+1, Op->op_end());
10413     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10414     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10415     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10416                                 DAG.getConstant(X86CC, MVT::i8),
10417                                 SDValue(PCMP.getNode(), 1));
10418     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10419   }
10420
10421   case Intrinsic::x86_sse42_pcmpistri128:
10422   case Intrinsic::x86_sse42_pcmpestri128: {
10423     unsigned Opcode;
10424     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10425       Opcode = X86ISD::PCMPISTRI;
10426     else
10427       Opcode = X86ISD::PCMPESTRI;
10428
10429     SmallVector<SDValue, 5> NewOps;
10430     NewOps.append(Op->op_begin()+1, Op->op_end());
10431     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10432     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10433   }
10434   case Intrinsic::x86_fma_vfmadd_ps:
10435   case Intrinsic::x86_fma_vfmadd_pd:
10436   case Intrinsic::x86_fma_vfmsub_ps:
10437   case Intrinsic::x86_fma_vfmsub_pd:
10438   case Intrinsic::x86_fma_vfnmadd_ps:
10439   case Intrinsic::x86_fma_vfnmadd_pd:
10440   case Intrinsic::x86_fma_vfnmsub_ps:
10441   case Intrinsic::x86_fma_vfnmsub_pd:
10442   case Intrinsic::x86_fma_vfmaddsub_ps:
10443   case Intrinsic::x86_fma_vfmaddsub_pd:
10444   case Intrinsic::x86_fma_vfmsubadd_ps:
10445   case Intrinsic::x86_fma_vfmsubadd_pd:
10446   case Intrinsic::x86_fma_vfmadd_ps_256:
10447   case Intrinsic::x86_fma_vfmadd_pd_256:
10448   case Intrinsic::x86_fma_vfmsub_ps_256:
10449   case Intrinsic::x86_fma_vfmsub_pd_256:
10450   case Intrinsic::x86_fma_vfnmadd_ps_256:
10451   case Intrinsic::x86_fma_vfnmadd_pd_256:
10452   case Intrinsic::x86_fma_vfnmsub_ps_256:
10453   case Intrinsic::x86_fma_vfnmsub_pd_256:
10454   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10455   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10456   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10457   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10458     unsigned Opc;
10459     switch (IntNo) {
10460     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10461     case Intrinsic::x86_fma_vfmadd_ps:
10462     case Intrinsic::x86_fma_vfmadd_pd:
10463     case Intrinsic::x86_fma_vfmadd_ps_256:
10464     case Intrinsic::x86_fma_vfmadd_pd_256:
10465       Opc = X86ISD::FMADD;
10466       break;
10467     case Intrinsic::x86_fma_vfmsub_ps:
10468     case Intrinsic::x86_fma_vfmsub_pd:
10469     case Intrinsic::x86_fma_vfmsub_ps_256:
10470     case Intrinsic::x86_fma_vfmsub_pd_256:
10471       Opc = X86ISD::FMSUB;
10472       break;
10473     case Intrinsic::x86_fma_vfnmadd_ps:
10474     case Intrinsic::x86_fma_vfnmadd_pd:
10475     case Intrinsic::x86_fma_vfnmadd_ps_256:
10476     case Intrinsic::x86_fma_vfnmadd_pd_256:
10477       Opc = X86ISD::FNMADD;
10478       break;
10479     case Intrinsic::x86_fma_vfnmsub_ps:
10480     case Intrinsic::x86_fma_vfnmsub_pd:
10481     case Intrinsic::x86_fma_vfnmsub_ps_256:
10482     case Intrinsic::x86_fma_vfnmsub_pd_256:
10483       Opc = X86ISD::FNMSUB;
10484       break;
10485     case Intrinsic::x86_fma_vfmaddsub_ps:
10486     case Intrinsic::x86_fma_vfmaddsub_pd:
10487     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10488     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10489       Opc = X86ISD::FMADDSUB;
10490       break;
10491     case Intrinsic::x86_fma_vfmsubadd_ps:
10492     case Intrinsic::x86_fma_vfmsubadd_pd:
10493     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10494     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10495       Opc = X86ISD::FMSUBADD;
10496       break;
10497     }
10498
10499     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10500                        Op.getOperand(2), Op.getOperand(3));
10501   }
10502   }
10503 }
10504
10505 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10506   DebugLoc dl = Op.getDebugLoc();
10507   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10508   switch (IntNo) {
10509   default: return SDValue();    // Don't custom lower most intrinsics.
10510
10511   // RDRAND intrinsics.
10512   case Intrinsic::x86_rdrand_16:
10513   case Intrinsic::x86_rdrand_32:
10514   case Intrinsic::x86_rdrand_64: {
10515     // Emit the node with the right value type.
10516     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10517     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10518
10519     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10520     // return the value from Rand, which is always 0, casted to i32.
10521     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10522                       DAG.getConstant(1, Op->getValueType(1)),
10523                       DAG.getConstant(X86::COND_B, MVT::i32),
10524                       SDValue(Result.getNode(), 1) };
10525     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10526                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10527                                   Ops, 4);
10528
10529     // Return { result, isValid, chain }.
10530     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10531                        SDValue(Result.getNode(), 2));
10532   }
10533   }
10534 }
10535
10536 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10537                                            SelectionDAG &DAG) const {
10538   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10539   MFI->setReturnAddressIsTaken(true);
10540
10541   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10542   DebugLoc dl = Op.getDebugLoc();
10543
10544   if (Depth > 0) {
10545     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10546     SDValue Offset =
10547       DAG.getConstant(TD->getPointerSize(0),
10548                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10549     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10550                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10551                                    FrameAddr, Offset),
10552                        MachinePointerInfo(), false, false, false, 0);
10553   }
10554
10555   // Just load the return address.
10556   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10557   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10558                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10559 }
10560
10561 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10562   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10563   MFI->setFrameAddressIsTaken(true);
10564
10565   EVT VT = Op.getValueType();
10566   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10567   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10568   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10569   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10570   while (Depth--)
10571     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10572                             MachinePointerInfo(),
10573                             false, false, false, 0);
10574   return FrameAddr;
10575 }
10576
10577 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10578                                                      SelectionDAG &DAG) const {
10579   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10580 }
10581
10582 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10583   SDValue Chain     = Op.getOperand(0);
10584   SDValue Offset    = Op.getOperand(1);
10585   SDValue Handler   = Op.getOperand(2);
10586   DebugLoc dl       = Op.getDebugLoc();
10587
10588   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10589                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10590                                      getPointerTy());
10591   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10592
10593   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10594                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10595   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10596   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10597                        false, false, 0);
10598   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10599
10600   return DAG.getNode(X86ISD::EH_RETURN, dl,
10601                      MVT::Other,
10602                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10603 }
10604
10605 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10606                                                SelectionDAG &DAG) const {
10607   DebugLoc DL = Op.getDebugLoc();
10608   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10609                      DAG.getVTList(MVT::i32, MVT::Other),
10610                      Op.getOperand(0), Op.getOperand(1));
10611 }
10612
10613 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10614                                                 SelectionDAG &DAG) const {
10615   DebugLoc DL = Op.getDebugLoc();
10616   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10617                      Op.getOperand(0), Op.getOperand(1));
10618 }
10619
10620 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10621   return Op.getOperand(0);
10622 }
10623
10624 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10625                                                 SelectionDAG &DAG) const {
10626   SDValue Root = Op.getOperand(0);
10627   SDValue Trmp = Op.getOperand(1); // trampoline
10628   SDValue FPtr = Op.getOperand(2); // nested function
10629   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10630   DebugLoc dl  = Op.getDebugLoc();
10631
10632   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10633   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10634
10635   if (Subtarget->is64Bit()) {
10636     SDValue OutChains[6];
10637
10638     // Large code-model.
10639     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10640     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10641
10642     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10643     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10644
10645     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10646
10647     // Load the pointer to the nested function into R11.
10648     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10649     SDValue Addr = Trmp;
10650     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10651                                 Addr, MachinePointerInfo(TrmpAddr),
10652                                 false, false, 0);
10653
10654     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10655                        DAG.getConstant(2, MVT::i64));
10656     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10657                                 MachinePointerInfo(TrmpAddr, 2),
10658                                 false, false, 2);
10659
10660     // Load the 'nest' parameter value into R10.
10661     // R10 is specified in X86CallingConv.td
10662     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10663     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10664                        DAG.getConstant(10, MVT::i64));
10665     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10666                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10667                                 false, false, 0);
10668
10669     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10670                        DAG.getConstant(12, MVT::i64));
10671     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10672                                 MachinePointerInfo(TrmpAddr, 12),
10673                                 false, false, 2);
10674
10675     // Jump to the nested function.
10676     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10677     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10678                        DAG.getConstant(20, MVT::i64));
10679     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10680                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10681                                 false, false, 0);
10682
10683     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10684     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10685                        DAG.getConstant(22, MVT::i64));
10686     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10687                                 MachinePointerInfo(TrmpAddr, 22),
10688                                 false, false, 0);
10689
10690     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10691   } else {
10692     const Function *Func =
10693       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10694     CallingConv::ID CC = Func->getCallingConv();
10695     unsigned NestReg;
10696
10697     switch (CC) {
10698     default:
10699       llvm_unreachable("Unsupported calling convention");
10700     case CallingConv::C:
10701     case CallingConv::X86_StdCall: {
10702       // Pass 'nest' parameter in ECX.
10703       // Must be kept in sync with X86CallingConv.td
10704       NestReg = X86::ECX;
10705
10706       // Check that ECX wasn't needed by an 'inreg' parameter.
10707       FunctionType *FTy = Func->getFunctionType();
10708       const AttrListPtr &Attrs = Func->getAttributes();
10709
10710       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10711         unsigned InRegCount = 0;
10712         unsigned Idx = 1;
10713
10714         for (FunctionType::param_iterator I = FTy->param_begin(),
10715              E = FTy->param_end(); I != E; ++I, ++Idx)
10716           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10717             // FIXME: should only count parameters that are lowered to integers.
10718             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10719
10720         if (InRegCount > 2) {
10721           report_fatal_error("Nest register in use - reduce number of inreg"
10722                              " parameters!");
10723         }
10724       }
10725       break;
10726     }
10727     case CallingConv::X86_FastCall:
10728     case CallingConv::X86_ThisCall:
10729     case CallingConv::Fast:
10730       // Pass 'nest' parameter in EAX.
10731       // Must be kept in sync with X86CallingConv.td
10732       NestReg = X86::EAX;
10733       break;
10734     }
10735
10736     SDValue OutChains[4];
10737     SDValue Addr, Disp;
10738
10739     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10740                        DAG.getConstant(10, MVT::i32));
10741     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10742
10743     // This is storing the opcode for MOV32ri.
10744     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10745     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10746     OutChains[0] = DAG.getStore(Root, dl,
10747                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10748                                 Trmp, MachinePointerInfo(TrmpAddr),
10749                                 false, false, 0);
10750
10751     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10752                        DAG.getConstant(1, MVT::i32));
10753     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10754                                 MachinePointerInfo(TrmpAddr, 1),
10755                                 false, false, 1);
10756
10757     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10759                        DAG.getConstant(5, MVT::i32));
10760     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10761                                 MachinePointerInfo(TrmpAddr, 5),
10762                                 false, false, 1);
10763
10764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10765                        DAG.getConstant(6, MVT::i32));
10766     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10767                                 MachinePointerInfo(TrmpAddr, 6),
10768                                 false, false, 1);
10769
10770     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10771   }
10772 }
10773
10774 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10775                                             SelectionDAG &DAG) const {
10776   /*
10777    The rounding mode is in bits 11:10 of FPSR, and has the following
10778    settings:
10779      00 Round to nearest
10780      01 Round to -inf
10781      10 Round to +inf
10782      11 Round to 0
10783
10784   FLT_ROUNDS, on the other hand, expects the following:
10785     -1 Undefined
10786      0 Round to 0
10787      1 Round to nearest
10788      2 Round to +inf
10789      3 Round to -inf
10790
10791   To perform the conversion, we do:
10792     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10793   */
10794
10795   MachineFunction &MF = DAG.getMachineFunction();
10796   const TargetMachine &TM = MF.getTarget();
10797   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10798   unsigned StackAlignment = TFI.getStackAlignment();
10799   EVT VT = Op.getValueType();
10800   DebugLoc DL = Op.getDebugLoc();
10801
10802   // Save FP Control Word to stack slot
10803   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10804   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10805
10806
10807   MachineMemOperand *MMO =
10808    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10809                            MachineMemOperand::MOStore, 2, 2);
10810
10811   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10812   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10813                                           DAG.getVTList(MVT::Other),
10814                                           Ops, 2, MVT::i16, MMO);
10815
10816   // Load FP Control Word from stack slot
10817   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10818                             MachinePointerInfo(), false, false, false, 0);
10819
10820   // Transform as necessary
10821   SDValue CWD1 =
10822     DAG.getNode(ISD::SRL, DL, MVT::i16,
10823                 DAG.getNode(ISD::AND, DL, MVT::i16,
10824                             CWD, DAG.getConstant(0x800, MVT::i16)),
10825                 DAG.getConstant(11, MVT::i8));
10826   SDValue CWD2 =
10827     DAG.getNode(ISD::SRL, DL, MVT::i16,
10828                 DAG.getNode(ISD::AND, DL, MVT::i16,
10829                             CWD, DAG.getConstant(0x400, MVT::i16)),
10830                 DAG.getConstant(9, MVT::i8));
10831
10832   SDValue RetVal =
10833     DAG.getNode(ISD::AND, DL, MVT::i16,
10834                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10835                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10836                             DAG.getConstant(1, MVT::i16)),
10837                 DAG.getConstant(3, MVT::i16));
10838
10839
10840   return DAG.getNode((VT.getSizeInBits() < 16 ?
10841                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10842 }
10843
10844 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10845   EVT VT = Op.getValueType();
10846   EVT OpVT = VT;
10847   unsigned NumBits = VT.getSizeInBits();
10848   DebugLoc dl = Op.getDebugLoc();
10849
10850   Op = Op.getOperand(0);
10851   if (VT == MVT::i8) {
10852     // Zero extend to i32 since there is not an i8 bsr.
10853     OpVT = MVT::i32;
10854     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10855   }
10856
10857   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10858   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10859   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10860
10861   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10862   SDValue Ops[] = {
10863     Op,
10864     DAG.getConstant(NumBits+NumBits-1, OpVT),
10865     DAG.getConstant(X86::COND_E, MVT::i8),
10866     Op.getValue(1)
10867   };
10868   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10869
10870   // Finally xor with NumBits-1.
10871   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10872
10873   if (VT == MVT::i8)
10874     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10875   return Op;
10876 }
10877
10878 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10879   EVT VT = Op.getValueType();
10880   EVT OpVT = VT;
10881   unsigned NumBits = VT.getSizeInBits();
10882   DebugLoc dl = Op.getDebugLoc();
10883
10884   Op = Op.getOperand(0);
10885   if (VT == MVT::i8) {
10886     // Zero extend to i32 since there is not an i8 bsr.
10887     OpVT = MVT::i32;
10888     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10889   }
10890
10891   // Issue a bsr (scan bits in reverse).
10892   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10893   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10894
10895   // And xor with NumBits-1.
10896   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10897
10898   if (VT == MVT::i8)
10899     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10900   return Op;
10901 }
10902
10903 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10904   EVT VT = Op.getValueType();
10905   unsigned NumBits = VT.getSizeInBits();
10906   DebugLoc dl = Op.getDebugLoc();
10907   Op = Op.getOperand(0);
10908
10909   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10910   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10911   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10912
10913   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10914   SDValue Ops[] = {
10915     Op,
10916     DAG.getConstant(NumBits, VT),
10917     DAG.getConstant(X86::COND_E, MVT::i8),
10918     Op.getValue(1)
10919   };
10920   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10921 }
10922
10923 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10924 // ones, and then concatenate the result back.
10925 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10926   EVT VT = Op.getValueType();
10927
10928   assert(VT.is256BitVector() && VT.isInteger() &&
10929          "Unsupported value type for operation");
10930
10931   unsigned NumElems = VT.getVectorNumElements();
10932   DebugLoc dl = Op.getDebugLoc();
10933
10934   // Extract the LHS vectors
10935   SDValue LHS = Op.getOperand(0);
10936   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10937   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10938
10939   // Extract the RHS vectors
10940   SDValue RHS = Op.getOperand(1);
10941   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10942   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10943
10944   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10945   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10946
10947   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10948                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10949                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10950 }
10951
10952 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10953   assert(Op.getValueType().is256BitVector() &&
10954          Op.getValueType().isInteger() &&
10955          "Only handle AVX 256-bit vector integer operation");
10956   return Lower256IntArith(Op, DAG);
10957 }
10958
10959 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10960   assert(Op.getValueType().is256BitVector() &&
10961          Op.getValueType().isInteger() &&
10962          "Only handle AVX 256-bit vector integer operation");
10963   return Lower256IntArith(Op, DAG);
10964 }
10965
10966 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10967                         SelectionDAG &DAG) {
10968   EVT VT = Op.getValueType();
10969
10970   // Decompose 256-bit ops into smaller 128-bit ops.
10971   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10972     return Lower256IntArith(Op, DAG);
10973
10974   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10975          "Only know how to lower V2I64/V4I64 multiply");
10976
10977   DebugLoc dl = Op.getDebugLoc();
10978
10979   //  Ahi = psrlqi(a, 32);
10980   //  Bhi = psrlqi(b, 32);
10981   //
10982   //  AloBlo = pmuludq(a, b);
10983   //  AloBhi = pmuludq(a, Bhi);
10984   //  AhiBlo = pmuludq(Ahi, b);
10985
10986   //  AloBhi = psllqi(AloBhi, 32);
10987   //  AhiBlo = psllqi(AhiBlo, 32);
10988   //  return AloBlo + AloBhi + AhiBlo;
10989
10990   SDValue A = Op.getOperand(0);
10991   SDValue B = Op.getOperand(1);
10992
10993   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10994
10995   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10996   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10997
10998   // Bit cast to 32-bit vectors for MULUDQ
10999   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11000   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11001   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11002   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11003   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11004
11005   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11006   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11007   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11008
11009   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11010   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11011
11012   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11013   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11014 }
11015
11016 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11017
11018   EVT VT = Op.getValueType();
11019   DebugLoc dl = Op.getDebugLoc();
11020   SDValue R = Op.getOperand(0);
11021   SDValue Amt = Op.getOperand(1);
11022   LLVMContext *Context = DAG.getContext();
11023
11024   if (!Subtarget->hasSSE2())
11025     return SDValue();
11026
11027   // Optimize shl/srl/sra with constant shift amount.
11028   if (isSplatVector(Amt.getNode())) {
11029     SDValue SclrAmt = Amt->getOperand(0);
11030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11031       uint64_t ShiftAmt = C->getZExtValue();
11032
11033       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11034           (Subtarget->hasAVX2() &&
11035            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11036         if (Op.getOpcode() == ISD::SHL)
11037           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11038                              DAG.getConstant(ShiftAmt, MVT::i32));
11039         if (Op.getOpcode() == ISD::SRL)
11040           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11041                              DAG.getConstant(ShiftAmt, MVT::i32));
11042         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11043           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11044                              DAG.getConstant(ShiftAmt, MVT::i32));
11045       }
11046
11047       if (VT == MVT::v16i8) {
11048         if (Op.getOpcode() == ISD::SHL) {
11049           // Make a large shift.
11050           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11051                                     DAG.getConstant(ShiftAmt, MVT::i32));
11052           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11053           // Zero out the rightmost bits.
11054           SmallVector<SDValue, 16> V(16,
11055                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11056                                                      MVT::i8));
11057           return DAG.getNode(ISD::AND, dl, VT, SHL,
11058                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11059         }
11060         if (Op.getOpcode() == ISD::SRL) {
11061           // Make a large shift.
11062           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11063                                     DAG.getConstant(ShiftAmt, MVT::i32));
11064           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11065           // Zero out the leftmost bits.
11066           SmallVector<SDValue, 16> V(16,
11067                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11068                                                      MVT::i8));
11069           return DAG.getNode(ISD::AND, dl, VT, SRL,
11070                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11071         }
11072         if (Op.getOpcode() == ISD::SRA) {
11073           if (ShiftAmt == 7) {
11074             // R s>> 7  ===  R s< 0
11075             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11076             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11077           }
11078
11079           // R s>> a === ((R u>> a) ^ m) - m
11080           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11081           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11082                                                          MVT::i8));
11083           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11084           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11085           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11086           return Res;
11087         }
11088         llvm_unreachable("Unknown shift opcode.");
11089       }
11090
11091       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11092         if (Op.getOpcode() == ISD::SHL) {
11093           // Make a large shift.
11094           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11095                                     DAG.getConstant(ShiftAmt, MVT::i32));
11096           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11097           // Zero out the rightmost bits.
11098           SmallVector<SDValue, 32> V(32,
11099                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11100                                                      MVT::i8));
11101           return DAG.getNode(ISD::AND, dl, VT, SHL,
11102                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11103         }
11104         if (Op.getOpcode() == ISD::SRL) {
11105           // Make a large shift.
11106           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11107                                     DAG.getConstant(ShiftAmt, MVT::i32));
11108           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11109           // Zero out the leftmost bits.
11110           SmallVector<SDValue, 32> V(32,
11111                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11112                                                      MVT::i8));
11113           return DAG.getNode(ISD::AND, dl, VT, SRL,
11114                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11115         }
11116         if (Op.getOpcode() == ISD::SRA) {
11117           if (ShiftAmt == 7) {
11118             // R s>> 7  ===  R s< 0
11119             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11120             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11121           }
11122
11123           // R s>> a === ((R u>> a) ^ m) - m
11124           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11125           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11126                                                          MVT::i8));
11127           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11128           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11129           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11130           return Res;
11131         }
11132         llvm_unreachable("Unknown shift opcode.");
11133       }
11134     }
11135   }
11136
11137   // Lower SHL with variable shift amount.
11138   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11139     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11140                      DAG.getConstant(23, MVT::i32));
11141
11142     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11143     Constant *C = ConstantDataVector::get(*Context, CV);
11144     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11145     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11146                                  MachinePointerInfo::getConstantPool(),
11147                                  false, false, false, 16);
11148
11149     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11150     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11151     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11152     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11153   }
11154   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11155     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11156
11157     // a = a << 5;
11158     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11159                      DAG.getConstant(5, MVT::i32));
11160     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11161
11162     // Turn 'a' into a mask suitable for VSELECT
11163     SDValue VSelM = DAG.getConstant(0x80, VT);
11164     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11165     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11166
11167     SDValue CM1 = DAG.getConstant(0x0f, VT);
11168     SDValue CM2 = DAG.getConstant(0x3f, VT);
11169
11170     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11171     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11172     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11173                             DAG.getConstant(4, MVT::i32), DAG);
11174     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11175     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11176
11177     // a += a
11178     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11179     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11180     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11181
11182     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11183     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11184     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11185                             DAG.getConstant(2, MVT::i32), DAG);
11186     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11187     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11188
11189     // a += a
11190     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11191     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11192     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11193
11194     // return VSELECT(r, r+r, a);
11195     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11196                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11197     return R;
11198   }
11199
11200   // Decompose 256-bit shifts into smaller 128-bit shifts.
11201   if (VT.is256BitVector()) {
11202     unsigned NumElems = VT.getVectorNumElements();
11203     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11204     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11205
11206     // Extract the two vectors
11207     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11208     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11209
11210     // Recreate the shift amount vectors
11211     SDValue Amt1, Amt2;
11212     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11213       // Constant shift amount
11214       SmallVector<SDValue, 4> Amt1Csts;
11215       SmallVector<SDValue, 4> Amt2Csts;
11216       for (unsigned i = 0; i != NumElems/2; ++i)
11217         Amt1Csts.push_back(Amt->getOperand(i));
11218       for (unsigned i = NumElems/2; i != NumElems; ++i)
11219         Amt2Csts.push_back(Amt->getOperand(i));
11220
11221       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11222                                  &Amt1Csts[0], NumElems/2);
11223       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11224                                  &Amt2Csts[0], NumElems/2);
11225     } else {
11226       // Variable shift amount
11227       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11228       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11229     }
11230
11231     // Issue new vector shifts for the smaller types
11232     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11233     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11234
11235     // Concatenate the result back
11236     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11237   }
11238
11239   return SDValue();
11240 }
11241
11242 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11243   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11244   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11245   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11246   // has only one use.
11247   SDNode *N = Op.getNode();
11248   SDValue LHS = N->getOperand(0);
11249   SDValue RHS = N->getOperand(1);
11250   unsigned BaseOp = 0;
11251   unsigned Cond = 0;
11252   DebugLoc DL = Op.getDebugLoc();
11253   switch (Op.getOpcode()) {
11254   default: llvm_unreachable("Unknown ovf instruction!");
11255   case ISD::SADDO:
11256     // A subtract of one will be selected as a INC. Note that INC doesn't
11257     // set CF, so we can't do this for UADDO.
11258     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11259       if (C->isOne()) {
11260         BaseOp = X86ISD::INC;
11261         Cond = X86::COND_O;
11262         break;
11263       }
11264     BaseOp = X86ISD::ADD;
11265     Cond = X86::COND_O;
11266     break;
11267   case ISD::UADDO:
11268     BaseOp = X86ISD::ADD;
11269     Cond = X86::COND_B;
11270     break;
11271   case ISD::SSUBO:
11272     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11273     // set CF, so we can't do this for USUBO.
11274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11275       if (C->isOne()) {
11276         BaseOp = X86ISD::DEC;
11277         Cond = X86::COND_O;
11278         break;
11279       }
11280     BaseOp = X86ISD::SUB;
11281     Cond = X86::COND_O;
11282     break;
11283   case ISD::USUBO:
11284     BaseOp = X86ISD::SUB;
11285     Cond = X86::COND_B;
11286     break;
11287   case ISD::SMULO:
11288     BaseOp = X86ISD::SMUL;
11289     Cond = X86::COND_O;
11290     break;
11291   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11292     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11293                                  MVT::i32);
11294     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11295
11296     SDValue SetCC =
11297       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11298                   DAG.getConstant(X86::COND_O, MVT::i32),
11299                   SDValue(Sum.getNode(), 2));
11300
11301     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11302   }
11303   }
11304
11305   // Also sets EFLAGS.
11306   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11307   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11308
11309   SDValue SetCC =
11310     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11311                 DAG.getConstant(Cond, MVT::i32),
11312                 SDValue(Sum.getNode(), 1));
11313
11314   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11315 }
11316
11317 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11318                                                   SelectionDAG &DAG) const {
11319   DebugLoc dl = Op.getDebugLoc();
11320   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11321   EVT VT = Op.getValueType();
11322
11323   if (!Subtarget->hasSSE2() || !VT.isVector())
11324     return SDValue();
11325
11326   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11327                       ExtraVT.getScalarType().getSizeInBits();
11328   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11329
11330   switch (VT.getSimpleVT().SimpleTy) {
11331     default: return SDValue();
11332     case MVT::v8i32:
11333     case MVT::v16i16:
11334       if (!Subtarget->hasAVX())
11335         return SDValue();
11336       if (!Subtarget->hasAVX2()) {
11337         // needs to be split
11338         unsigned NumElems = VT.getVectorNumElements();
11339
11340         // Extract the LHS vectors
11341         SDValue LHS = Op.getOperand(0);
11342         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11343         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11344
11345         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11346         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11347
11348         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11349         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11350         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11351                                    ExtraNumElems/2);
11352         SDValue Extra = DAG.getValueType(ExtraVT);
11353
11354         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11355         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11356
11357         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11358       }
11359       // fall through
11360     case MVT::v4i32:
11361     case MVT::v8i16: {
11362       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11363                                          Op.getOperand(0), ShAmt, DAG);
11364       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11365     }
11366   }
11367 }
11368
11369
11370 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11371                               SelectionDAG &DAG) {
11372   DebugLoc dl = Op.getDebugLoc();
11373
11374   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11375   // There isn't any reason to disable it if the target processor supports it.
11376   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11377     SDValue Chain = Op.getOperand(0);
11378     SDValue Zero = DAG.getConstant(0, MVT::i32);
11379     SDValue Ops[] = {
11380       DAG.getRegister(X86::ESP, MVT::i32), // Base
11381       DAG.getTargetConstant(1, MVT::i8),   // Scale
11382       DAG.getRegister(0, MVT::i32),        // Index
11383       DAG.getTargetConstant(0, MVT::i32),  // Disp
11384       DAG.getRegister(0, MVT::i32),        // Segment.
11385       Zero,
11386       Chain
11387     };
11388     SDNode *Res =
11389       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11390                           array_lengthof(Ops));
11391     return SDValue(Res, 0);
11392   }
11393
11394   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11395   if (!isDev)
11396     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11397
11398   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11399   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11400   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11401   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11402
11403   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11404   if (!Op1 && !Op2 && !Op3 && Op4)
11405     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11406
11407   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11408   if (Op1 && !Op2 && !Op3 && !Op4)
11409     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11410
11411   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11412   //           (MFENCE)>;
11413   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11414 }
11415
11416 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11417                                  SelectionDAG &DAG) {
11418   DebugLoc dl = Op.getDebugLoc();
11419   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11420     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11421   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11422     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11423
11424   // The only fence that needs an instruction is a sequentially-consistent
11425   // cross-thread fence.
11426   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11427     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11428     // no-sse2). There isn't any reason to disable it if the target processor
11429     // supports it.
11430     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11431       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11432
11433     SDValue Chain = Op.getOperand(0);
11434     SDValue Zero = DAG.getConstant(0, MVT::i32);
11435     SDValue Ops[] = {
11436       DAG.getRegister(X86::ESP, MVT::i32), // Base
11437       DAG.getTargetConstant(1, MVT::i8),   // Scale
11438       DAG.getRegister(0, MVT::i32),        // Index
11439       DAG.getTargetConstant(0, MVT::i32),  // Disp
11440       DAG.getRegister(0, MVT::i32),        // Segment.
11441       Zero,
11442       Chain
11443     };
11444     SDNode *Res =
11445       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11446                          array_lengthof(Ops));
11447     return SDValue(Res, 0);
11448   }
11449
11450   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11451   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11452 }
11453
11454
11455 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11456                              SelectionDAG &DAG) {
11457   EVT T = Op.getValueType();
11458   DebugLoc DL = Op.getDebugLoc();
11459   unsigned Reg = 0;
11460   unsigned size = 0;
11461   switch(T.getSimpleVT().SimpleTy) {
11462   default: llvm_unreachable("Invalid value type!");
11463   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11464   case MVT::i16: Reg = X86::AX;  size = 2; break;
11465   case MVT::i32: Reg = X86::EAX; size = 4; break;
11466   case MVT::i64:
11467     assert(Subtarget->is64Bit() && "Node not type legal!");
11468     Reg = X86::RAX; size = 8;
11469     break;
11470   }
11471   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11472                                     Op.getOperand(2), SDValue());
11473   SDValue Ops[] = { cpIn.getValue(0),
11474                     Op.getOperand(1),
11475                     Op.getOperand(3),
11476                     DAG.getTargetConstant(size, MVT::i8),
11477                     cpIn.getValue(1) };
11478   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11479   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11480   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11481                                            Ops, 5, T, MMO);
11482   SDValue cpOut =
11483     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11484   return cpOut;
11485 }
11486
11487 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11488                                      SelectionDAG &DAG) {
11489   assert(Subtarget->is64Bit() && "Result not type legalized?");
11490   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11491   SDValue TheChain = Op.getOperand(0);
11492   DebugLoc dl = Op.getDebugLoc();
11493   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11494   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11495   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11496                                    rax.getValue(2));
11497   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11498                             DAG.getConstant(32, MVT::i8));
11499   SDValue Ops[] = {
11500     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11501     rdx.getValue(1)
11502   };
11503   return DAG.getMergeValues(Ops, 2, dl);
11504 }
11505
11506 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11507   EVT SrcVT = Op.getOperand(0).getValueType();
11508   EVT DstVT = Op.getValueType();
11509   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11510          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11511   assert((DstVT == MVT::i64 ||
11512           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11513          "Unexpected custom BITCAST");
11514   // i64 <=> MMX conversions are Legal.
11515   if (SrcVT==MVT::i64 && DstVT.isVector())
11516     return Op;
11517   if (DstVT==MVT::i64 && SrcVT.isVector())
11518     return Op;
11519   // MMX <=> MMX conversions are Legal.
11520   if (SrcVT.isVector() && DstVT.isVector())
11521     return Op;
11522   // All other conversions need to be expanded.
11523   return SDValue();
11524 }
11525
11526 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11527   SDNode *Node = Op.getNode();
11528   DebugLoc dl = Node->getDebugLoc();
11529   EVT T = Node->getValueType(0);
11530   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11531                               DAG.getConstant(0, T), Node->getOperand(2));
11532   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11533                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11534                        Node->getOperand(0),
11535                        Node->getOperand(1), negOp,
11536                        cast<AtomicSDNode>(Node)->getSrcValue(),
11537                        cast<AtomicSDNode>(Node)->getAlignment(),
11538                        cast<AtomicSDNode>(Node)->getOrdering(),
11539                        cast<AtomicSDNode>(Node)->getSynchScope());
11540 }
11541
11542 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11543   SDNode *Node = Op.getNode();
11544   DebugLoc dl = Node->getDebugLoc();
11545   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11546
11547   // Convert seq_cst store -> xchg
11548   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11549   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11550   //        (The only way to get a 16-byte store is cmpxchg16b)
11551   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11552   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11553       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11554     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11555                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11556                                  Node->getOperand(0),
11557                                  Node->getOperand(1), Node->getOperand(2),
11558                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11559                                  cast<AtomicSDNode>(Node)->getOrdering(),
11560                                  cast<AtomicSDNode>(Node)->getSynchScope());
11561     return Swap.getValue(1);
11562   }
11563   // Other atomic stores have a simple pattern.
11564   return Op;
11565 }
11566
11567 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11568   EVT VT = Op.getNode()->getValueType(0);
11569
11570   // Let legalize expand this if it isn't a legal type yet.
11571   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11572     return SDValue();
11573
11574   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11575
11576   unsigned Opc;
11577   bool ExtraOp = false;
11578   switch (Op.getOpcode()) {
11579   default: llvm_unreachable("Invalid code");
11580   case ISD::ADDC: Opc = X86ISD::ADD; break;
11581   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11582   case ISD::SUBC: Opc = X86ISD::SUB; break;
11583   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11584   }
11585
11586   if (!ExtraOp)
11587     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11588                        Op.getOperand(1));
11589   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11590                      Op.getOperand(1), Op.getOperand(2));
11591 }
11592
11593 /// LowerOperation - Provide custom lowering hooks for some operations.
11594 ///
11595 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11596   switch (Op.getOpcode()) {
11597   default: llvm_unreachable("Should not custom lower this!");
11598   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11599   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11600   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11601   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11602   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11603   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11604   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11605   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11606   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11607   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11608   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11609   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11610   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11611   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11612   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11613   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11614   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11615   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11616   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11617   case ISD::SHL_PARTS:
11618   case ISD::SRA_PARTS:
11619   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11620   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11621   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11622   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11623   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11624   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11625   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11626   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11627   case ISD::FABS:               return LowerFABS(Op, DAG);
11628   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11629   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11630   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11631   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11632   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11633   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11634   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11635   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11636   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11637   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11638   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11639   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11640   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11641   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11642   case ISD::FRAME_TO_ARGS_OFFSET:
11643                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11644   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11645   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11646   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11647   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11648   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11649   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11650   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11651   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11652   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11653   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11654   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11655   case ISD::SRA:
11656   case ISD::SRL:
11657   case ISD::SHL:                return LowerShift(Op, DAG);
11658   case ISD::SADDO:
11659   case ISD::UADDO:
11660   case ISD::SSUBO:
11661   case ISD::USUBO:
11662   case ISD::SMULO:
11663   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11664   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11665   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11666   case ISD::ADDC:
11667   case ISD::ADDE:
11668   case ISD::SUBC:
11669   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11670   case ISD::ADD:                return LowerADD(Op, DAG);
11671   case ISD::SUB:                return LowerSUB(Op, DAG);
11672   }
11673 }
11674
11675 static void ReplaceATOMIC_LOAD(SDNode *Node,
11676                                   SmallVectorImpl<SDValue> &Results,
11677                                   SelectionDAG &DAG) {
11678   DebugLoc dl = Node->getDebugLoc();
11679   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11680
11681   // Convert wide load -> cmpxchg8b/cmpxchg16b
11682   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11683   //        (The only way to get a 16-byte load is cmpxchg16b)
11684   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11685   SDValue Zero = DAG.getConstant(0, VT);
11686   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11687                                Node->getOperand(0),
11688                                Node->getOperand(1), Zero, Zero,
11689                                cast<AtomicSDNode>(Node)->getMemOperand(),
11690                                cast<AtomicSDNode>(Node)->getOrdering(),
11691                                cast<AtomicSDNode>(Node)->getSynchScope());
11692   Results.push_back(Swap.getValue(0));
11693   Results.push_back(Swap.getValue(1));
11694 }
11695
11696 static void
11697 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11698                         SelectionDAG &DAG, unsigned NewOp) {
11699   DebugLoc dl = Node->getDebugLoc();
11700   assert (Node->getValueType(0) == MVT::i64 &&
11701           "Only know how to expand i64 atomics");
11702
11703   SDValue Chain = Node->getOperand(0);
11704   SDValue In1 = Node->getOperand(1);
11705   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11706                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11707   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11708                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11709   SDValue Ops[] = { Chain, In1, In2L, In2H };
11710   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11711   SDValue Result =
11712     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11713                             cast<MemSDNode>(Node)->getMemOperand());
11714   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11715   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11716   Results.push_back(Result.getValue(2));
11717 }
11718
11719 /// ReplaceNodeResults - Replace a node with an illegal result type
11720 /// with a new node built out of custom code.
11721 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11722                                            SmallVectorImpl<SDValue>&Results,
11723                                            SelectionDAG &DAG) const {
11724   DebugLoc dl = N->getDebugLoc();
11725   switch (N->getOpcode()) {
11726   default:
11727     llvm_unreachable("Do not know how to custom type legalize this operation!");
11728   case ISD::SIGN_EXTEND_INREG:
11729   case ISD::ADDC:
11730   case ISD::ADDE:
11731   case ISD::SUBC:
11732   case ISD::SUBE:
11733     // We don't want to expand or promote these.
11734     return;
11735   case ISD::FP_TO_SINT:
11736   case ISD::FP_TO_UINT: {
11737     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11738
11739     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11740       return;
11741
11742     std::pair<SDValue,SDValue> Vals =
11743         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11744     SDValue FIST = Vals.first, StackSlot = Vals.second;
11745     if (FIST.getNode() != 0) {
11746       EVT VT = N->getValueType(0);
11747       // Return a load from the stack slot.
11748       if (StackSlot.getNode() != 0)
11749         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11750                                       MachinePointerInfo(),
11751                                       false, false, false, 0));
11752       else
11753         Results.push_back(FIST);
11754     }
11755     return;
11756   }
11757   case ISD::FP_ROUND: {
11758     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11759     Results.push_back(V);
11760     return;
11761   }
11762   case ISD::READCYCLECOUNTER: {
11763     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11764     SDValue TheChain = N->getOperand(0);
11765     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11766     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11767                                      rd.getValue(1));
11768     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11769                                      eax.getValue(2));
11770     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11771     SDValue Ops[] = { eax, edx };
11772     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11773     Results.push_back(edx.getValue(1));
11774     return;
11775   }
11776   case ISD::ATOMIC_CMP_SWAP: {
11777     EVT T = N->getValueType(0);
11778     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11779     bool Regs64bit = T == MVT::i128;
11780     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11781     SDValue cpInL, cpInH;
11782     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11783                         DAG.getConstant(0, HalfT));
11784     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11785                         DAG.getConstant(1, HalfT));
11786     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11787                              Regs64bit ? X86::RAX : X86::EAX,
11788                              cpInL, SDValue());
11789     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11790                              Regs64bit ? X86::RDX : X86::EDX,
11791                              cpInH, cpInL.getValue(1));
11792     SDValue swapInL, swapInH;
11793     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11794                           DAG.getConstant(0, HalfT));
11795     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11796                           DAG.getConstant(1, HalfT));
11797     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11798                                Regs64bit ? X86::RBX : X86::EBX,
11799                                swapInL, cpInH.getValue(1));
11800     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11801                                Regs64bit ? X86::RCX : X86::ECX,
11802                                swapInH, swapInL.getValue(1));
11803     SDValue Ops[] = { swapInH.getValue(0),
11804                       N->getOperand(1),
11805                       swapInH.getValue(1) };
11806     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11807     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11808     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11809                                   X86ISD::LCMPXCHG8_DAG;
11810     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11811                                              Ops, 3, T, MMO);
11812     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11813                                         Regs64bit ? X86::RAX : X86::EAX,
11814                                         HalfT, Result.getValue(1));
11815     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11816                                         Regs64bit ? X86::RDX : X86::EDX,
11817                                         HalfT, cpOutL.getValue(2));
11818     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11819     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11820     Results.push_back(cpOutH.getValue(1));
11821     return;
11822   }
11823   case ISD::ATOMIC_LOAD_ADD:
11824   case ISD::ATOMIC_LOAD_AND:
11825   case ISD::ATOMIC_LOAD_NAND:
11826   case ISD::ATOMIC_LOAD_OR:
11827   case ISD::ATOMIC_LOAD_SUB:
11828   case ISD::ATOMIC_LOAD_XOR:
11829   case ISD::ATOMIC_LOAD_MAX:
11830   case ISD::ATOMIC_LOAD_MIN:
11831   case ISD::ATOMIC_LOAD_UMAX:
11832   case ISD::ATOMIC_LOAD_UMIN:
11833   case ISD::ATOMIC_SWAP: {
11834     unsigned Opc;
11835     switch (N->getOpcode()) {
11836     default: llvm_unreachable("Unexpected opcode");
11837     case ISD::ATOMIC_LOAD_ADD:
11838       Opc = X86ISD::ATOMADD64_DAG;
11839       break;
11840     case ISD::ATOMIC_LOAD_AND:
11841       Opc = X86ISD::ATOMAND64_DAG;
11842       break;
11843     case ISD::ATOMIC_LOAD_NAND:
11844       Opc = X86ISD::ATOMNAND64_DAG;
11845       break;
11846     case ISD::ATOMIC_LOAD_OR:
11847       Opc = X86ISD::ATOMOR64_DAG;
11848       break;
11849     case ISD::ATOMIC_LOAD_SUB:
11850       Opc = X86ISD::ATOMSUB64_DAG;
11851       break;
11852     case ISD::ATOMIC_LOAD_XOR:
11853       Opc = X86ISD::ATOMXOR64_DAG;
11854       break;
11855     case ISD::ATOMIC_LOAD_MAX:
11856       Opc = X86ISD::ATOMMAX64_DAG;
11857       break;
11858     case ISD::ATOMIC_LOAD_MIN:
11859       Opc = X86ISD::ATOMMIN64_DAG;
11860       break;
11861     case ISD::ATOMIC_LOAD_UMAX:
11862       Opc = X86ISD::ATOMUMAX64_DAG;
11863       break;
11864     case ISD::ATOMIC_LOAD_UMIN:
11865       Opc = X86ISD::ATOMUMIN64_DAG;
11866       break;
11867     case ISD::ATOMIC_SWAP:
11868       Opc = X86ISD::ATOMSWAP64_DAG;
11869       break;
11870     }
11871     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11872     return;
11873   }
11874   case ISD::ATOMIC_LOAD:
11875     ReplaceATOMIC_LOAD(N, Results, DAG);
11876   }
11877 }
11878
11879 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11880   switch (Opcode) {
11881   default: return NULL;
11882   case X86ISD::BSF:                return "X86ISD::BSF";
11883   case X86ISD::BSR:                return "X86ISD::BSR";
11884   case X86ISD::SHLD:               return "X86ISD::SHLD";
11885   case X86ISD::SHRD:               return "X86ISD::SHRD";
11886   case X86ISD::FAND:               return "X86ISD::FAND";
11887   case X86ISD::FOR:                return "X86ISD::FOR";
11888   case X86ISD::FXOR:               return "X86ISD::FXOR";
11889   case X86ISD::FSRL:               return "X86ISD::FSRL";
11890   case X86ISD::FILD:               return "X86ISD::FILD";
11891   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11892   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11893   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11894   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11895   case X86ISD::FLD:                return "X86ISD::FLD";
11896   case X86ISD::FST:                return "X86ISD::FST";
11897   case X86ISD::CALL:               return "X86ISD::CALL";
11898   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11899   case X86ISD::BT:                 return "X86ISD::BT";
11900   case X86ISD::CMP:                return "X86ISD::CMP";
11901   case X86ISD::COMI:               return "X86ISD::COMI";
11902   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11903   case X86ISD::SETCC:              return "X86ISD::SETCC";
11904   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11905   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11906   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11907   case X86ISD::CMOV:               return "X86ISD::CMOV";
11908   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11909   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11910   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11911   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11912   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11913   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11914   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11915   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11916   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11917   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11918   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11919   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11920   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11921   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11922   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11923   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11924   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11925   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11926   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11927   case X86ISD::HADD:               return "X86ISD::HADD";
11928   case X86ISD::HSUB:               return "X86ISD::HSUB";
11929   case X86ISD::FHADD:              return "X86ISD::FHADD";
11930   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11931   case X86ISD::FMAX:               return "X86ISD::FMAX";
11932   case X86ISD::FMIN:               return "X86ISD::FMIN";
11933   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11934   case X86ISD::FMINC:              return "X86ISD::FMINC";
11935   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11936   case X86ISD::FRCP:               return "X86ISD::FRCP";
11937   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11938   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11939   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11940   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11941   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11942   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11943   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11944   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11945   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11946   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11947   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11948   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11949   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11950   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11951   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11952   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11953   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11954   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11955   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11956   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11957   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
11958   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
11959   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11960   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11961   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11962   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11963   case X86ISD::VSHL:               return "X86ISD::VSHL";
11964   case X86ISD::VSRL:               return "X86ISD::VSRL";
11965   case X86ISD::VSRA:               return "X86ISD::VSRA";
11966   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11967   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11968   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11969   case X86ISD::CMPP:               return "X86ISD::CMPP";
11970   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11971   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11972   case X86ISD::ADD:                return "X86ISD::ADD";
11973   case X86ISD::SUB:                return "X86ISD::SUB";
11974   case X86ISD::ADC:                return "X86ISD::ADC";
11975   case X86ISD::SBB:                return "X86ISD::SBB";
11976   case X86ISD::SMUL:               return "X86ISD::SMUL";
11977   case X86ISD::UMUL:               return "X86ISD::UMUL";
11978   case X86ISD::INC:                return "X86ISD::INC";
11979   case X86ISD::DEC:                return "X86ISD::DEC";
11980   case X86ISD::OR:                 return "X86ISD::OR";
11981   case X86ISD::XOR:                return "X86ISD::XOR";
11982   case X86ISD::AND:                return "X86ISD::AND";
11983   case X86ISD::ANDN:               return "X86ISD::ANDN";
11984   case X86ISD::BLSI:               return "X86ISD::BLSI";
11985   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11986   case X86ISD::BLSR:               return "X86ISD::BLSR";
11987   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11988   case X86ISD::PTEST:              return "X86ISD::PTEST";
11989   case X86ISD::TESTP:              return "X86ISD::TESTP";
11990   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11991   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11992   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11993   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11994   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11995   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11996   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11997   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11998   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11999   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12000   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12001   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12002   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12003   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12004   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12005   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12006   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12007   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12008   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12009   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12010   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12011   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12012   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12013   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12014   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12015   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12016   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12017   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12018   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12019   case X86ISD::SAHF:               return "X86ISD::SAHF";
12020   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12021   case X86ISD::FMADD:              return "X86ISD::FMADD";
12022   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12023   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12024   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12025   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12026   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12027   }
12028 }
12029
12030 // isLegalAddressingMode - Return true if the addressing mode represented
12031 // by AM is legal for this target, for a load/store of the specified type.
12032 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12033                                               Type *Ty) const {
12034   // X86 supports extremely general addressing modes.
12035   CodeModel::Model M = getTargetMachine().getCodeModel();
12036   Reloc::Model R = getTargetMachine().getRelocationModel();
12037
12038   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12039   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12040     return false;
12041
12042   if (AM.BaseGV) {
12043     unsigned GVFlags =
12044       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12045
12046     // If a reference to this global requires an extra load, we can't fold it.
12047     if (isGlobalStubReference(GVFlags))
12048       return false;
12049
12050     // If BaseGV requires a register for the PIC base, we cannot also have a
12051     // BaseReg specified.
12052     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12053       return false;
12054
12055     // If lower 4G is not available, then we must use rip-relative addressing.
12056     if ((M != CodeModel::Small || R != Reloc::Static) &&
12057         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12058       return false;
12059   }
12060
12061   switch (AM.Scale) {
12062   case 0:
12063   case 1:
12064   case 2:
12065   case 4:
12066   case 8:
12067     // These scales always work.
12068     break;
12069   case 3:
12070   case 5:
12071   case 9:
12072     // These scales are formed with basereg+scalereg.  Only accept if there is
12073     // no basereg yet.
12074     if (AM.HasBaseReg)
12075       return false;
12076     break;
12077   default:  // Other stuff never works.
12078     return false;
12079   }
12080
12081   return true;
12082 }
12083
12084
12085 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12086   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12087     return false;
12088   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12089   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12090   if (NumBits1 <= NumBits2)
12091     return false;
12092   return true;
12093 }
12094
12095 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12096   return Imm == (int32_t)Imm;
12097 }
12098
12099 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12100   // Can also use sub to handle negated immediates.
12101   return Imm == (int32_t)Imm;
12102 }
12103
12104 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12105   if (!VT1.isInteger() || !VT2.isInteger())
12106     return false;
12107   unsigned NumBits1 = VT1.getSizeInBits();
12108   unsigned NumBits2 = VT2.getSizeInBits();
12109   if (NumBits1 <= NumBits2)
12110     return false;
12111   return true;
12112 }
12113
12114 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12115   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12116   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12117 }
12118
12119 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12120   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12121   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12122 }
12123
12124 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12125   // i16 instructions are longer (0x66 prefix) and potentially slower.
12126   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12127 }
12128
12129 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12130 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12131 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12132 /// are assumed to be legal.
12133 bool
12134 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12135                                       EVT VT) const {
12136   // Very little shuffling can be done for 64-bit vectors right now.
12137   if (VT.getSizeInBits() == 64)
12138     return false;
12139
12140   // FIXME: pshufb, blends, shifts.
12141   return (VT.getVectorNumElements() == 2 ||
12142           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12143           isMOVLMask(M, VT) ||
12144           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12145           isPSHUFDMask(M, VT) ||
12146           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12147           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12148           isPALIGNRMask(M, VT, Subtarget) ||
12149           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12150           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12151           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12152           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12153 }
12154
12155 bool
12156 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12157                                           EVT VT) const {
12158   unsigned NumElts = VT.getVectorNumElements();
12159   // FIXME: This collection of masks seems suspect.
12160   if (NumElts == 2)
12161     return true;
12162   if (NumElts == 4 && VT.is128BitVector()) {
12163     return (isMOVLMask(Mask, VT)  ||
12164             isCommutedMOVLMask(Mask, VT, true) ||
12165             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12166             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12167   }
12168   return false;
12169 }
12170
12171 //===----------------------------------------------------------------------===//
12172 //                           X86 Scheduler Hooks
12173 //===----------------------------------------------------------------------===//
12174
12175 // private utility function
12176
12177 // Get CMPXCHG opcode for the specified data type.
12178 static unsigned getCmpXChgOpcode(EVT VT) {
12179   switch (VT.getSimpleVT().SimpleTy) {
12180   case MVT::i8:  return X86::LCMPXCHG8;
12181   case MVT::i16: return X86::LCMPXCHG16;
12182   case MVT::i32: return X86::LCMPXCHG32;
12183   case MVT::i64: return X86::LCMPXCHG64;
12184   default:
12185     break;
12186   }
12187   llvm_unreachable("Invalid operand size!");
12188 }
12189
12190 // Get LOAD opcode for the specified data type.
12191 static unsigned getLoadOpcode(EVT VT) {
12192   switch (VT.getSimpleVT().SimpleTy) {
12193   case MVT::i8:  return X86::MOV8rm;
12194   case MVT::i16: return X86::MOV16rm;
12195   case MVT::i32: return X86::MOV32rm;
12196   case MVT::i64: return X86::MOV64rm;
12197   default:
12198     break;
12199   }
12200   llvm_unreachable("Invalid operand size!");
12201 }
12202
12203 // Get opcode of the non-atomic one from the specified atomic instruction.
12204 static unsigned getNonAtomicOpcode(unsigned Opc) {
12205   switch (Opc) {
12206   case X86::ATOMAND8:  return X86::AND8rr;
12207   case X86::ATOMAND16: return X86::AND16rr;
12208   case X86::ATOMAND32: return X86::AND32rr;
12209   case X86::ATOMAND64: return X86::AND64rr;
12210   case X86::ATOMOR8:   return X86::OR8rr;
12211   case X86::ATOMOR16:  return X86::OR16rr;
12212   case X86::ATOMOR32:  return X86::OR32rr;
12213   case X86::ATOMOR64:  return X86::OR64rr;
12214   case X86::ATOMXOR8:  return X86::XOR8rr;
12215   case X86::ATOMXOR16: return X86::XOR16rr;
12216   case X86::ATOMXOR32: return X86::XOR32rr;
12217   case X86::ATOMXOR64: return X86::XOR64rr;
12218   }
12219   llvm_unreachable("Unhandled atomic-load-op opcode!");
12220 }
12221
12222 // Get opcode of the non-atomic one from the specified atomic instruction with
12223 // extra opcode.
12224 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12225                                                unsigned &ExtraOpc) {
12226   switch (Opc) {
12227   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12228   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12229   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12230   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12231   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12232   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12233   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12234   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12235   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12236   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12237   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12238   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12239   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12240   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12241   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12242   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12243   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12244   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12245   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12246   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12247   }
12248   llvm_unreachable("Unhandled atomic-load-op opcode!");
12249 }
12250
12251 // Get opcode of the non-atomic one from the specified atomic instruction for
12252 // 64-bit data type on 32-bit target.
12253 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12254   switch (Opc) {
12255   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12256   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12257   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12258   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12259   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12260   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12261   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12262   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12263   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12264   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12265   }
12266   llvm_unreachable("Unhandled atomic-load-op opcode!");
12267 }
12268
12269 // Get opcode of the non-atomic one from the specified atomic instruction for
12270 // 64-bit data type on 32-bit target with extra opcode.
12271 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12272                                                    unsigned &HiOpc,
12273                                                    unsigned &ExtraOpc) {
12274   switch (Opc) {
12275   case X86::ATOMNAND6432:
12276     ExtraOpc = X86::NOT32r;
12277     HiOpc = X86::AND32rr;
12278     return X86::AND32rr;
12279   }
12280   llvm_unreachable("Unhandled atomic-load-op opcode!");
12281 }
12282
12283 // Get pseudo CMOV opcode from the specified data type.
12284 static unsigned getPseudoCMOVOpc(EVT VT) {
12285   switch (VT.getSimpleVT().SimpleTy) {
12286   case MVT::i8:  return X86::CMOV_GR8;
12287   case MVT::i16: return X86::CMOV_GR16;
12288   case MVT::i32: return X86::CMOV_GR32;
12289   default:
12290     break;
12291   }
12292   llvm_unreachable("Unknown CMOV opcode!");
12293 }
12294
12295 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12296 // They will be translated into a spin-loop or compare-exchange loop from
12297 //
12298 //    ...
12299 //    dst = atomic-fetch-op MI.addr, MI.val
12300 //    ...
12301 //
12302 // to
12303 //
12304 //    ...
12305 //    EAX = LOAD MI.addr
12306 // loop:
12307 //    t1 = OP MI.val, EAX
12308 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12309 //    JNE loop
12310 // sink:
12311 //    dst = EAX
12312 //    ...
12313 MachineBasicBlock *
12314 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12315                                        MachineBasicBlock *MBB) const {
12316   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12317   DebugLoc DL = MI->getDebugLoc();
12318
12319   MachineFunction *MF = MBB->getParent();
12320   MachineRegisterInfo &MRI = MF->getRegInfo();
12321
12322   const BasicBlock *BB = MBB->getBasicBlock();
12323   MachineFunction::iterator I = MBB;
12324   ++I;
12325
12326   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12327          "Unexpected number of operands");
12328
12329   assert(MI->hasOneMemOperand() &&
12330          "Expected atomic-load-op to have one memoperand");
12331
12332   // Memory Reference
12333   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12334   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12335
12336   unsigned DstReg, SrcReg;
12337   unsigned MemOpndSlot;
12338
12339   unsigned CurOp = 0;
12340
12341   DstReg = MI->getOperand(CurOp++).getReg();
12342   MemOpndSlot = CurOp;
12343   CurOp += X86::AddrNumOperands;
12344   SrcReg = MI->getOperand(CurOp++).getReg();
12345
12346   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12347   MVT::SimpleValueType VT = *RC->vt_begin();
12348   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12349
12350   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12351   unsigned LOADOpc = getLoadOpcode(VT);
12352
12353   // For the atomic load-arith operator, we generate
12354   //
12355   //  thisMBB:
12356   //    EAX = LOAD [MI.addr]
12357   //  mainMBB:
12358   //    t1 = OP MI.val, EAX
12359   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12360   //    JNE mainMBB
12361   //  sinkMBB:
12362
12363   MachineBasicBlock *thisMBB = MBB;
12364   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12365   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12366   MF->insert(I, mainMBB);
12367   MF->insert(I, sinkMBB);
12368
12369   MachineInstrBuilder MIB;
12370
12371   // Transfer the remainder of BB and its successor edges to sinkMBB.
12372   sinkMBB->splice(sinkMBB->begin(), MBB,
12373                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12374   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12375
12376   // thisMBB:
12377   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12378   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12379     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12380   MIB.setMemRefs(MMOBegin, MMOEnd);
12381
12382   thisMBB->addSuccessor(mainMBB);
12383
12384   // mainMBB:
12385   MachineBasicBlock *origMainMBB = mainMBB;
12386   mainMBB->addLiveIn(AccPhyReg);
12387
12388   // Copy AccPhyReg as it is used more than once.
12389   unsigned AccReg = MRI.createVirtualRegister(RC);
12390   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12391     .addReg(AccPhyReg);
12392
12393   unsigned t1 = MRI.createVirtualRegister(RC);
12394   unsigned Opc = MI->getOpcode();
12395   switch (Opc) {
12396   default:
12397     llvm_unreachable("Unhandled atomic-load-op opcode!");
12398   case X86::ATOMAND8:
12399   case X86::ATOMAND16:
12400   case X86::ATOMAND32:
12401   case X86::ATOMAND64:
12402   case X86::ATOMOR8:
12403   case X86::ATOMOR16:
12404   case X86::ATOMOR32:
12405   case X86::ATOMOR64:
12406   case X86::ATOMXOR8:
12407   case X86::ATOMXOR16:
12408   case X86::ATOMXOR32:
12409   case X86::ATOMXOR64: {
12410     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12411     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12412       .addReg(AccReg);
12413     break;
12414   }
12415   case X86::ATOMNAND8:
12416   case X86::ATOMNAND16:
12417   case X86::ATOMNAND32:
12418   case X86::ATOMNAND64: {
12419     unsigned t2 = MRI.createVirtualRegister(RC);
12420     unsigned NOTOpc;
12421     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12422     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12423       .addReg(AccReg);
12424     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12425     break;
12426   }
12427   case X86::ATOMMAX8:
12428   case X86::ATOMMAX16:
12429   case X86::ATOMMAX32:
12430   case X86::ATOMMAX64:
12431   case X86::ATOMMIN8:
12432   case X86::ATOMMIN16:
12433   case X86::ATOMMIN32:
12434   case X86::ATOMMIN64:
12435   case X86::ATOMUMAX8:
12436   case X86::ATOMUMAX16:
12437   case X86::ATOMUMAX32:
12438   case X86::ATOMUMAX64:
12439   case X86::ATOMUMIN8:
12440   case X86::ATOMUMIN16:
12441   case X86::ATOMUMIN32:
12442   case X86::ATOMUMIN64: {
12443     unsigned CMPOpc;
12444     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12445
12446     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12447       .addReg(SrcReg)
12448       .addReg(AccReg);
12449
12450     if (Subtarget->hasCMov()) {
12451       if (VT != MVT::i8) {
12452         // Native support
12453         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12454           .addReg(SrcReg)
12455           .addReg(AccReg);
12456       } else {
12457         // Promote i8 to i32 to use CMOV32
12458         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12459         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12460         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12461         unsigned t2 = MRI.createVirtualRegister(RC32);
12462
12463         unsigned Undef = MRI.createVirtualRegister(RC32);
12464         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12465
12466         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12467           .addReg(Undef)
12468           .addReg(SrcReg)
12469           .addImm(X86::sub_8bit);
12470         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12471           .addReg(Undef)
12472           .addReg(AccReg)
12473           .addImm(X86::sub_8bit);
12474
12475         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12476           .addReg(SrcReg32)
12477           .addReg(AccReg32);
12478
12479         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12480           .addReg(t2, 0, X86::sub_8bit);
12481       }
12482     } else {
12483       // Use pseudo select and lower them.
12484       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12485              "Invalid atomic-load-op transformation!");
12486       unsigned SelOpc = getPseudoCMOVOpc(VT);
12487       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12488       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12489       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12490               .addReg(SrcReg).addReg(AccReg)
12491               .addImm(CC);
12492       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12493     }
12494     break;
12495   }
12496   }
12497
12498   // Copy AccPhyReg back from virtual register.
12499   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12500     .addReg(AccReg);
12501
12502   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12503   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12504     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12505   MIB.addReg(t1);
12506   MIB.setMemRefs(MMOBegin, MMOEnd);
12507
12508   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12509
12510   mainMBB->addSuccessor(origMainMBB);
12511   mainMBB->addSuccessor(sinkMBB);
12512
12513   // sinkMBB:
12514   sinkMBB->addLiveIn(AccPhyReg);
12515
12516   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12517           TII->get(TargetOpcode::COPY), DstReg)
12518     .addReg(AccPhyReg);
12519
12520   MI->eraseFromParent();
12521   return sinkMBB;
12522 }
12523
12524 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12525 // instructions. They will be translated into a spin-loop or compare-exchange
12526 // loop from
12527 //
12528 //    ...
12529 //    dst = atomic-fetch-op MI.addr, MI.val
12530 //    ...
12531 //
12532 // to
12533 //
12534 //    ...
12535 //    EAX = LOAD [MI.addr + 0]
12536 //    EDX = LOAD [MI.addr + 4]
12537 // loop:
12538 //    EBX = OP MI.val.lo, EAX
12539 //    ECX = OP MI.val.hi, EDX
12540 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12541 //    JNE loop
12542 // sink:
12543 //    dst = EDX:EAX
12544 //    ...
12545 MachineBasicBlock *
12546 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12547                                            MachineBasicBlock *MBB) const {
12548   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12549   DebugLoc DL = MI->getDebugLoc();
12550
12551   MachineFunction *MF = MBB->getParent();
12552   MachineRegisterInfo &MRI = MF->getRegInfo();
12553
12554   const BasicBlock *BB = MBB->getBasicBlock();
12555   MachineFunction::iterator I = MBB;
12556   ++I;
12557
12558   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12559          "Unexpected number of operands");
12560
12561   assert(MI->hasOneMemOperand() &&
12562          "Expected atomic-load-op32 to have one memoperand");
12563
12564   // Memory Reference
12565   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12566   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12567
12568   unsigned DstLoReg, DstHiReg;
12569   unsigned SrcLoReg, SrcHiReg;
12570   unsigned MemOpndSlot;
12571
12572   unsigned CurOp = 0;
12573
12574   DstLoReg = MI->getOperand(CurOp++).getReg();
12575   DstHiReg = MI->getOperand(CurOp++).getReg();
12576   MemOpndSlot = CurOp;
12577   CurOp += X86::AddrNumOperands;
12578   SrcLoReg = MI->getOperand(CurOp++).getReg();
12579   SrcHiReg = MI->getOperand(CurOp++).getReg();
12580
12581   const TargetRegisterClass *RC = &X86::GR32RegClass;
12582   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12583
12584   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12585   unsigned LOADOpc = X86::MOV32rm;
12586
12587   // For the atomic load-arith operator, we generate
12588   //
12589   //  thisMBB:
12590   //    EAX = LOAD [MI.addr + 0]
12591   //    EDX = LOAD [MI.addr + 4]
12592   //  mainMBB:
12593   //    EBX = OP MI.vallo, EAX
12594   //    ECX = OP MI.valhi, EDX
12595   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12596   //    JNE mainMBB
12597   //  sinkMBB:
12598
12599   MachineBasicBlock *thisMBB = MBB;
12600   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12601   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12602   MF->insert(I, mainMBB);
12603   MF->insert(I, sinkMBB);
12604
12605   MachineInstrBuilder MIB;
12606
12607   // Transfer the remainder of BB and its successor edges to sinkMBB.
12608   sinkMBB->splice(sinkMBB->begin(), MBB,
12609                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12610   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12611
12612   // thisMBB:
12613   // Lo
12614   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12615   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12616     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12617   MIB.setMemRefs(MMOBegin, MMOEnd);
12618   // Hi
12619   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12620   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12621     if (i == X86::AddrDisp)
12622       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12623     else
12624       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12625   }
12626   MIB.setMemRefs(MMOBegin, MMOEnd);
12627
12628   thisMBB->addSuccessor(mainMBB);
12629
12630   // mainMBB:
12631   MachineBasicBlock *origMainMBB = mainMBB;
12632   mainMBB->addLiveIn(X86::EAX);
12633   mainMBB->addLiveIn(X86::EDX);
12634
12635   // Copy EDX:EAX as they are used more than once.
12636   unsigned LoReg = MRI.createVirtualRegister(RC);
12637   unsigned HiReg = MRI.createVirtualRegister(RC);
12638   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12639   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12640
12641   unsigned t1L = MRI.createVirtualRegister(RC);
12642   unsigned t1H = MRI.createVirtualRegister(RC);
12643
12644   unsigned Opc = MI->getOpcode();
12645   switch (Opc) {
12646   default:
12647     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12648   case X86::ATOMAND6432:
12649   case X86::ATOMOR6432:
12650   case X86::ATOMXOR6432:
12651   case X86::ATOMADD6432:
12652   case X86::ATOMSUB6432: {
12653     unsigned HiOpc;
12654     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12655     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12656     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12657     break;
12658   }
12659   case X86::ATOMNAND6432: {
12660     unsigned HiOpc, NOTOpc;
12661     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12662     unsigned t2L = MRI.createVirtualRegister(RC);
12663     unsigned t2H = MRI.createVirtualRegister(RC);
12664     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12665     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12666     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12667     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12668     break;
12669   }
12670   case X86::ATOMMAX6432:
12671   case X86::ATOMMIN6432:
12672   case X86::ATOMUMAX6432:
12673   case X86::ATOMUMIN6432: {
12674     unsigned HiOpc;
12675     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12676     unsigned cL = MRI.createVirtualRegister(RC8);
12677     unsigned cH = MRI.createVirtualRegister(RC8);
12678     unsigned cL32 = MRI.createVirtualRegister(RC);
12679     unsigned cH32 = MRI.createVirtualRegister(RC);
12680     unsigned cc = MRI.createVirtualRegister(RC);
12681     // cl := cmp src_lo, lo
12682     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12683       .addReg(SrcLoReg).addReg(LoReg);
12684     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12685     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12686     // ch := cmp src_hi, hi
12687     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12688       .addReg(SrcHiReg).addReg(HiReg);
12689     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12690     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12691     // cc := if (src_hi == hi) ? cl : ch;
12692     if (Subtarget->hasCMov()) {
12693       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12694         .addReg(cH32).addReg(cL32);
12695     } else {
12696       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12697               .addReg(cH32).addReg(cL32)
12698               .addImm(X86::COND_E);
12699       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12700     }
12701     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12702     if (Subtarget->hasCMov()) {
12703       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12704         .addReg(SrcLoReg).addReg(LoReg);
12705       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12706         .addReg(SrcHiReg).addReg(HiReg);
12707     } else {
12708       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12709               .addReg(SrcLoReg).addReg(LoReg)
12710               .addImm(X86::COND_NE);
12711       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12712       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12713               .addReg(SrcHiReg).addReg(HiReg)
12714               .addImm(X86::COND_NE);
12715       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12716     }
12717     break;
12718   }
12719   case X86::ATOMSWAP6432: {
12720     unsigned HiOpc;
12721     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12722     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12723     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12724     break;
12725   }
12726   }
12727
12728   // Copy EDX:EAX back from HiReg:LoReg
12729   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12730   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12731   // Copy ECX:EBX from t1H:t1L
12732   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12733   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12734
12735   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12736   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12737     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12738   MIB.setMemRefs(MMOBegin, MMOEnd);
12739
12740   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12741
12742   mainMBB->addSuccessor(origMainMBB);
12743   mainMBB->addSuccessor(sinkMBB);
12744
12745   // sinkMBB:
12746   sinkMBB->addLiveIn(X86::EAX);
12747   sinkMBB->addLiveIn(X86::EDX);
12748
12749   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12750           TII->get(TargetOpcode::COPY), DstLoReg)
12751     .addReg(X86::EAX);
12752   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12753           TII->get(TargetOpcode::COPY), DstHiReg)
12754     .addReg(X86::EDX);
12755
12756   MI->eraseFromParent();
12757   return sinkMBB;
12758 }
12759
12760 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12761 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12762 // in the .td file.
12763 MachineBasicBlock *
12764 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12765                             unsigned numArgs, bool memArg) const {
12766   assert(Subtarget->hasSSE42() &&
12767          "Target must have SSE4.2 or AVX features enabled");
12768
12769   DebugLoc dl = MI->getDebugLoc();
12770   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12771   unsigned Opc;
12772   if (!Subtarget->hasAVX()) {
12773     if (memArg)
12774       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12775     else
12776       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12777   } else {
12778     if (memArg)
12779       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12780     else
12781       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12782   }
12783
12784   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12785   for (unsigned i = 0; i < numArgs; ++i) {
12786     MachineOperand &Op = MI->getOperand(i+1);
12787     if (!(Op.isReg() && Op.isImplicit()))
12788       MIB.addOperand(Op);
12789   }
12790   BuildMI(*BB, MI, dl,
12791     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12792     .addReg(X86::XMM0);
12793
12794   MI->eraseFromParent();
12795   return BB;
12796 }
12797
12798 MachineBasicBlock *
12799 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12800   DebugLoc dl = MI->getDebugLoc();
12801   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12802
12803   // Address into RAX/EAX, other two args into ECX, EDX.
12804   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12805   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12806   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12807   for (int i = 0; i < X86::AddrNumOperands; ++i)
12808     MIB.addOperand(MI->getOperand(i));
12809
12810   unsigned ValOps = X86::AddrNumOperands;
12811   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12812     .addReg(MI->getOperand(ValOps).getReg());
12813   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12814     .addReg(MI->getOperand(ValOps+1).getReg());
12815
12816   // The instruction doesn't actually take any operands though.
12817   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12818
12819   MI->eraseFromParent(); // The pseudo is gone now.
12820   return BB;
12821 }
12822
12823 MachineBasicBlock *
12824 X86TargetLowering::EmitVAARG64WithCustomInserter(
12825                    MachineInstr *MI,
12826                    MachineBasicBlock *MBB) const {
12827   // Emit va_arg instruction on X86-64.
12828
12829   // Operands to this pseudo-instruction:
12830   // 0  ) Output        : destination address (reg)
12831   // 1-5) Input         : va_list address (addr, i64mem)
12832   // 6  ) ArgSize       : Size (in bytes) of vararg type
12833   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12834   // 8  ) Align         : Alignment of type
12835   // 9  ) EFLAGS (implicit-def)
12836
12837   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12838   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12839
12840   unsigned DestReg = MI->getOperand(0).getReg();
12841   MachineOperand &Base = MI->getOperand(1);
12842   MachineOperand &Scale = MI->getOperand(2);
12843   MachineOperand &Index = MI->getOperand(3);
12844   MachineOperand &Disp = MI->getOperand(4);
12845   MachineOperand &Segment = MI->getOperand(5);
12846   unsigned ArgSize = MI->getOperand(6).getImm();
12847   unsigned ArgMode = MI->getOperand(7).getImm();
12848   unsigned Align = MI->getOperand(8).getImm();
12849
12850   // Memory Reference
12851   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12852   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12853   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12854
12855   // Machine Information
12856   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12857   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12858   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12859   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12860   DebugLoc DL = MI->getDebugLoc();
12861
12862   // struct va_list {
12863   //   i32   gp_offset
12864   //   i32   fp_offset
12865   //   i64   overflow_area (address)
12866   //   i64   reg_save_area (address)
12867   // }
12868   // sizeof(va_list) = 24
12869   // alignment(va_list) = 8
12870
12871   unsigned TotalNumIntRegs = 6;
12872   unsigned TotalNumXMMRegs = 8;
12873   bool UseGPOffset = (ArgMode == 1);
12874   bool UseFPOffset = (ArgMode == 2);
12875   unsigned MaxOffset = TotalNumIntRegs * 8 +
12876                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12877
12878   /* Align ArgSize to a multiple of 8 */
12879   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12880   bool NeedsAlign = (Align > 8);
12881
12882   MachineBasicBlock *thisMBB = MBB;
12883   MachineBasicBlock *overflowMBB;
12884   MachineBasicBlock *offsetMBB;
12885   MachineBasicBlock *endMBB;
12886
12887   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12888   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12889   unsigned OffsetReg = 0;
12890
12891   if (!UseGPOffset && !UseFPOffset) {
12892     // If we only pull from the overflow region, we don't create a branch.
12893     // We don't need to alter control flow.
12894     OffsetDestReg = 0; // unused
12895     OverflowDestReg = DestReg;
12896
12897     offsetMBB = NULL;
12898     overflowMBB = thisMBB;
12899     endMBB = thisMBB;
12900   } else {
12901     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12902     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12903     // If not, pull from overflow_area. (branch to overflowMBB)
12904     //
12905     //       thisMBB
12906     //         |     .
12907     //         |        .
12908     //     offsetMBB   overflowMBB
12909     //         |        .
12910     //         |     .
12911     //        endMBB
12912
12913     // Registers for the PHI in endMBB
12914     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12915     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12916
12917     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12918     MachineFunction *MF = MBB->getParent();
12919     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12920     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12921     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12922
12923     MachineFunction::iterator MBBIter = MBB;
12924     ++MBBIter;
12925
12926     // Insert the new basic blocks
12927     MF->insert(MBBIter, offsetMBB);
12928     MF->insert(MBBIter, overflowMBB);
12929     MF->insert(MBBIter, endMBB);
12930
12931     // Transfer the remainder of MBB and its successor edges to endMBB.
12932     endMBB->splice(endMBB->begin(), thisMBB,
12933                     llvm::next(MachineBasicBlock::iterator(MI)),
12934                     thisMBB->end());
12935     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12936
12937     // Make offsetMBB and overflowMBB successors of thisMBB
12938     thisMBB->addSuccessor(offsetMBB);
12939     thisMBB->addSuccessor(overflowMBB);
12940
12941     // endMBB is a successor of both offsetMBB and overflowMBB
12942     offsetMBB->addSuccessor(endMBB);
12943     overflowMBB->addSuccessor(endMBB);
12944
12945     // Load the offset value into a register
12946     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12947     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12948       .addOperand(Base)
12949       .addOperand(Scale)
12950       .addOperand(Index)
12951       .addDisp(Disp, UseFPOffset ? 4 : 0)
12952       .addOperand(Segment)
12953       .setMemRefs(MMOBegin, MMOEnd);
12954
12955     // Check if there is enough room left to pull this argument.
12956     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12957       .addReg(OffsetReg)
12958       .addImm(MaxOffset + 8 - ArgSizeA8);
12959
12960     // Branch to "overflowMBB" if offset >= max
12961     // Fall through to "offsetMBB" otherwise
12962     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12963       .addMBB(overflowMBB);
12964   }
12965
12966   // In offsetMBB, emit code to use the reg_save_area.
12967   if (offsetMBB) {
12968     assert(OffsetReg != 0);
12969
12970     // Read the reg_save_area address.
12971     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12972     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12973       .addOperand(Base)
12974       .addOperand(Scale)
12975       .addOperand(Index)
12976       .addDisp(Disp, 16)
12977       .addOperand(Segment)
12978       .setMemRefs(MMOBegin, MMOEnd);
12979
12980     // Zero-extend the offset
12981     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12982       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12983         .addImm(0)
12984         .addReg(OffsetReg)
12985         .addImm(X86::sub_32bit);
12986
12987     // Add the offset to the reg_save_area to get the final address.
12988     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12989       .addReg(OffsetReg64)
12990       .addReg(RegSaveReg);
12991
12992     // Compute the offset for the next argument
12993     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12994     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12995       .addReg(OffsetReg)
12996       .addImm(UseFPOffset ? 16 : 8);
12997
12998     // Store it back into the va_list.
12999     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13000       .addOperand(Base)
13001       .addOperand(Scale)
13002       .addOperand(Index)
13003       .addDisp(Disp, UseFPOffset ? 4 : 0)
13004       .addOperand(Segment)
13005       .addReg(NextOffsetReg)
13006       .setMemRefs(MMOBegin, MMOEnd);
13007
13008     // Jump to endMBB
13009     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13010       .addMBB(endMBB);
13011   }
13012
13013   //
13014   // Emit code to use overflow area
13015   //
13016
13017   // Load the overflow_area address into a register.
13018   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13019   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13020     .addOperand(Base)
13021     .addOperand(Scale)
13022     .addOperand(Index)
13023     .addDisp(Disp, 8)
13024     .addOperand(Segment)
13025     .setMemRefs(MMOBegin, MMOEnd);
13026
13027   // If we need to align it, do so. Otherwise, just copy the address
13028   // to OverflowDestReg.
13029   if (NeedsAlign) {
13030     // Align the overflow address
13031     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13032     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13033
13034     // aligned_addr = (addr + (align-1)) & ~(align-1)
13035     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13036       .addReg(OverflowAddrReg)
13037       .addImm(Align-1);
13038
13039     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13040       .addReg(TmpReg)
13041       .addImm(~(uint64_t)(Align-1));
13042   } else {
13043     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13044       .addReg(OverflowAddrReg);
13045   }
13046
13047   // Compute the next overflow address after this argument.
13048   // (the overflow address should be kept 8-byte aligned)
13049   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13050   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13051     .addReg(OverflowDestReg)
13052     .addImm(ArgSizeA8);
13053
13054   // Store the new overflow address.
13055   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13056     .addOperand(Base)
13057     .addOperand(Scale)
13058     .addOperand(Index)
13059     .addDisp(Disp, 8)
13060     .addOperand(Segment)
13061     .addReg(NextAddrReg)
13062     .setMemRefs(MMOBegin, MMOEnd);
13063
13064   // If we branched, emit the PHI to the front of endMBB.
13065   if (offsetMBB) {
13066     BuildMI(*endMBB, endMBB->begin(), DL,
13067             TII->get(X86::PHI), DestReg)
13068       .addReg(OffsetDestReg).addMBB(offsetMBB)
13069       .addReg(OverflowDestReg).addMBB(overflowMBB);
13070   }
13071
13072   // Erase the pseudo instruction
13073   MI->eraseFromParent();
13074
13075   return endMBB;
13076 }
13077
13078 MachineBasicBlock *
13079 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13080                                                  MachineInstr *MI,
13081                                                  MachineBasicBlock *MBB) const {
13082   // Emit code to save XMM registers to the stack. The ABI says that the
13083   // number of registers to save is given in %al, so it's theoretically
13084   // possible to do an indirect jump trick to avoid saving all of them,
13085   // however this code takes a simpler approach and just executes all
13086   // of the stores if %al is non-zero. It's less code, and it's probably
13087   // easier on the hardware branch predictor, and stores aren't all that
13088   // expensive anyway.
13089
13090   // Create the new basic blocks. One block contains all the XMM stores,
13091   // and one block is the final destination regardless of whether any
13092   // stores were performed.
13093   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13094   MachineFunction *F = MBB->getParent();
13095   MachineFunction::iterator MBBIter = MBB;
13096   ++MBBIter;
13097   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13098   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13099   F->insert(MBBIter, XMMSaveMBB);
13100   F->insert(MBBIter, EndMBB);
13101
13102   // Transfer the remainder of MBB and its successor edges to EndMBB.
13103   EndMBB->splice(EndMBB->begin(), MBB,
13104                  llvm::next(MachineBasicBlock::iterator(MI)),
13105                  MBB->end());
13106   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13107
13108   // The original block will now fall through to the XMM save block.
13109   MBB->addSuccessor(XMMSaveMBB);
13110   // The XMMSaveMBB will fall through to the end block.
13111   XMMSaveMBB->addSuccessor(EndMBB);
13112
13113   // Now add the instructions.
13114   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13115   DebugLoc DL = MI->getDebugLoc();
13116
13117   unsigned CountReg = MI->getOperand(0).getReg();
13118   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13119   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13120
13121   if (!Subtarget->isTargetWin64()) {
13122     // If %al is 0, branch around the XMM save block.
13123     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13124     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13125     MBB->addSuccessor(EndMBB);
13126   }
13127
13128   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13129   // In the XMM save block, save all the XMM argument registers.
13130   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13131     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13132     MachineMemOperand *MMO =
13133       F->getMachineMemOperand(
13134           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13135         MachineMemOperand::MOStore,
13136         /*Size=*/16, /*Align=*/16);
13137     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13138       .addFrameIndex(RegSaveFrameIndex)
13139       .addImm(/*Scale=*/1)
13140       .addReg(/*IndexReg=*/0)
13141       .addImm(/*Disp=*/Offset)
13142       .addReg(/*Segment=*/0)
13143       .addReg(MI->getOperand(i).getReg())
13144       .addMemOperand(MMO);
13145   }
13146
13147   MI->eraseFromParent();   // The pseudo instruction is gone now.
13148
13149   return EndMBB;
13150 }
13151
13152 // The EFLAGS operand of SelectItr might be missing a kill marker
13153 // because there were multiple uses of EFLAGS, and ISel didn't know
13154 // which to mark. Figure out whether SelectItr should have had a
13155 // kill marker, and set it if it should. Returns the correct kill
13156 // marker value.
13157 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13158                                      MachineBasicBlock* BB,
13159                                      const TargetRegisterInfo* TRI) {
13160   // Scan forward through BB for a use/def of EFLAGS.
13161   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13162   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13163     const MachineInstr& mi = *miI;
13164     if (mi.readsRegister(X86::EFLAGS))
13165       return false;
13166     if (mi.definesRegister(X86::EFLAGS))
13167       break; // Should have kill-flag - update below.
13168   }
13169
13170   // If we hit the end of the block, check whether EFLAGS is live into a
13171   // successor.
13172   if (miI == BB->end()) {
13173     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13174                                           sEnd = BB->succ_end();
13175          sItr != sEnd; ++sItr) {
13176       MachineBasicBlock* succ = *sItr;
13177       if (succ->isLiveIn(X86::EFLAGS))
13178         return false;
13179     }
13180   }
13181
13182   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13183   // out. SelectMI should have a kill flag on EFLAGS.
13184   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13185   return true;
13186 }
13187
13188 MachineBasicBlock *
13189 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13190                                      MachineBasicBlock *BB) const {
13191   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13192   DebugLoc DL = MI->getDebugLoc();
13193
13194   // To "insert" a SELECT_CC instruction, we actually have to insert the
13195   // diamond control-flow pattern.  The incoming instruction knows the
13196   // destination vreg to set, the condition code register to branch on, the
13197   // true/false values to select between, and a branch opcode to use.
13198   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13199   MachineFunction::iterator It = BB;
13200   ++It;
13201
13202   //  thisMBB:
13203   //  ...
13204   //   TrueVal = ...
13205   //   cmpTY ccX, r1, r2
13206   //   bCC copy1MBB
13207   //   fallthrough --> copy0MBB
13208   MachineBasicBlock *thisMBB = BB;
13209   MachineFunction *F = BB->getParent();
13210   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13211   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13212   F->insert(It, copy0MBB);
13213   F->insert(It, sinkMBB);
13214
13215   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13216   // live into the sink and copy blocks.
13217   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13218   if (!MI->killsRegister(X86::EFLAGS) &&
13219       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13220     copy0MBB->addLiveIn(X86::EFLAGS);
13221     sinkMBB->addLiveIn(X86::EFLAGS);
13222   }
13223
13224   // Transfer the remainder of BB and its successor edges to sinkMBB.
13225   sinkMBB->splice(sinkMBB->begin(), BB,
13226                   llvm::next(MachineBasicBlock::iterator(MI)),
13227                   BB->end());
13228   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13229
13230   // Add the true and fallthrough blocks as its successors.
13231   BB->addSuccessor(copy0MBB);
13232   BB->addSuccessor(sinkMBB);
13233
13234   // Create the conditional branch instruction.
13235   unsigned Opc =
13236     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13237   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13238
13239   //  copy0MBB:
13240   //   %FalseValue = ...
13241   //   # fallthrough to sinkMBB
13242   copy0MBB->addSuccessor(sinkMBB);
13243
13244   //  sinkMBB:
13245   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13246   //  ...
13247   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13248           TII->get(X86::PHI), MI->getOperand(0).getReg())
13249     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13250     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13251
13252   MI->eraseFromParent();   // The pseudo instruction is gone now.
13253   return sinkMBB;
13254 }
13255
13256 MachineBasicBlock *
13257 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13258                                         bool Is64Bit) const {
13259   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13260   DebugLoc DL = MI->getDebugLoc();
13261   MachineFunction *MF = BB->getParent();
13262   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13263
13264   assert(getTargetMachine().Options.EnableSegmentedStacks);
13265
13266   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13267   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13268
13269   // BB:
13270   //  ... [Till the alloca]
13271   // If stacklet is not large enough, jump to mallocMBB
13272   //
13273   // bumpMBB:
13274   //  Allocate by subtracting from RSP
13275   //  Jump to continueMBB
13276   //
13277   // mallocMBB:
13278   //  Allocate by call to runtime
13279   //
13280   // continueMBB:
13281   //  ...
13282   //  [rest of original BB]
13283   //
13284
13285   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13286   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13287   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13288
13289   MachineRegisterInfo &MRI = MF->getRegInfo();
13290   const TargetRegisterClass *AddrRegClass =
13291     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13292
13293   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13294     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13295     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13296     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13297     sizeVReg = MI->getOperand(1).getReg(),
13298     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13299
13300   MachineFunction::iterator MBBIter = BB;
13301   ++MBBIter;
13302
13303   MF->insert(MBBIter, bumpMBB);
13304   MF->insert(MBBIter, mallocMBB);
13305   MF->insert(MBBIter, continueMBB);
13306
13307   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13308                       (MachineBasicBlock::iterator(MI)), BB->end());
13309   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13310
13311   // Add code to the main basic block to check if the stack limit has been hit,
13312   // and if so, jump to mallocMBB otherwise to bumpMBB.
13313   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13314   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13315     .addReg(tmpSPVReg).addReg(sizeVReg);
13316   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13317     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13318     .addReg(SPLimitVReg);
13319   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13320
13321   // bumpMBB simply decreases the stack pointer, since we know the current
13322   // stacklet has enough space.
13323   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13324     .addReg(SPLimitVReg);
13325   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13326     .addReg(SPLimitVReg);
13327   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13328
13329   // Calls into a routine in libgcc to allocate more space from the heap.
13330   const uint32_t *RegMask =
13331     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13332   if (Is64Bit) {
13333     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13334       .addReg(sizeVReg);
13335     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13336       .addExternalSymbol("__morestack_allocate_stack_space")
13337       .addRegMask(RegMask)
13338       .addReg(X86::RDI, RegState::Implicit)
13339       .addReg(X86::RAX, RegState::ImplicitDefine);
13340   } else {
13341     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13342       .addImm(12);
13343     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13344     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13345       .addExternalSymbol("__morestack_allocate_stack_space")
13346       .addRegMask(RegMask)
13347       .addReg(X86::EAX, RegState::ImplicitDefine);
13348   }
13349
13350   if (!Is64Bit)
13351     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13352       .addImm(16);
13353
13354   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13355     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13356   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13357
13358   // Set up the CFG correctly.
13359   BB->addSuccessor(bumpMBB);
13360   BB->addSuccessor(mallocMBB);
13361   mallocMBB->addSuccessor(continueMBB);
13362   bumpMBB->addSuccessor(continueMBB);
13363
13364   // Take care of the PHI nodes.
13365   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13366           MI->getOperand(0).getReg())
13367     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13368     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13369
13370   // Delete the original pseudo instruction.
13371   MI->eraseFromParent();
13372
13373   // And we're done.
13374   return continueMBB;
13375 }
13376
13377 MachineBasicBlock *
13378 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13379                                           MachineBasicBlock *BB) const {
13380   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13381   DebugLoc DL = MI->getDebugLoc();
13382
13383   assert(!Subtarget->isTargetEnvMacho());
13384
13385   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13386   // non-trivial part is impdef of ESP.
13387
13388   if (Subtarget->isTargetWin64()) {
13389     if (Subtarget->isTargetCygMing()) {
13390       // ___chkstk(Mingw64):
13391       // Clobbers R10, R11, RAX and EFLAGS.
13392       // Updates RSP.
13393       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13394         .addExternalSymbol("___chkstk")
13395         .addReg(X86::RAX, RegState::Implicit)
13396         .addReg(X86::RSP, RegState::Implicit)
13397         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13398         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13399         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13400     } else {
13401       // __chkstk(MSVCRT): does not update stack pointer.
13402       // Clobbers R10, R11 and EFLAGS.
13403       // FIXME: RAX(allocated size) might be reused and not killed.
13404       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13405         .addExternalSymbol("__chkstk")
13406         .addReg(X86::RAX, RegState::Implicit)
13407         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13408       // RAX has the offset to subtracted from RSP.
13409       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13410         .addReg(X86::RSP)
13411         .addReg(X86::RAX);
13412     }
13413   } else {
13414     const char *StackProbeSymbol =
13415       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13416
13417     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13418       .addExternalSymbol(StackProbeSymbol)
13419       .addReg(X86::EAX, RegState::Implicit)
13420       .addReg(X86::ESP, RegState::Implicit)
13421       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13422       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13423       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13424   }
13425
13426   MI->eraseFromParent();   // The pseudo instruction is gone now.
13427   return BB;
13428 }
13429
13430 MachineBasicBlock *
13431 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13432                                       MachineBasicBlock *BB) const {
13433   // This is pretty easy.  We're taking the value that we received from
13434   // our load from the relocation, sticking it in either RDI (x86-64)
13435   // or EAX and doing an indirect call.  The return value will then
13436   // be in the normal return register.
13437   const X86InstrInfo *TII
13438     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13439   DebugLoc DL = MI->getDebugLoc();
13440   MachineFunction *F = BB->getParent();
13441
13442   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13443   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13444
13445   // Get a register mask for the lowered call.
13446   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13447   // proper register mask.
13448   const uint32_t *RegMask =
13449     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13450   if (Subtarget->is64Bit()) {
13451     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13452                                       TII->get(X86::MOV64rm), X86::RDI)
13453     .addReg(X86::RIP)
13454     .addImm(0).addReg(0)
13455     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13456                       MI->getOperand(3).getTargetFlags())
13457     .addReg(0);
13458     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13459     addDirectMem(MIB, X86::RDI);
13460     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13461   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13462     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13463                                       TII->get(X86::MOV32rm), X86::EAX)
13464     .addReg(0)
13465     .addImm(0).addReg(0)
13466     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13467                       MI->getOperand(3).getTargetFlags())
13468     .addReg(0);
13469     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13470     addDirectMem(MIB, X86::EAX);
13471     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13472   } else {
13473     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13474                                       TII->get(X86::MOV32rm), X86::EAX)
13475     .addReg(TII->getGlobalBaseReg(F))
13476     .addImm(0).addReg(0)
13477     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13478                       MI->getOperand(3).getTargetFlags())
13479     .addReg(0);
13480     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13481     addDirectMem(MIB, X86::EAX);
13482     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13483   }
13484
13485   MI->eraseFromParent(); // The pseudo instruction is gone now.
13486   return BB;
13487 }
13488
13489 MachineBasicBlock *
13490 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13491                                     MachineBasicBlock *MBB) const {
13492   DebugLoc DL = MI->getDebugLoc();
13493   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13494
13495   MachineFunction *MF = MBB->getParent();
13496   MachineRegisterInfo &MRI = MF->getRegInfo();
13497
13498   const BasicBlock *BB = MBB->getBasicBlock();
13499   MachineFunction::iterator I = MBB;
13500   ++I;
13501
13502   // Memory Reference
13503   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13504   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13505
13506   unsigned DstReg;
13507   unsigned MemOpndSlot = 0;
13508
13509   unsigned CurOp = 0;
13510
13511   DstReg = MI->getOperand(CurOp++).getReg();
13512   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13513   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13514   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13515   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13516
13517   MemOpndSlot = CurOp;
13518
13519   MVT PVT = getPointerTy();
13520   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13521          "Invalid Pointer Size!");
13522
13523   // For v = setjmp(buf), we generate
13524   //
13525   // thisMBB:
13526   //  buf[LabelOffset] = restoreMBB
13527   //  SjLjSetup restoreMBB
13528   //
13529   // mainMBB:
13530   //  v_main = 0
13531   //
13532   // sinkMBB:
13533   //  v = phi(main, restore)
13534   //
13535   // restoreMBB:
13536   //  v_restore = 1
13537
13538   MachineBasicBlock *thisMBB = MBB;
13539   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13540   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13541   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13542   MF->insert(I, mainMBB);
13543   MF->insert(I, sinkMBB);
13544   MF->push_back(restoreMBB);
13545
13546   MachineInstrBuilder MIB;
13547
13548   // Transfer the remainder of BB and its successor edges to sinkMBB.
13549   sinkMBB->splice(sinkMBB->begin(), MBB,
13550                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13551   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13552
13553   // thisMBB:
13554   unsigned PtrStoreOpc = 0;
13555   unsigned LabelReg = 0;
13556   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13557   Reloc::Model RM = getTargetMachine().getRelocationModel();
13558   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13559                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13560
13561   // Prepare IP either in reg or imm.
13562   if (!UseImmLabel) {
13563     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13564     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13565     LabelReg = MRI.createVirtualRegister(PtrRC);
13566     if (Subtarget->is64Bit()) {
13567       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13568               .addReg(X86::RIP)
13569               .addImm(0)
13570               .addReg(0)
13571               .addMBB(restoreMBB)
13572               .addReg(0);
13573     } else {
13574       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13575       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13576               .addReg(XII->getGlobalBaseReg(MF))
13577               .addImm(0)
13578               .addReg(0)
13579               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13580               .addReg(0);
13581     }
13582   } else
13583     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13584   // Store IP
13585   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13586   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13587     if (i == X86::AddrDisp)
13588       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13589     else
13590       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13591   }
13592   if (!UseImmLabel)
13593     MIB.addReg(LabelReg);
13594   else
13595     MIB.addMBB(restoreMBB);
13596   MIB.setMemRefs(MMOBegin, MMOEnd);
13597   // Setup
13598   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13599           .addMBB(restoreMBB);
13600   MIB.addRegMask(RegInfo->getNoPreservedMask());
13601   thisMBB->addSuccessor(mainMBB);
13602   thisMBB->addSuccessor(restoreMBB);
13603
13604   // mainMBB:
13605   //  EAX = 0
13606   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13607   mainMBB->addSuccessor(sinkMBB);
13608
13609   // sinkMBB:
13610   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13611           TII->get(X86::PHI), DstReg)
13612     .addReg(mainDstReg).addMBB(mainMBB)
13613     .addReg(restoreDstReg).addMBB(restoreMBB);
13614
13615   // restoreMBB:
13616   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13617   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13618   restoreMBB->addSuccessor(sinkMBB);
13619
13620   MI->eraseFromParent();
13621   return sinkMBB;
13622 }
13623
13624 MachineBasicBlock *
13625 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13626                                      MachineBasicBlock *MBB) const {
13627   DebugLoc DL = MI->getDebugLoc();
13628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13629
13630   MachineFunction *MF = MBB->getParent();
13631   MachineRegisterInfo &MRI = MF->getRegInfo();
13632
13633   // Memory Reference
13634   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13635   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13636
13637   MVT PVT = getPointerTy();
13638   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13639          "Invalid Pointer Size!");
13640
13641   const TargetRegisterClass *RC =
13642     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13643   unsigned Tmp = MRI.createVirtualRegister(RC);
13644   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13645   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13646   unsigned SP = RegInfo->getStackRegister();
13647
13648   MachineInstrBuilder MIB;
13649
13650   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13651   const int64_t SPOffset = 2 * PVT.getStoreSize();
13652
13653   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13654   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13655
13656   // Reload FP
13657   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13658   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13659     MIB.addOperand(MI->getOperand(i));
13660   MIB.setMemRefs(MMOBegin, MMOEnd);
13661   // Reload IP
13662   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13663   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13664     if (i == X86::AddrDisp)
13665       MIB.addDisp(MI->getOperand(i), LabelOffset);
13666     else
13667       MIB.addOperand(MI->getOperand(i));
13668   }
13669   MIB.setMemRefs(MMOBegin, MMOEnd);
13670   // Reload SP
13671   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13672   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13673     if (i == X86::AddrDisp)
13674       MIB.addDisp(MI->getOperand(i), SPOffset);
13675     else
13676       MIB.addOperand(MI->getOperand(i));
13677   }
13678   MIB.setMemRefs(MMOBegin, MMOEnd);
13679   // Jump
13680   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13681
13682   MI->eraseFromParent();
13683   return MBB;
13684 }
13685
13686 MachineBasicBlock *
13687 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13688                                                MachineBasicBlock *BB) const {
13689   switch (MI->getOpcode()) {
13690   default: llvm_unreachable("Unexpected instr type to insert");
13691   case X86::TAILJMPd64:
13692   case X86::TAILJMPr64:
13693   case X86::TAILJMPm64:
13694     llvm_unreachable("TAILJMP64 would not be touched here.");
13695   case X86::TCRETURNdi64:
13696   case X86::TCRETURNri64:
13697   case X86::TCRETURNmi64:
13698     return BB;
13699   case X86::WIN_ALLOCA:
13700     return EmitLoweredWinAlloca(MI, BB);
13701   case X86::SEG_ALLOCA_32:
13702     return EmitLoweredSegAlloca(MI, BB, false);
13703   case X86::SEG_ALLOCA_64:
13704     return EmitLoweredSegAlloca(MI, BB, true);
13705   case X86::TLSCall_32:
13706   case X86::TLSCall_64:
13707     return EmitLoweredTLSCall(MI, BB);
13708   case X86::CMOV_GR8:
13709   case X86::CMOV_FR32:
13710   case X86::CMOV_FR64:
13711   case X86::CMOV_V4F32:
13712   case X86::CMOV_V2F64:
13713   case X86::CMOV_V2I64:
13714   case X86::CMOV_V8F32:
13715   case X86::CMOV_V4F64:
13716   case X86::CMOV_V4I64:
13717   case X86::CMOV_GR16:
13718   case X86::CMOV_GR32:
13719   case X86::CMOV_RFP32:
13720   case X86::CMOV_RFP64:
13721   case X86::CMOV_RFP80:
13722     return EmitLoweredSelect(MI, BB);
13723
13724   case X86::FP32_TO_INT16_IN_MEM:
13725   case X86::FP32_TO_INT32_IN_MEM:
13726   case X86::FP32_TO_INT64_IN_MEM:
13727   case X86::FP64_TO_INT16_IN_MEM:
13728   case X86::FP64_TO_INT32_IN_MEM:
13729   case X86::FP64_TO_INT64_IN_MEM:
13730   case X86::FP80_TO_INT16_IN_MEM:
13731   case X86::FP80_TO_INT32_IN_MEM:
13732   case X86::FP80_TO_INT64_IN_MEM: {
13733     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13734     DebugLoc DL = MI->getDebugLoc();
13735
13736     // Change the floating point control register to use "round towards zero"
13737     // mode when truncating to an integer value.
13738     MachineFunction *F = BB->getParent();
13739     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13740     addFrameReference(BuildMI(*BB, MI, DL,
13741                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13742
13743     // Load the old value of the high byte of the control word...
13744     unsigned OldCW =
13745       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13746     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13747                       CWFrameIdx);
13748
13749     // Set the high part to be round to zero...
13750     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13751       .addImm(0xC7F);
13752
13753     // Reload the modified control word now...
13754     addFrameReference(BuildMI(*BB, MI, DL,
13755                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13756
13757     // Restore the memory image of control word to original value
13758     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13759       .addReg(OldCW);
13760
13761     // Get the X86 opcode to use.
13762     unsigned Opc;
13763     switch (MI->getOpcode()) {
13764     default: llvm_unreachable("illegal opcode!");
13765     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13766     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13767     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13768     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13769     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13770     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13771     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13772     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13773     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13774     }
13775
13776     X86AddressMode AM;
13777     MachineOperand &Op = MI->getOperand(0);
13778     if (Op.isReg()) {
13779       AM.BaseType = X86AddressMode::RegBase;
13780       AM.Base.Reg = Op.getReg();
13781     } else {
13782       AM.BaseType = X86AddressMode::FrameIndexBase;
13783       AM.Base.FrameIndex = Op.getIndex();
13784     }
13785     Op = MI->getOperand(1);
13786     if (Op.isImm())
13787       AM.Scale = Op.getImm();
13788     Op = MI->getOperand(2);
13789     if (Op.isImm())
13790       AM.IndexReg = Op.getImm();
13791     Op = MI->getOperand(3);
13792     if (Op.isGlobal()) {
13793       AM.GV = Op.getGlobal();
13794     } else {
13795       AM.Disp = Op.getImm();
13796     }
13797     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13798                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13799
13800     // Reload the original control word now.
13801     addFrameReference(BuildMI(*BB, MI, DL,
13802                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13803
13804     MI->eraseFromParent();   // The pseudo instruction is gone now.
13805     return BB;
13806   }
13807     // String/text processing lowering.
13808   case X86::PCMPISTRM128REG:
13809   case X86::VPCMPISTRM128REG:
13810   case X86::PCMPISTRM128MEM:
13811   case X86::VPCMPISTRM128MEM:
13812   case X86::PCMPESTRM128REG:
13813   case X86::VPCMPESTRM128REG:
13814   case X86::PCMPESTRM128MEM:
13815   case X86::VPCMPESTRM128MEM: {
13816     unsigned NumArgs;
13817     bool MemArg;
13818     switch (MI->getOpcode()) {
13819     default: llvm_unreachable("illegal opcode!");
13820     case X86::PCMPISTRM128REG:
13821     case X86::VPCMPISTRM128REG:
13822       NumArgs = 3; MemArg = false; break;
13823     case X86::PCMPISTRM128MEM:
13824     case X86::VPCMPISTRM128MEM:
13825       NumArgs = 3; MemArg = true; break;
13826     case X86::PCMPESTRM128REG:
13827     case X86::VPCMPESTRM128REG:
13828       NumArgs = 5; MemArg = false; break;
13829     case X86::PCMPESTRM128MEM:
13830     case X86::VPCMPESTRM128MEM:
13831       NumArgs = 5; MemArg = true; break;
13832     }
13833     return EmitPCMP(MI, BB, NumArgs, MemArg);
13834   }
13835
13836     // Thread synchronization.
13837   case X86::MONITOR:
13838     return EmitMonitor(MI, BB);
13839
13840     // Atomic Lowering.
13841   case X86::ATOMAND8:
13842   case X86::ATOMAND16:
13843   case X86::ATOMAND32:
13844   case X86::ATOMAND64:
13845     // Fall through
13846   case X86::ATOMOR8:
13847   case X86::ATOMOR16:
13848   case X86::ATOMOR32:
13849   case X86::ATOMOR64:
13850     // Fall through
13851   case X86::ATOMXOR16:
13852   case X86::ATOMXOR8:
13853   case X86::ATOMXOR32:
13854   case X86::ATOMXOR64:
13855     // Fall through
13856   case X86::ATOMNAND8:
13857   case X86::ATOMNAND16:
13858   case X86::ATOMNAND32:
13859   case X86::ATOMNAND64:
13860     // Fall through
13861   case X86::ATOMMAX8:
13862   case X86::ATOMMAX16:
13863   case X86::ATOMMAX32:
13864   case X86::ATOMMAX64:
13865     // Fall through
13866   case X86::ATOMMIN8:
13867   case X86::ATOMMIN16:
13868   case X86::ATOMMIN32:
13869   case X86::ATOMMIN64:
13870     // Fall through
13871   case X86::ATOMUMAX8:
13872   case X86::ATOMUMAX16:
13873   case X86::ATOMUMAX32:
13874   case X86::ATOMUMAX64:
13875     // Fall through
13876   case X86::ATOMUMIN8:
13877   case X86::ATOMUMIN16:
13878   case X86::ATOMUMIN32:
13879   case X86::ATOMUMIN64:
13880     return EmitAtomicLoadArith(MI, BB);
13881
13882   // This group does 64-bit operations on a 32-bit host.
13883   case X86::ATOMAND6432:
13884   case X86::ATOMOR6432:
13885   case X86::ATOMXOR6432:
13886   case X86::ATOMNAND6432:
13887   case X86::ATOMADD6432:
13888   case X86::ATOMSUB6432:
13889   case X86::ATOMMAX6432:
13890   case X86::ATOMMIN6432:
13891   case X86::ATOMUMAX6432:
13892   case X86::ATOMUMIN6432:
13893   case X86::ATOMSWAP6432:
13894     return EmitAtomicLoadArith6432(MI, BB);
13895
13896   case X86::VASTART_SAVE_XMM_REGS:
13897     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13898
13899   case X86::VAARG_64:
13900     return EmitVAARG64WithCustomInserter(MI, BB);
13901
13902   case X86::EH_SjLj_SetJmp32:
13903   case X86::EH_SjLj_SetJmp64:
13904     return emitEHSjLjSetJmp(MI, BB);
13905
13906   case X86::EH_SjLj_LongJmp32:
13907   case X86::EH_SjLj_LongJmp64:
13908     return emitEHSjLjLongJmp(MI, BB);
13909   }
13910 }
13911
13912 //===----------------------------------------------------------------------===//
13913 //                           X86 Optimization Hooks
13914 //===----------------------------------------------------------------------===//
13915
13916 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13917                                                        APInt &KnownZero,
13918                                                        APInt &KnownOne,
13919                                                        const SelectionDAG &DAG,
13920                                                        unsigned Depth) const {
13921   unsigned BitWidth = KnownZero.getBitWidth();
13922   unsigned Opc = Op.getOpcode();
13923   assert((Opc >= ISD::BUILTIN_OP_END ||
13924           Opc == ISD::INTRINSIC_WO_CHAIN ||
13925           Opc == ISD::INTRINSIC_W_CHAIN ||
13926           Opc == ISD::INTRINSIC_VOID) &&
13927          "Should use MaskedValueIsZero if you don't know whether Op"
13928          " is a target node!");
13929
13930   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13931   switch (Opc) {
13932   default: break;
13933   case X86ISD::ADD:
13934   case X86ISD::SUB:
13935   case X86ISD::ADC:
13936   case X86ISD::SBB:
13937   case X86ISD::SMUL:
13938   case X86ISD::UMUL:
13939   case X86ISD::INC:
13940   case X86ISD::DEC:
13941   case X86ISD::OR:
13942   case X86ISD::XOR:
13943   case X86ISD::AND:
13944     // These nodes' second result is a boolean.
13945     if (Op.getResNo() == 0)
13946       break;
13947     // Fallthrough
13948   case X86ISD::SETCC:
13949     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13950     break;
13951   case ISD::INTRINSIC_WO_CHAIN: {
13952     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13953     unsigned NumLoBits = 0;
13954     switch (IntId) {
13955     default: break;
13956     case Intrinsic::x86_sse_movmsk_ps:
13957     case Intrinsic::x86_avx_movmsk_ps_256:
13958     case Intrinsic::x86_sse2_movmsk_pd:
13959     case Intrinsic::x86_avx_movmsk_pd_256:
13960     case Intrinsic::x86_mmx_pmovmskb:
13961     case Intrinsic::x86_sse2_pmovmskb_128:
13962     case Intrinsic::x86_avx2_pmovmskb: {
13963       // High bits of movmskp{s|d}, pmovmskb are known zero.
13964       switch (IntId) {
13965         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13966         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13967         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13968         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13969         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13970         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13971         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13972         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13973       }
13974       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13975       break;
13976     }
13977     }
13978     break;
13979   }
13980   }
13981 }
13982
13983 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13984                                                          unsigned Depth) const {
13985   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13986   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13987     return Op.getValueType().getScalarType().getSizeInBits();
13988
13989   // Fallback case.
13990   return 1;
13991 }
13992
13993 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13994 /// node is a GlobalAddress + offset.
13995 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13996                                        const GlobalValue* &GA,
13997                                        int64_t &Offset) const {
13998   if (N->getOpcode() == X86ISD::Wrapper) {
13999     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14000       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14001       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14002       return true;
14003     }
14004   }
14005   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14006 }
14007
14008 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14009 /// same as extracting the high 128-bit part of 256-bit vector and then
14010 /// inserting the result into the low part of a new 256-bit vector
14011 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14012   EVT VT = SVOp->getValueType(0);
14013   unsigned NumElems = VT.getVectorNumElements();
14014
14015   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14016   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14017     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14018         SVOp->getMaskElt(j) >= 0)
14019       return false;
14020
14021   return true;
14022 }
14023
14024 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14025 /// same as extracting the low 128-bit part of 256-bit vector and then
14026 /// inserting the result into the high part of a new 256-bit vector
14027 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14028   EVT VT = SVOp->getValueType(0);
14029   unsigned NumElems = VT.getVectorNumElements();
14030
14031   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14032   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14033     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14034         SVOp->getMaskElt(j) >= 0)
14035       return false;
14036
14037   return true;
14038 }
14039
14040 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14041 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14042                                         TargetLowering::DAGCombinerInfo &DCI,
14043                                         const X86Subtarget* Subtarget) {
14044   DebugLoc dl = N->getDebugLoc();
14045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14046   SDValue V1 = SVOp->getOperand(0);
14047   SDValue V2 = SVOp->getOperand(1);
14048   EVT VT = SVOp->getValueType(0);
14049   unsigned NumElems = VT.getVectorNumElements();
14050
14051   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14052       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14053     //
14054     //                   0,0,0,...
14055     //                      |
14056     //    V      UNDEF    BUILD_VECTOR    UNDEF
14057     //     \      /           \           /
14058     //  CONCAT_VECTOR         CONCAT_VECTOR
14059     //         \                  /
14060     //          \                /
14061     //          RESULT: V + zero extended
14062     //
14063     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14064         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14065         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14066       return SDValue();
14067
14068     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14069       return SDValue();
14070
14071     // To match the shuffle mask, the first half of the mask should
14072     // be exactly the first vector, and all the rest a splat with the
14073     // first element of the second one.
14074     for (unsigned i = 0; i != NumElems/2; ++i)
14075       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14076           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14077         return SDValue();
14078
14079     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14080     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14081       if (Ld->hasNUsesOfValue(1, 0)) {
14082         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14083         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14084         SDValue ResNode =
14085           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14086                                   Ld->getMemoryVT(),
14087                                   Ld->getPointerInfo(),
14088                                   Ld->getAlignment(),
14089                                   false/*isVolatile*/, true/*ReadMem*/,
14090                                   false/*WriteMem*/);
14091         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14092       }
14093     }
14094
14095     // Emit a zeroed vector and insert the desired subvector on its
14096     // first half.
14097     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14098     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14099     return DCI.CombineTo(N, InsV);
14100   }
14101
14102   //===--------------------------------------------------------------------===//
14103   // Combine some shuffles into subvector extracts and inserts:
14104   //
14105
14106   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14107   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14108     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14109     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14110     return DCI.CombineTo(N, InsV);
14111   }
14112
14113   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14114   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14115     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14116     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14117     return DCI.CombineTo(N, InsV);
14118   }
14119
14120   return SDValue();
14121 }
14122
14123 /// PerformShuffleCombine - Performs several different shuffle combines.
14124 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14125                                      TargetLowering::DAGCombinerInfo &DCI,
14126                                      const X86Subtarget *Subtarget) {
14127   DebugLoc dl = N->getDebugLoc();
14128   EVT VT = N->getValueType(0);
14129
14130   // Don't create instructions with illegal types after legalize types has run.
14131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14132   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14133     return SDValue();
14134
14135   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14136   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14137       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14138     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14139
14140   // Only handle 128 wide vector from here on.
14141   if (!VT.is128BitVector())
14142     return SDValue();
14143
14144   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14145   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14146   // consecutive, non-overlapping, and in the right order.
14147   SmallVector<SDValue, 16> Elts;
14148   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14149     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14150
14151   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14152 }
14153
14154
14155 /// PerformTruncateCombine - Converts truncate operation to
14156 /// a sequence of vector shuffle operations.
14157 /// It is possible when we truncate 256-bit vector to 128-bit vector
14158 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14159                                       TargetLowering::DAGCombinerInfo &DCI,
14160                                       const X86Subtarget *Subtarget)  {
14161   if (!DCI.isBeforeLegalizeOps())
14162     return SDValue();
14163
14164   if (!Subtarget->hasAVX())
14165     return SDValue();
14166
14167   EVT VT = N->getValueType(0);
14168   SDValue Op = N->getOperand(0);
14169   EVT OpVT = Op.getValueType();
14170   DebugLoc dl = N->getDebugLoc();
14171
14172   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14173
14174     if (Subtarget->hasAVX2()) {
14175       // AVX2: v4i64 -> v4i32
14176
14177       // VPERMD
14178       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14179
14180       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14181       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14182                                 ShufMask);
14183
14184       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14185                          DAG.getIntPtrConstant(0));
14186     }
14187
14188     // AVX: v4i64 -> v4i32
14189     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14190                                DAG.getIntPtrConstant(0));
14191
14192     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14193                                DAG.getIntPtrConstant(2));
14194
14195     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14196     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14197
14198     // PSHUFD
14199     static const int ShufMask1[] = {0, 2, 0, 0};
14200
14201     SDValue Undef = DAG.getUNDEF(VT);
14202     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14203     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14204
14205     // MOVLHPS
14206     static const int ShufMask2[] = {0, 1, 4, 5};
14207
14208     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14209   }
14210
14211   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14212
14213     if (Subtarget->hasAVX2()) {
14214       // AVX2: v8i32 -> v8i16
14215
14216       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14217
14218       // PSHUFB
14219       SmallVector<SDValue,32> pshufbMask;
14220       for (unsigned i = 0; i < 2; ++i) {
14221         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14222         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14223         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14224         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14225         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14226         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14227         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14228         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14229         for (unsigned j = 0; j < 8; ++j)
14230           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14231       }
14232       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14233                                &pshufbMask[0], 32);
14234       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14235
14236       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14237
14238       static const int ShufMask[] = {0,  2,  -1,  -1};
14239       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14240                                 &ShufMask[0]);
14241
14242       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14243                        DAG.getIntPtrConstant(0));
14244
14245       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14246     }
14247
14248     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14249                                DAG.getIntPtrConstant(0));
14250
14251     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14252                                DAG.getIntPtrConstant(4));
14253
14254     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14255     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14256
14257     // PSHUFB
14258     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14259                                    -1, -1, -1, -1, -1, -1, -1, -1};
14260
14261     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14262     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14263     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14264
14265     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14266     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14267
14268     // MOVLHPS
14269     static const int ShufMask2[] = {0, 1, 4, 5};
14270
14271     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14272     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14273   }
14274
14275   return SDValue();
14276 }
14277
14278 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14279 /// specific shuffle of a load can be folded into a single element load.
14280 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14281 /// shuffles have been customed lowered so we need to handle those here.
14282 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14283                                          TargetLowering::DAGCombinerInfo &DCI) {
14284   if (DCI.isBeforeLegalizeOps())
14285     return SDValue();
14286
14287   SDValue InVec = N->getOperand(0);
14288   SDValue EltNo = N->getOperand(1);
14289
14290   if (!isa<ConstantSDNode>(EltNo))
14291     return SDValue();
14292
14293   EVT VT = InVec.getValueType();
14294
14295   bool HasShuffleIntoBitcast = false;
14296   if (InVec.getOpcode() == ISD::BITCAST) {
14297     // Don't duplicate a load with other uses.
14298     if (!InVec.hasOneUse())
14299       return SDValue();
14300     EVT BCVT = InVec.getOperand(0).getValueType();
14301     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14302       return SDValue();
14303     InVec = InVec.getOperand(0);
14304     HasShuffleIntoBitcast = true;
14305   }
14306
14307   if (!isTargetShuffle(InVec.getOpcode()))
14308     return SDValue();
14309
14310   // Don't duplicate a load with other uses.
14311   if (!InVec.hasOneUse())
14312     return SDValue();
14313
14314   SmallVector<int, 16> ShuffleMask;
14315   bool UnaryShuffle;
14316   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14317                             UnaryShuffle))
14318     return SDValue();
14319
14320   // Select the input vector, guarding against out of range extract vector.
14321   unsigned NumElems = VT.getVectorNumElements();
14322   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14323   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14324   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14325                                          : InVec.getOperand(1);
14326
14327   // If inputs to shuffle are the same for both ops, then allow 2 uses
14328   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14329
14330   if (LdNode.getOpcode() == ISD::BITCAST) {
14331     // Don't duplicate a load with other uses.
14332     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14333       return SDValue();
14334
14335     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14336     LdNode = LdNode.getOperand(0);
14337   }
14338
14339   if (!ISD::isNormalLoad(LdNode.getNode()))
14340     return SDValue();
14341
14342   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14343
14344   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14345     return SDValue();
14346
14347   if (HasShuffleIntoBitcast) {
14348     // If there's a bitcast before the shuffle, check if the load type and
14349     // alignment is valid.
14350     unsigned Align = LN0->getAlignment();
14351     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14352     unsigned NewAlign = TLI.getDataLayout()->
14353       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14354
14355     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14356       return SDValue();
14357   }
14358
14359   // All checks match so transform back to vector_shuffle so that DAG combiner
14360   // can finish the job
14361   DebugLoc dl = N->getDebugLoc();
14362
14363   // Create shuffle node taking into account the case that its a unary shuffle
14364   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14365   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14366                                  InVec.getOperand(0), Shuffle,
14367                                  &ShuffleMask[0]);
14368   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14369   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14370                      EltNo);
14371 }
14372
14373 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14374 /// generation and convert it from being a bunch of shuffles and extracts
14375 /// to a simple store and scalar loads to extract the elements.
14376 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14377                                          TargetLowering::DAGCombinerInfo &DCI) {
14378   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14379   if (NewOp.getNode())
14380     return NewOp;
14381
14382   SDValue InputVector = N->getOperand(0);
14383
14384   // Only operate on vectors of 4 elements, where the alternative shuffling
14385   // gets to be more expensive.
14386   if (InputVector.getValueType() != MVT::v4i32)
14387     return SDValue();
14388
14389   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14390   // single use which is a sign-extend or zero-extend, and all elements are
14391   // used.
14392   SmallVector<SDNode *, 4> Uses;
14393   unsigned ExtractedElements = 0;
14394   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14395        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14396     if (UI.getUse().getResNo() != InputVector.getResNo())
14397       return SDValue();
14398
14399     SDNode *Extract = *UI;
14400     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14401       return SDValue();
14402
14403     if (Extract->getValueType(0) != MVT::i32)
14404       return SDValue();
14405     if (!Extract->hasOneUse())
14406       return SDValue();
14407     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14408         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14409       return SDValue();
14410     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14411       return SDValue();
14412
14413     // Record which element was extracted.
14414     ExtractedElements |=
14415       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14416
14417     Uses.push_back(Extract);
14418   }
14419
14420   // If not all the elements were used, this may not be worthwhile.
14421   if (ExtractedElements != 15)
14422     return SDValue();
14423
14424   // Ok, we've now decided to do the transformation.
14425   DebugLoc dl = InputVector.getDebugLoc();
14426
14427   // Store the value to a temporary stack slot.
14428   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14429   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14430                             MachinePointerInfo(), false, false, 0);
14431
14432   // Replace each use (extract) with a load of the appropriate element.
14433   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14434        UE = Uses.end(); UI != UE; ++UI) {
14435     SDNode *Extract = *UI;
14436
14437     // cOMpute the element's address.
14438     SDValue Idx = Extract->getOperand(1);
14439     unsigned EltSize =
14440         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14441     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14442     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14443     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14444
14445     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14446                                      StackPtr, OffsetVal);
14447
14448     // Load the scalar.
14449     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14450                                      ScalarAddr, MachinePointerInfo(),
14451                                      false, false, false, 0);
14452
14453     // Replace the exact with the load.
14454     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14455   }
14456
14457   // The replacement was made in place; don't return anything.
14458   return SDValue();
14459 }
14460
14461 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14462 /// nodes.
14463 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14464                                     TargetLowering::DAGCombinerInfo &DCI,
14465                                     const X86Subtarget *Subtarget) {
14466   DebugLoc DL = N->getDebugLoc();
14467   SDValue Cond = N->getOperand(0);
14468   // Get the LHS/RHS of the select.
14469   SDValue LHS = N->getOperand(1);
14470   SDValue RHS = N->getOperand(2);
14471   EVT VT = LHS.getValueType();
14472
14473   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14474   // instructions match the semantics of the common C idiom x<y?x:y but not
14475   // x<=y?x:y, because of how they handle negative zero (which can be
14476   // ignored in unsafe-math mode).
14477   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14478       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14479       (Subtarget->hasSSE2() ||
14480        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14481     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14482
14483     unsigned Opcode = 0;
14484     // Check for x CC y ? x : y.
14485     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14486         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14487       switch (CC) {
14488       default: break;
14489       case ISD::SETULT:
14490         // Converting this to a min would handle NaNs incorrectly, and swapping
14491         // the operands would cause it to handle comparisons between positive
14492         // and negative zero incorrectly.
14493         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14494           if (!DAG.getTarget().Options.UnsafeFPMath &&
14495               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14496             break;
14497           std::swap(LHS, RHS);
14498         }
14499         Opcode = X86ISD::FMIN;
14500         break;
14501       case ISD::SETOLE:
14502         // Converting this to a min would handle comparisons between positive
14503         // and negative zero incorrectly.
14504         if (!DAG.getTarget().Options.UnsafeFPMath &&
14505             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14506           break;
14507         Opcode = X86ISD::FMIN;
14508         break;
14509       case ISD::SETULE:
14510         // Converting this to a min would handle both negative zeros and NaNs
14511         // incorrectly, but we can swap the operands to fix both.
14512         std::swap(LHS, RHS);
14513       case ISD::SETOLT:
14514       case ISD::SETLT:
14515       case ISD::SETLE:
14516         Opcode = X86ISD::FMIN;
14517         break;
14518
14519       case ISD::SETOGE:
14520         // Converting this to a max would handle comparisons between positive
14521         // and negative zero incorrectly.
14522         if (!DAG.getTarget().Options.UnsafeFPMath &&
14523             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14524           break;
14525         Opcode = X86ISD::FMAX;
14526         break;
14527       case ISD::SETUGT:
14528         // Converting this to a max would handle NaNs incorrectly, and swapping
14529         // the operands would cause it to handle comparisons between positive
14530         // and negative zero incorrectly.
14531         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14532           if (!DAG.getTarget().Options.UnsafeFPMath &&
14533               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14534             break;
14535           std::swap(LHS, RHS);
14536         }
14537         Opcode = X86ISD::FMAX;
14538         break;
14539       case ISD::SETUGE:
14540         // Converting this to a max would handle both negative zeros and NaNs
14541         // incorrectly, but we can swap the operands to fix both.
14542         std::swap(LHS, RHS);
14543       case ISD::SETOGT:
14544       case ISD::SETGT:
14545       case ISD::SETGE:
14546         Opcode = X86ISD::FMAX;
14547         break;
14548       }
14549     // Check for x CC y ? y : x -- a min/max with reversed arms.
14550     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14551                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14552       switch (CC) {
14553       default: break;
14554       case ISD::SETOGE:
14555         // Converting this to a min would handle comparisons between positive
14556         // and negative zero incorrectly, and swapping the operands would
14557         // cause it to handle NaNs incorrectly.
14558         if (!DAG.getTarget().Options.UnsafeFPMath &&
14559             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14560           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14561             break;
14562           std::swap(LHS, RHS);
14563         }
14564         Opcode = X86ISD::FMIN;
14565         break;
14566       case ISD::SETUGT:
14567         // Converting this to a min would handle NaNs incorrectly.
14568         if (!DAG.getTarget().Options.UnsafeFPMath &&
14569             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14570           break;
14571         Opcode = X86ISD::FMIN;
14572         break;
14573       case ISD::SETUGE:
14574         // Converting this to a min would handle both negative zeros and NaNs
14575         // incorrectly, but we can swap the operands to fix both.
14576         std::swap(LHS, RHS);
14577       case ISD::SETOGT:
14578       case ISD::SETGT:
14579       case ISD::SETGE:
14580         Opcode = X86ISD::FMIN;
14581         break;
14582
14583       case ISD::SETULT:
14584         // Converting this to a max would handle NaNs incorrectly.
14585         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14586           break;
14587         Opcode = X86ISD::FMAX;
14588         break;
14589       case ISD::SETOLE:
14590         // Converting this to a max would handle comparisons between positive
14591         // and negative zero incorrectly, and swapping the operands would
14592         // cause it to handle NaNs incorrectly.
14593         if (!DAG.getTarget().Options.UnsafeFPMath &&
14594             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14595           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14596             break;
14597           std::swap(LHS, RHS);
14598         }
14599         Opcode = X86ISD::FMAX;
14600         break;
14601       case ISD::SETULE:
14602         // Converting this to a max would handle both negative zeros and NaNs
14603         // incorrectly, but we can swap the operands to fix both.
14604         std::swap(LHS, RHS);
14605       case ISD::SETOLT:
14606       case ISD::SETLT:
14607       case ISD::SETLE:
14608         Opcode = X86ISD::FMAX;
14609         break;
14610       }
14611     }
14612
14613     if (Opcode)
14614       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14615   }
14616
14617   // If this is a select between two integer constants, try to do some
14618   // optimizations.
14619   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14620     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14621       // Don't do this for crazy integer types.
14622       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14623         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14624         // so that TrueC (the true value) is larger than FalseC.
14625         bool NeedsCondInvert = false;
14626
14627         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14628             // Efficiently invertible.
14629             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14630              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14631               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14632           NeedsCondInvert = true;
14633           std::swap(TrueC, FalseC);
14634         }
14635
14636         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14637         if (FalseC->getAPIntValue() == 0 &&
14638             TrueC->getAPIntValue().isPowerOf2()) {
14639           if (NeedsCondInvert) // Invert the condition if needed.
14640             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14641                                DAG.getConstant(1, Cond.getValueType()));
14642
14643           // Zero extend the condition if needed.
14644           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14645
14646           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14647           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14648                              DAG.getConstant(ShAmt, MVT::i8));
14649         }
14650
14651         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14652         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14653           if (NeedsCondInvert) // Invert the condition if needed.
14654             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14655                                DAG.getConstant(1, Cond.getValueType()));
14656
14657           // Zero extend the condition if needed.
14658           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14659                              FalseC->getValueType(0), Cond);
14660           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14661                              SDValue(FalseC, 0));
14662         }
14663
14664         // Optimize cases that will turn into an LEA instruction.  This requires
14665         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14666         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14667           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14668           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14669
14670           bool isFastMultiplier = false;
14671           if (Diff < 10) {
14672             switch ((unsigned char)Diff) {
14673               default: break;
14674               case 1:  // result = add base, cond
14675               case 2:  // result = lea base(    , cond*2)
14676               case 3:  // result = lea base(cond, cond*2)
14677               case 4:  // result = lea base(    , cond*4)
14678               case 5:  // result = lea base(cond, cond*4)
14679               case 8:  // result = lea base(    , cond*8)
14680               case 9:  // result = lea base(cond, cond*8)
14681                 isFastMultiplier = true;
14682                 break;
14683             }
14684           }
14685
14686           if (isFastMultiplier) {
14687             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14688             if (NeedsCondInvert) // Invert the condition if needed.
14689               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14690                                  DAG.getConstant(1, Cond.getValueType()));
14691
14692             // Zero extend the condition if needed.
14693             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14694                                Cond);
14695             // Scale the condition by the difference.
14696             if (Diff != 1)
14697               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14698                                  DAG.getConstant(Diff, Cond.getValueType()));
14699
14700             // Add the base if non-zero.
14701             if (FalseC->getAPIntValue() != 0)
14702               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14703                                  SDValue(FalseC, 0));
14704             return Cond;
14705           }
14706         }
14707       }
14708   }
14709
14710   // Canonicalize max and min:
14711   // (x > y) ? x : y -> (x >= y) ? x : y
14712   // (x < y) ? x : y -> (x <= y) ? x : y
14713   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14714   // the need for an extra compare
14715   // against zero. e.g.
14716   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14717   // subl   %esi, %edi
14718   // testl  %edi, %edi
14719   // movl   $0, %eax
14720   // cmovgl %edi, %eax
14721   // =>
14722   // xorl   %eax, %eax
14723   // subl   %esi, $edi
14724   // cmovsl %eax, %edi
14725   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14726       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14727       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14728     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14729     switch (CC) {
14730     default: break;
14731     case ISD::SETLT:
14732     case ISD::SETGT: {
14733       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14734       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14735                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14736       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14737     }
14738     }
14739   }
14740
14741   // If we know that this node is legal then we know that it is going to be
14742   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14743   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14744   // to simplify previous instructions.
14745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14746   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14747       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14748     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14749
14750     // Don't optimize vector selects that map to mask-registers.
14751     if (BitWidth == 1)
14752       return SDValue();
14753
14754     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14755     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14756
14757     APInt KnownZero, KnownOne;
14758     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14759                                           DCI.isBeforeLegalizeOps());
14760     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14761         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14762       DCI.CommitTargetLoweringOpt(TLO);
14763   }
14764
14765   return SDValue();
14766 }
14767
14768 // Check whether a boolean test is testing a boolean value generated by
14769 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14770 // code.
14771 //
14772 // Simplify the following patterns:
14773 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14774 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14775 // to (Op EFLAGS Cond)
14776 //
14777 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14778 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14779 // to (Op EFLAGS !Cond)
14780 //
14781 // where Op could be BRCOND or CMOV.
14782 //
14783 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14784   // Quit if not CMP and SUB with its value result used.
14785   if (Cmp.getOpcode() != X86ISD::CMP &&
14786       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14787       return SDValue();
14788
14789   // Quit if not used as a boolean value.
14790   if (CC != X86::COND_E && CC != X86::COND_NE)
14791     return SDValue();
14792
14793   // Check CMP operands. One of them should be 0 or 1 and the other should be
14794   // an SetCC or extended from it.
14795   SDValue Op1 = Cmp.getOperand(0);
14796   SDValue Op2 = Cmp.getOperand(1);
14797
14798   SDValue SetCC;
14799   const ConstantSDNode* C = 0;
14800   bool needOppositeCond = (CC == X86::COND_E);
14801
14802   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14803     SetCC = Op2;
14804   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14805     SetCC = Op1;
14806   else // Quit if all operands are not constants.
14807     return SDValue();
14808
14809   if (C->getZExtValue() == 1)
14810     needOppositeCond = !needOppositeCond;
14811   else if (C->getZExtValue() != 0)
14812     // Quit if the constant is neither 0 or 1.
14813     return SDValue();
14814
14815   // Skip 'zext' node.
14816   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14817     SetCC = SetCC.getOperand(0);
14818
14819   switch (SetCC.getOpcode()) {
14820   case X86ISD::SETCC:
14821     // Set the condition code or opposite one if necessary.
14822     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14823     if (needOppositeCond)
14824       CC = X86::GetOppositeBranchCondition(CC);
14825     return SetCC.getOperand(1);
14826   case X86ISD::CMOV: {
14827     // Check whether false/true value has canonical one, i.e. 0 or 1.
14828     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14829     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14830     // Quit if true value is not a constant.
14831     if (!TVal)
14832       return SDValue();
14833     // Quit if false value is not a constant.
14834     if (!FVal) {
14835       // A special case for rdrand, where 0 is set if false cond is found.
14836       SDValue Op = SetCC.getOperand(0);
14837       if (Op.getOpcode() != X86ISD::RDRAND)
14838         return SDValue();
14839     }
14840     // Quit if false value is not the constant 0 or 1.
14841     bool FValIsFalse = true;
14842     if (FVal && FVal->getZExtValue() != 0) {
14843       if (FVal->getZExtValue() != 1)
14844         return SDValue();
14845       // If FVal is 1, opposite cond is needed.
14846       needOppositeCond = !needOppositeCond;
14847       FValIsFalse = false;
14848     }
14849     // Quit if TVal is not the constant opposite of FVal.
14850     if (FValIsFalse && TVal->getZExtValue() != 1)
14851       return SDValue();
14852     if (!FValIsFalse && TVal->getZExtValue() != 0)
14853       return SDValue();
14854     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14855     if (needOppositeCond)
14856       CC = X86::GetOppositeBranchCondition(CC);
14857     return SetCC.getOperand(3);
14858   }
14859   }
14860
14861   return SDValue();
14862 }
14863
14864 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14865 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14866                                   TargetLowering::DAGCombinerInfo &DCI,
14867                                   const X86Subtarget *Subtarget) {
14868   DebugLoc DL = N->getDebugLoc();
14869
14870   // If the flag operand isn't dead, don't touch this CMOV.
14871   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14872     return SDValue();
14873
14874   SDValue FalseOp = N->getOperand(0);
14875   SDValue TrueOp = N->getOperand(1);
14876   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14877   SDValue Cond = N->getOperand(3);
14878
14879   if (CC == X86::COND_E || CC == X86::COND_NE) {
14880     switch (Cond.getOpcode()) {
14881     default: break;
14882     case X86ISD::BSR:
14883     case X86ISD::BSF:
14884       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14885       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14886         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14887     }
14888   }
14889
14890   SDValue Flags;
14891
14892   Flags = checkBoolTestSetCCCombine(Cond, CC);
14893   if (Flags.getNode() &&
14894       // Extra check as FCMOV only supports a subset of X86 cond.
14895       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14896     SDValue Ops[] = { FalseOp, TrueOp,
14897                       DAG.getConstant(CC, MVT::i8), Flags };
14898     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14899                        Ops, array_lengthof(Ops));
14900   }
14901
14902   // If this is a select between two integer constants, try to do some
14903   // optimizations.  Note that the operands are ordered the opposite of SELECT
14904   // operands.
14905   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14906     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14907       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14908       // larger than FalseC (the false value).
14909       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14910         CC = X86::GetOppositeBranchCondition(CC);
14911         std::swap(TrueC, FalseC);
14912         std::swap(TrueOp, FalseOp);
14913       }
14914
14915       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14916       // This is efficient for any integer data type (including i8/i16) and
14917       // shift amount.
14918       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14919         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14920                            DAG.getConstant(CC, MVT::i8), Cond);
14921
14922         // Zero extend the condition if needed.
14923         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14924
14925         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14926         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14927                            DAG.getConstant(ShAmt, MVT::i8));
14928         if (N->getNumValues() == 2)  // Dead flag value?
14929           return DCI.CombineTo(N, Cond, SDValue());
14930         return Cond;
14931       }
14932
14933       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14934       // for any integer data type, including i8/i16.
14935       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14936         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14937                            DAG.getConstant(CC, MVT::i8), Cond);
14938
14939         // Zero extend the condition if needed.
14940         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14941                            FalseC->getValueType(0), Cond);
14942         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14943                            SDValue(FalseC, 0));
14944
14945         if (N->getNumValues() == 2)  // Dead flag value?
14946           return DCI.CombineTo(N, Cond, SDValue());
14947         return Cond;
14948       }
14949
14950       // Optimize cases that will turn into an LEA instruction.  This requires
14951       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14952       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14953         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14954         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14955
14956         bool isFastMultiplier = false;
14957         if (Diff < 10) {
14958           switch ((unsigned char)Diff) {
14959           default: break;
14960           case 1:  // result = add base, cond
14961           case 2:  // result = lea base(    , cond*2)
14962           case 3:  // result = lea base(cond, cond*2)
14963           case 4:  // result = lea base(    , cond*4)
14964           case 5:  // result = lea base(cond, cond*4)
14965           case 8:  // result = lea base(    , cond*8)
14966           case 9:  // result = lea base(cond, cond*8)
14967             isFastMultiplier = true;
14968             break;
14969           }
14970         }
14971
14972         if (isFastMultiplier) {
14973           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14974           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14975                              DAG.getConstant(CC, MVT::i8), Cond);
14976           // Zero extend the condition if needed.
14977           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14978                              Cond);
14979           // Scale the condition by the difference.
14980           if (Diff != 1)
14981             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14982                                DAG.getConstant(Diff, Cond.getValueType()));
14983
14984           // Add the base if non-zero.
14985           if (FalseC->getAPIntValue() != 0)
14986             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14987                                SDValue(FalseC, 0));
14988           if (N->getNumValues() == 2)  // Dead flag value?
14989             return DCI.CombineTo(N, Cond, SDValue());
14990           return Cond;
14991         }
14992       }
14993     }
14994   }
14995
14996   // Handle these cases:
14997   //   (select (x != c), e, c) -> select (x != c), e, x),
14998   //   (select (x == c), c, e) -> select (x == c), x, e)
14999   // where the c is an integer constant, and the "select" is the combination
15000   // of CMOV and CMP.
15001   //
15002   // The rationale for this change is that the conditional-move from a constant
15003   // needs two instructions, however, conditional-move from a register needs
15004   // only one instruction.
15005   //
15006   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15007   //  some instruction-combining opportunities. This opt needs to be
15008   //  postponed as late as possible.
15009   //
15010   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15011     // the DCI.xxxx conditions are provided to postpone the optimization as
15012     // late as possible.
15013
15014     ConstantSDNode *CmpAgainst = 0;
15015     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15016         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15017         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15018
15019       if (CC == X86::COND_NE &&
15020           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15021         CC = X86::GetOppositeBranchCondition(CC);
15022         std::swap(TrueOp, FalseOp);
15023       }
15024
15025       if (CC == X86::COND_E &&
15026           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15027         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15028                           DAG.getConstant(CC, MVT::i8), Cond };
15029         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15030                            array_lengthof(Ops));
15031       }
15032     }
15033   }
15034
15035   return SDValue();
15036 }
15037
15038
15039 /// PerformMulCombine - Optimize a single multiply with constant into two
15040 /// in order to implement it with two cheaper instructions, e.g.
15041 /// LEA + SHL, LEA + LEA.
15042 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15043                                  TargetLowering::DAGCombinerInfo &DCI) {
15044   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15045     return SDValue();
15046
15047   EVT VT = N->getValueType(0);
15048   if (VT != MVT::i64)
15049     return SDValue();
15050
15051   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15052   if (!C)
15053     return SDValue();
15054   uint64_t MulAmt = C->getZExtValue();
15055   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15056     return SDValue();
15057
15058   uint64_t MulAmt1 = 0;
15059   uint64_t MulAmt2 = 0;
15060   if ((MulAmt % 9) == 0) {
15061     MulAmt1 = 9;
15062     MulAmt2 = MulAmt / 9;
15063   } else if ((MulAmt % 5) == 0) {
15064     MulAmt1 = 5;
15065     MulAmt2 = MulAmt / 5;
15066   } else if ((MulAmt % 3) == 0) {
15067     MulAmt1 = 3;
15068     MulAmt2 = MulAmt / 3;
15069   }
15070   if (MulAmt2 &&
15071       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15072     DebugLoc DL = N->getDebugLoc();
15073
15074     if (isPowerOf2_64(MulAmt2) &&
15075         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15076       // If second multiplifer is pow2, issue it first. We want the multiply by
15077       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15078       // is an add.
15079       std::swap(MulAmt1, MulAmt2);
15080
15081     SDValue NewMul;
15082     if (isPowerOf2_64(MulAmt1))
15083       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15084                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15085     else
15086       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15087                            DAG.getConstant(MulAmt1, VT));
15088
15089     if (isPowerOf2_64(MulAmt2))
15090       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15091                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15092     else
15093       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15094                            DAG.getConstant(MulAmt2, VT));
15095
15096     // Do not add new nodes to DAG combiner worklist.
15097     DCI.CombineTo(N, NewMul, false);
15098   }
15099   return SDValue();
15100 }
15101
15102 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15103   SDValue N0 = N->getOperand(0);
15104   SDValue N1 = N->getOperand(1);
15105   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15106   EVT VT = N0.getValueType();
15107
15108   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15109   // since the result of setcc_c is all zero's or all ones.
15110   if (VT.isInteger() && !VT.isVector() &&
15111       N1C && N0.getOpcode() == ISD::AND &&
15112       N0.getOperand(1).getOpcode() == ISD::Constant) {
15113     SDValue N00 = N0.getOperand(0);
15114     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15115         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15116           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15117          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15118       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15119       APInt ShAmt = N1C->getAPIntValue();
15120       Mask = Mask.shl(ShAmt);
15121       if (Mask != 0)
15122         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15123                            N00, DAG.getConstant(Mask, VT));
15124     }
15125   }
15126
15127
15128   // Hardware support for vector shifts is sparse which makes us scalarize the
15129   // vector operations in many cases. Also, on sandybridge ADD is faster than
15130   // shl.
15131   // (shl V, 1) -> add V,V
15132   if (isSplatVector(N1.getNode())) {
15133     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15134     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15135     // We shift all of the values by one. In many cases we do not have
15136     // hardware support for this operation. This is better expressed as an ADD
15137     // of two values.
15138     if (N1C && (1 == N1C->getZExtValue())) {
15139       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15140     }
15141   }
15142
15143   return SDValue();
15144 }
15145
15146 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15147 ///                       when possible.
15148 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15149                                    TargetLowering::DAGCombinerInfo &DCI,
15150                                    const X86Subtarget *Subtarget) {
15151   EVT VT = N->getValueType(0);
15152   if (N->getOpcode() == ISD::SHL) {
15153     SDValue V = PerformSHLCombine(N, DAG);
15154     if (V.getNode()) return V;
15155   }
15156
15157   // On X86 with SSE2 support, we can transform this to a vector shift if
15158   // all elements are shifted by the same amount.  We can't do this in legalize
15159   // because the a constant vector is typically transformed to a constant pool
15160   // so we have no knowledge of the shift amount.
15161   if (!Subtarget->hasSSE2())
15162     return SDValue();
15163
15164   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15165       (!Subtarget->hasAVX2() ||
15166        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15167     return SDValue();
15168
15169   SDValue ShAmtOp = N->getOperand(1);
15170   EVT EltVT = VT.getVectorElementType();
15171   DebugLoc DL = N->getDebugLoc();
15172   SDValue BaseShAmt = SDValue();
15173   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15174     unsigned NumElts = VT.getVectorNumElements();
15175     unsigned i = 0;
15176     for (; i != NumElts; ++i) {
15177       SDValue Arg = ShAmtOp.getOperand(i);
15178       if (Arg.getOpcode() == ISD::UNDEF) continue;
15179       BaseShAmt = Arg;
15180       break;
15181     }
15182     // Handle the case where the build_vector is all undef
15183     // FIXME: Should DAG allow this?
15184     if (i == NumElts)
15185       return SDValue();
15186
15187     for (; i != NumElts; ++i) {
15188       SDValue Arg = ShAmtOp.getOperand(i);
15189       if (Arg.getOpcode() == ISD::UNDEF) continue;
15190       if (Arg != BaseShAmt) {
15191         return SDValue();
15192       }
15193     }
15194   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15195              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15196     SDValue InVec = ShAmtOp.getOperand(0);
15197     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15198       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15199       unsigned i = 0;
15200       for (; i != NumElts; ++i) {
15201         SDValue Arg = InVec.getOperand(i);
15202         if (Arg.getOpcode() == ISD::UNDEF) continue;
15203         BaseShAmt = Arg;
15204         break;
15205       }
15206     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15207        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15208          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15209          if (C->getZExtValue() == SplatIdx)
15210            BaseShAmt = InVec.getOperand(1);
15211        }
15212     }
15213     if (BaseShAmt.getNode() == 0) {
15214       // Don't create instructions with illegal types after legalize
15215       // types has run.
15216       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15217           !DCI.isBeforeLegalize())
15218         return SDValue();
15219
15220       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15221                               DAG.getIntPtrConstant(0));
15222     }
15223   } else
15224     return SDValue();
15225
15226   // The shift amount is an i32.
15227   if (EltVT.bitsGT(MVT::i32))
15228     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15229   else if (EltVT.bitsLT(MVT::i32))
15230     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15231
15232   // The shift amount is identical so we can do a vector shift.
15233   SDValue  ValOp = N->getOperand(0);
15234   switch (N->getOpcode()) {
15235   default:
15236     llvm_unreachable("Unknown shift opcode!");
15237   case ISD::SHL:
15238     switch (VT.getSimpleVT().SimpleTy) {
15239     default: return SDValue();
15240     case MVT::v2i64:
15241     case MVT::v4i32:
15242     case MVT::v8i16:
15243     case MVT::v4i64:
15244     case MVT::v8i32:
15245     case MVT::v16i16:
15246       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15247     }
15248   case ISD::SRA:
15249     switch (VT.getSimpleVT().SimpleTy) {
15250     default: return SDValue();
15251     case MVT::v4i32:
15252     case MVT::v8i16:
15253     case MVT::v8i32:
15254     case MVT::v16i16:
15255       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15256     }
15257   case ISD::SRL:
15258     switch (VT.getSimpleVT().SimpleTy) {
15259     default: return SDValue();
15260     case MVT::v2i64:
15261     case MVT::v4i32:
15262     case MVT::v8i16:
15263     case MVT::v4i64:
15264     case MVT::v8i32:
15265     case MVT::v16i16:
15266       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15267     }
15268   }
15269 }
15270
15271
15272 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15273 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15274 // and friends.  Likewise for OR -> CMPNEQSS.
15275 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15276                             TargetLowering::DAGCombinerInfo &DCI,
15277                             const X86Subtarget *Subtarget) {
15278   unsigned opcode;
15279
15280   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15281   // we're requiring SSE2 for both.
15282   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15283     SDValue N0 = N->getOperand(0);
15284     SDValue N1 = N->getOperand(1);
15285     SDValue CMP0 = N0->getOperand(1);
15286     SDValue CMP1 = N1->getOperand(1);
15287     DebugLoc DL = N->getDebugLoc();
15288
15289     // The SETCCs should both refer to the same CMP.
15290     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15291       return SDValue();
15292
15293     SDValue CMP00 = CMP0->getOperand(0);
15294     SDValue CMP01 = CMP0->getOperand(1);
15295     EVT     VT    = CMP00.getValueType();
15296
15297     if (VT == MVT::f32 || VT == MVT::f64) {
15298       bool ExpectingFlags = false;
15299       // Check for any users that want flags:
15300       for (SDNode::use_iterator UI = N->use_begin(),
15301              UE = N->use_end();
15302            !ExpectingFlags && UI != UE; ++UI)
15303         switch (UI->getOpcode()) {
15304         default:
15305         case ISD::BR_CC:
15306         case ISD::BRCOND:
15307         case ISD::SELECT:
15308           ExpectingFlags = true;
15309           break;
15310         case ISD::CopyToReg:
15311         case ISD::SIGN_EXTEND:
15312         case ISD::ZERO_EXTEND:
15313         case ISD::ANY_EXTEND:
15314           break;
15315         }
15316
15317       if (!ExpectingFlags) {
15318         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15319         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15320
15321         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15322           X86::CondCode tmp = cc0;
15323           cc0 = cc1;
15324           cc1 = tmp;
15325         }
15326
15327         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15328             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15329           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15330           X86ISD::NodeType NTOperator = is64BitFP ?
15331             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15332           // FIXME: need symbolic constants for these magic numbers.
15333           // See X86ATTInstPrinter.cpp:printSSECC().
15334           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15335           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15336                                               DAG.getConstant(x86cc, MVT::i8));
15337           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15338                                               OnesOrZeroesF);
15339           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15340                                       DAG.getConstant(1, MVT::i32));
15341           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15342           return OneBitOfTruth;
15343         }
15344       }
15345     }
15346   }
15347   return SDValue();
15348 }
15349
15350 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15351 /// so it can be folded inside ANDNP.
15352 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15353   EVT VT = N->getValueType(0);
15354
15355   // Match direct AllOnes for 128 and 256-bit vectors
15356   if (ISD::isBuildVectorAllOnes(N))
15357     return true;
15358
15359   // Look through a bit convert.
15360   if (N->getOpcode() == ISD::BITCAST)
15361     N = N->getOperand(0).getNode();
15362
15363   // Sometimes the operand may come from a insert_subvector building a 256-bit
15364   // allones vector
15365   if (VT.is256BitVector() &&
15366       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15367     SDValue V1 = N->getOperand(0);
15368     SDValue V2 = N->getOperand(1);
15369
15370     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15371         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15372         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15373         ISD::isBuildVectorAllOnes(V2.getNode()))
15374       return true;
15375   }
15376
15377   return false;
15378 }
15379
15380 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15381                                  TargetLowering::DAGCombinerInfo &DCI,
15382                                  const X86Subtarget *Subtarget) {
15383   if (DCI.isBeforeLegalizeOps())
15384     return SDValue();
15385
15386   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15387   if (R.getNode())
15388     return R;
15389
15390   EVT VT = N->getValueType(0);
15391
15392   // Create ANDN, BLSI, and BLSR instructions
15393   // BLSI is X & (-X)
15394   // BLSR is X & (X-1)
15395   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15396     SDValue N0 = N->getOperand(0);
15397     SDValue N1 = N->getOperand(1);
15398     DebugLoc DL = N->getDebugLoc();
15399
15400     // Check LHS for not
15401     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15402       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15403     // Check RHS for not
15404     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15405       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15406
15407     // Check LHS for neg
15408     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15409         isZero(N0.getOperand(0)))
15410       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15411
15412     // Check RHS for neg
15413     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15414         isZero(N1.getOperand(0)))
15415       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15416
15417     // Check LHS for X-1
15418     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15419         isAllOnes(N0.getOperand(1)))
15420       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15421
15422     // Check RHS for X-1
15423     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15424         isAllOnes(N1.getOperand(1)))
15425       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15426
15427     return SDValue();
15428   }
15429
15430   // Want to form ANDNP nodes:
15431   // 1) In the hopes of then easily combining them with OR and AND nodes
15432   //    to form PBLEND/PSIGN.
15433   // 2) To match ANDN packed intrinsics
15434   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15435     return SDValue();
15436
15437   SDValue N0 = N->getOperand(0);
15438   SDValue N1 = N->getOperand(1);
15439   DebugLoc DL = N->getDebugLoc();
15440
15441   // Check LHS for vnot
15442   if (N0.getOpcode() == ISD::XOR &&
15443       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15444       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15445     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15446
15447   // Check RHS for vnot
15448   if (N1.getOpcode() == ISD::XOR &&
15449       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15450       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15451     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15452
15453   return SDValue();
15454 }
15455
15456 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15457                                 TargetLowering::DAGCombinerInfo &DCI,
15458                                 const X86Subtarget *Subtarget) {
15459   if (DCI.isBeforeLegalizeOps())
15460     return SDValue();
15461
15462   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15463   if (R.getNode())
15464     return R;
15465
15466   EVT VT = N->getValueType(0);
15467
15468   SDValue N0 = N->getOperand(0);
15469   SDValue N1 = N->getOperand(1);
15470
15471   // look for psign/blend
15472   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15473     if (!Subtarget->hasSSSE3() ||
15474         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15475       return SDValue();
15476
15477     // Canonicalize pandn to RHS
15478     if (N0.getOpcode() == X86ISD::ANDNP)
15479       std::swap(N0, N1);
15480     // or (and (m, y), (pandn m, x))
15481     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15482       SDValue Mask = N1.getOperand(0);
15483       SDValue X    = N1.getOperand(1);
15484       SDValue Y;
15485       if (N0.getOperand(0) == Mask)
15486         Y = N0.getOperand(1);
15487       if (N0.getOperand(1) == Mask)
15488         Y = N0.getOperand(0);
15489
15490       // Check to see if the mask appeared in both the AND and ANDNP and
15491       if (!Y.getNode())
15492         return SDValue();
15493
15494       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15495       // Look through mask bitcast.
15496       if (Mask.getOpcode() == ISD::BITCAST)
15497         Mask = Mask.getOperand(0);
15498       if (X.getOpcode() == ISD::BITCAST)
15499         X = X.getOperand(0);
15500       if (Y.getOpcode() == ISD::BITCAST)
15501         Y = Y.getOperand(0);
15502
15503       EVT MaskVT = Mask.getValueType();
15504
15505       // Validate that the Mask operand is a vector sra node.
15506       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15507       // there is no psrai.b
15508       if (Mask.getOpcode() != X86ISD::VSRAI)
15509         return SDValue();
15510
15511       // Check that the SRA is all signbits.
15512       SDValue SraC = Mask.getOperand(1);
15513       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15514       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15515       if ((SraAmt + 1) != EltBits)
15516         return SDValue();
15517
15518       DebugLoc DL = N->getDebugLoc();
15519
15520       // Now we know we at least have a plendvb with the mask val.  See if
15521       // we can form a psignb/w/d.
15522       // psign = x.type == y.type == mask.type && y = sub(0, x);
15523       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15524           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15525           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15526         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15527                "Unsupported VT for PSIGN");
15528         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15529         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15530       }
15531       // PBLENDVB only available on SSE 4.1
15532       if (!Subtarget->hasSSE41())
15533         return SDValue();
15534
15535       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15536
15537       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15538       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15539       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15540       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15541       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15542     }
15543   }
15544
15545   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15546     return SDValue();
15547
15548   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15549   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15550     std::swap(N0, N1);
15551   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15552     return SDValue();
15553   if (!N0.hasOneUse() || !N1.hasOneUse())
15554     return SDValue();
15555
15556   SDValue ShAmt0 = N0.getOperand(1);
15557   if (ShAmt0.getValueType() != MVT::i8)
15558     return SDValue();
15559   SDValue ShAmt1 = N1.getOperand(1);
15560   if (ShAmt1.getValueType() != MVT::i8)
15561     return SDValue();
15562   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15563     ShAmt0 = ShAmt0.getOperand(0);
15564   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15565     ShAmt1 = ShAmt1.getOperand(0);
15566
15567   DebugLoc DL = N->getDebugLoc();
15568   unsigned Opc = X86ISD::SHLD;
15569   SDValue Op0 = N0.getOperand(0);
15570   SDValue Op1 = N1.getOperand(0);
15571   if (ShAmt0.getOpcode() == ISD::SUB) {
15572     Opc = X86ISD::SHRD;
15573     std::swap(Op0, Op1);
15574     std::swap(ShAmt0, ShAmt1);
15575   }
15576
15577   unsigned Bits = VT.getSizeInBits();
15578   if (ShAmt1.getOpcode() == ISD::SUB) {
15579     SDValue Sum = ShAmt1.getOperand(0);
15580     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15581       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15582       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15583         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15584       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15585         return DAG.getNode(Opc, DL, VT,
15586                            Op0, Op1,
15587                            DAG.getNode(ISD::TRUNCATE, DL,
15588                                        MVT::i8, ShAmt0));
15589     }
15590   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15591     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15592     if (ShAmt0C &&
15593         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15594       return DAG.getNode(Opc, DL, VT,
15595                          N0.getOperand(0), N1.getOperand(0),
15596                          DAG.getNode(ISD::TRUNCATE, DL,
15597                                        MVT::i8, ShAmt0));
15598   }
15599
15600   return SDValue();
15601 }
15602
15603 // Generate NEG and CMOV for integer abs.
15604 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15605   EVT VT = N->getValueType(0);
15606
15607   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15608   // 8-bit integer abs to NEG and CMOV.
15609   if (VT.isInteger() && VT.getSizeInBits() == 8)
15610     return SDValue();
15611
15612   SDValue N0 = N->getOperand(0);
15613   SDValue N1 = N->getOperand(1);
15614   DebugLoc DL = N->getDebugLoc();
15615
15616   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15617   // and change it to SUB and CMOV.
15618   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15619       N0.getOpcode() == ISD::ADD &&
15620       N0.getOperand(1) == N1 &&
15621       N1.getOpcode() == ISD::SRA &&
15622       N1.getOperand(0) == N0.getOperand(0))
15623     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15624       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15625         // Generate SUB & CMOV.
15626         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15627                                   DAG.getConstant(0, VT), N0.getOperand(0));
15628
15629         SDValue Ops[] = { N0.getOperand(0), Neg,
15630                           DAG.getConstant(X86::COND_GE, MVT::i8),
15631                           SDValue(Neg.getNode(), 1) };
15632         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15633                            Ops, array_lengthof(Ops));
15634       }
15635   return SDValue();
15636 }
15637
15638 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15639 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15640                                  TargetLowering::DAGCombinerInfo &DCI,
15641                                  const X86Subtarget *Subtarget) {
15642   if (DCI.isBeforeLegalizeOps())
15643     return SDValue();
15644
15645   if (Subtarget->hasCMov()) {
15646     SDValue RV = performIntegerAbsCombine(N, DAG);
15647     if (RV.getNode())
15648       return RV;
15649   }
15650
15651   // Try forming BMI if it is available.
15652   if (!Subtarget->hasBMI())
15653     return SDValue();
15654
15655   EVT VT = N->getValueType(0);
15656
15657   if (VT != MVT::i32 && VT != MVT::i64)
15658     return SDValue();
15659
15660   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15661
15662   // Create BLSMSK instructions by finding X ^ (X-1)
15663   SDValue N0 = N->getOperand(0);
15664   SDValue N1 = N->getOperand(1);
15665   DebugLoc DL = N->getDebugLoc();
15666
15667   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15668       isAllOnes(N0.getOperand(1)))
15669     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15670
15671   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15672       isAllOnes(N1.getOperand(1)))
15673     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15674
15675   return SDValue();
15676 }
15677
15678 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15679 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15680                                   TargetLowering::DAGCombinerInfo &DCI,
15681                                   const X86Subtarget *Subtarget) {
15682   LoadSDNode *Ld = cast<LoadSDNode>(N);
15683   EVT RegVT = Ld->getValueType(0);
15684   EVT MemVT = Ld->getMemoryVT();
15685   DebugLoc dl = Ld->getDebugLoc();
15686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15687
15688   ISD::LoadExtType Ext = Ld->getExtensionType();
15689
15690   // If this is a vector EXT Load then attempt to optimize it using a
15691   // shuffle. We need SSSE3 shuffles.
15692   // TODO: It is possible to support ZExt by zeroing the undef values
15693   // during the shuffle phase or after the shuffle.
15694   if (RegVT.isVector() && RegVT.isInteger() &&
15695       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15696     assert(MemVT != RegVT && "Cannot extend to the same type");
15697     assert(MemVT.isVector() && "Must load a vector from memory");
15698
15699     unsigned NumElems = RegVT.getVectorNumElements();
15700     unsigned RegSz = RegVT.getSizeInBits();
15701     unsigned MemSz = MemVT.getSizeInBits();
15702     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15703
15704     // All sizes must be a power of two.
15705     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15706       return SDValue();
15707
15708     // Attempt to load the original value using scalar loads.
15709     // Find the largest scalar type that divides the total loaded size.
15710     MVT SclrLoadTy = MVT::i8;
15711     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15712          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15713       MVT Tp = (MVT::SimpleValueType)tp;
15714       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15715         SclrLoadTy = Tp;
15716       }
15717     }
15718
15719     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15720     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15721         (64 <= MemSz))
15722       SclrLoadTy = MVT::f64;
15723
15724     // Calculate the number of scalar loads that we need to perform
15725     // in order to load our vector from memory.
15726     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15727
15728     // Represent our vector as a sequence of elements which are the
15729     // largest scalar that we can load.
15730     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15731       RegSz/SclrLoadTy.getSizeInBits());
15732
15733     // Represent the data using the same element type that is stored in
15734     // memory. In practice, we ''widen'' MemVT.
15735     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15736                                   RegSz/MemVT.getScalarType().getSizeInBits());
15737
15738     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15739       "Invalid vector type");
15740
15741     // We can't shuffle using an illegal type.
15742     if (!TLI.isTypeLegal(WideVecVT))
15743       return SDValue();
15744
15745     SmallVector<SDValue, 8> Chains;
15746     SDValue Ptr = Ld->getBasePtr();
15747     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15748                                         TLI.getPointerTy());
15749     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15750
15751     for (unsigned i = 0; i < NumLoads; ++i) {
15752       // Perform a single load.
15753       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15754                                        Ptr, Ld->getPointerInfo(),
15755                                        Ld->isVolatile(), Ld->isNonTemporal(),
15756                                        Ld->isInvariant(), Ld->getAlignment());
15757       Chains.push_back(ScalarLoad.getValue(1));
15758       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15759       // another round of DAGCombining.
15760       if (i == 0)
15761         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15762       else
15763         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15764                           ScalarLoad, DAG.getIntPtrConstant(i));
15765
15766       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15767     }
15768
15769     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15770                                Chains.size());
15771
15772     // Bitcast the loaded value to a vector of the original element type, in
15773     // the size of the target vector type.
15774     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15775     unsigned SizeRatio = RegSz/MemSz;
15776
15777     // Redistribute the loaded elements into the different locations.
15778     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15779     for (unsigned i = 0; i != NumElems; ++i)
15780       ShuffleVec[i*SizeRatio] = i;
15781
15782     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15783                                          DAG.getUNDEF(WideVecVT),
15784                                          &ShuffleVec[0]);
15785
15786     // Bitcast to the requested type.
15787     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15788     // Replace the original load with the new sequence
15789     // and return the new chain.
15790     return DCI.CombineTo(N, Shuff, TF, true);
15791   }
15792
15793   return SDValue();
15794 }
15795
15796 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15797 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15798                                    const X86Subtarget *Subtarget) {
15799   StoreSDNode *St = cast<StoreSDNode>(N);
15800   EVT VT = St->getValue().getValueType();
15801   EVT StVT = St->getMemoryVT();
15802   DebugLoc dl = St->getDebugLoc();
15803   SDValue StoredVal = St->getOperand(1);
15804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15805
15806   // If we are saving a concatenation of two XMM registers, perform two stores.
15807   // On Sandy Bridge, 256-bit memory operations are executed by two
15808   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15809   // memory  operation.
15810   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15811       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15812       StoredVal.getNumOperands() == 2) {
15813     SDValue Value0 = StoredVal.getOperand(0);
15814     SDValue Value1 = StoredVal.getOperand(1);
15815
15816     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15817     SDValue Ptr0 = St->getBasePtr();
15818     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15819
15820     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15821                                 St->getPointerInfo(), St->isVolatile(),
15822                                 St->isNonTemporal(), St->getAlignment());
15823     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15824                                 St->getPointerInfo(), St->isVolatile(),
15825                                 St->isNonTemporal(), St->getAlignment());
15826     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15827   }
15828
15829   // Optimize trunc store (of multiple scalars) to shuffle and store.
15830   // First, pack all of the elements in one place. Next, store to memory
15831   // in fewer chunks.
15832   if (St->isTruncatingStore() && VT.isVector()) {
15833     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15834     unsigned NumElems = VT.getVectorNumElements();
15835     assert(StVT != VT && "Cannot truncate to the same type");
15836     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15837     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15838
15839     // From, To sizes and ElemCount must be pow of two
15840     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15841     // We are going to use the original vector elt for storing.
15842     // Accumulated smaller vector elements must be a multiple of the store size.
15843     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15844
15845     unsigned SizeRatio  = FromSz / ToSz;
15846
15847     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15848
15849     // Create a type on which we perform the shuffle
15850     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15851             StVT.getScalarType(), NumElems*SizeRatio);
15852
15853     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15854
15855     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15856     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15857     for (unsigned i = 0; i != NumElems; ++i)
15858       ShuffleVec[i] = i * SizeRatio;
15859
15860     // Can't shuffle using an illegal type.
15861     if (!TLI.isTypeLegal(WideVecVT))
15862       return SDValue();
15863
15864     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15865                                          DAG.getUNDEF(WideVecVT),
15866                                          &ShuffleVec[0]);
15867     // At this point all of the data is stored at the bottom of the
15868     // register. We now need to save it to mem.
15869
15870     // Find the largest store unit
15871     MVT StoreType = MVT::i8;
15872     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15873          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15874       MVT Tp = (MVT::SimpleValueType)tp;
15875       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15876         StoreType = Tp;
15877     }
15878
15879     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15880     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15881         (64 <= NumElems * ToSz))
15882       StoreType = MVT::f64;
15883
15884     // Bitcast the original vector into a vector of store-size units
15885     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15886             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15887     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15888     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15889     SmallVector<SDValue, 8> Chains;
15890     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15891                                         TLI.getPointerTy());
15892     SDValue Ptr = St->getBasePtr();
15893
15894     // Perform one or more big stores into memory.
15895     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15896       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15897                                    StoreType, ShuffWide,
15898                                    DAG.getIntPtrConstant(i));
15899       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15900                                 St->getPointerInfo(), St->isVolatile(),
15901                                 St->isNonTemporal(), St->getAlignment());
15902       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15903       Chains.push_back(Ch);
15904     }
15905
15906     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15907                                Chains.size());
15908   }
15909
15910
15911   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15912   // the FP state in cases where an emms may be missing.
15913   // A preferable solution to the general problem is to figure out the right
15914   // places to insert EMMS.  This qualifies as a quick hack.
15915
15916   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15917   if (VT.getSizeInBits() != 64)
15918     return SDValue();
15919
15920   const Function *F = DAG.getMachineFunction().getFunction();
15921   bool NoImplicitFloatOps = F->getFnAttributes().
15922     hasAttribute(Attributes::NoImplicitFloat);
15923   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15924                      && Subtarget->hasSSE2();
15925   if ((VT.isVector() ||
15926        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15927       isa<LoadSDNode>(St->getValue()) &&
15928       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15929       St->getChain().hasOneUse() && !St->isVolatile()) {
15930     SDNode* LdVal = St->getValue().getNode();
15931     LoadSDNode *Ld = 0;
15932     int TokenFactorIndex = -1;
15933     SmallVector<SDValue, 8> Ops;
15934     SDNode* ChainVal = St->getChain().getNode();
15935     // Must be a store of a load.  We currently handle two cases:  the load
15936     // is a direct child, and it's under an intervening TokenFactor.  It is
15937     // possible to dig deeper under nested TokenFactors.
15938     if (ChainVal == LdVal)
15939       Ld = cast<LoadSDNode>(St->getChain());
15940     else if (St->getValue().hasOneUse() &&
15941              ChainVal->getOpcode() == ISD::TokenFactor) {
15942       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15943         if (ChainVal->getOperand(i).getNode() == LdVal) {
15944           TokenFactorIndex = i;
15945           Ld = cast<LoadSDNode>(St->getValue());
15946         } else
15947           Ops.push_back(ChainVal->getOperand(i));
15948       }
15949     }
15950
15951     if (!Ld || !ISD::isNormalLoad(Ld))
15952       return SDValue();
15953
15954     // If this is not the MMX case, i.e. we are just turning i64 load/store
15955     // into f64 load/store, avoid the transformation if there are multiple
15956     // uses of the loaded value.
15957     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15958       return SDValue();
15959
15960     DebugLoc LdDL = Ld->getDebugLoc();
15961     DebugLoc StDL = N->getDebugLoc();
15962     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15963     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15964     // pair instead.
15965     if (Subtarget->is64Bit() || F64IsLegal) {
15966       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15967       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15968                                   Ld->getPointerInfo(), Ld->isVolatile(),
15969                                   Ld->isNonTemporal(), Ld->isInvariant(),
15970                                   Ld->getAlignment());
15971       SDValue NewChain = NewLd.getValue(1);
15972       if (TokenFactorIndex != -1) {
15973         Ops.push_back(NewChain);
15974         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15975                                Ops.size());
15976       }
15977       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15978                           St->getPointerInfo(),
15979                           St->isVolatile(), St->isNonTemporal(),
15980                           St->getAlignment());
15981     }
15982
15983     // Otherwise, lower to two pairs of 32-bit loads / stores.
15984     SDValue LoAddr = Ld->getBasePtr();
15985     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15986                                  DAG.getConstant(4, MVT::i32));
15987
15988     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15989                                Ld->getPointerInfo(),
15990                                Ld->isVolatile(), Ld->isNonTemporal(),
15991                                Ld->isInvariant(), Ld->getAlignment());
15992     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15993                                Ld->getPointerInfo().getWithOffset(4),
15994                                Ld->isVolatile(), Ld->isNonTemporal(),
15995                                Ld->isInvariant(),
15996                                MinAlign(Ld->getAlignment(), 4));
15997
15998     SDValue NewChain = LoLd.getValue(1);
15999     if (TokenFactorIndex != -1) {
16000       Ops.push_back(LoLd);
16001       Ops.push_back(HiLd);
16002       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16003                              Ops.size());
16004     }
16005
16006     LoAddr = St->getBasePtr();
16007     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16008                          DAG.getConstant(4, MVT::i32));
16009
16010     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16011                                 St->getPointerInfo(),
16012                                 St->isVolatile(), St->isNonTemporal(),
16013                                 St->getAlignment());
16014     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16015                                 St->getPointerInfo().getWithOffset(4),
16016                                 St->isVolatile(),
16017                                 St->isNonTemporal(),
16018                                 MinAlign(St->getAlignment(), 4));
16019     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16020   }
16021   return SDValue();
16022 }
16023
16024 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16025 /// and return the operands for the horizontal operation in LHS and RHS.  A
16026 /// horizontal operation performs the binary operation on successive elements
16027 /// of its first operand, then on successive elements of its second operand,
16028 /// returning the resulting values in a vector.  For example, if
16029 ///   A = < float a0, float a1, float a2, float a3 >
16030 /// and
16031 ///   B = < float b0, float b1, float b2, float b3 >
16032 /// then the result of doing a horizontal operation on A and B is
16033 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16034 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16035 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16036 /// set to A, RHS to B, and the routine returns 'true'.
16037 /// Note that the binary operation should have the property that if one of the
16038 /// operands is UNDEF then the result is UNDEF.
16039 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16040   // Look for the following pattern: if
16041   //   A = < float a0, float a1, float a2, float a3 >
16042   //   B = < float b0, float b1, float b2, float b3 >
16043   // and
16044   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16045   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16046   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16047   // which is A horizontal-op B.
16048
16049   // At least one of the operands should be a vector shuffle.
16050   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16051       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16052     return false;
16053
16054   EVT VT = LHS.getValueType();
16055
16056   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16057          "Unsupported vector type for horizontal add/sub");
16058
16059   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16060   // operate independently on 128-bit lanes.
16061   unsigned NumElts = VT.getVectorNumElements();
16062   unsigned NumLanes = VT.getSizeInBits()/128;
16063   unsigned NumLaneElts = NumElts / NumLanes;
16064   assert((NumLaneElts % 2 == 0) &&
16065          "Vector type should have an even number of elements in each lane");
16066   unsigned HalfLaneElts = NumLaneElts/2;
16067
16068   // View LHS in the form
16069   //   LHS = VECTOR_SHUFFLE A, B, LMask
16070   // If LHS is not a shuffle then pretend it is the shuffle
16071   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16072   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16073   // type VT.
16074   SDValue A, B;
16075   SmallVector<int, 16> LMask(NumElts);
16076   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16077     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16078       A = LHS.getOperand(0);
16079     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16080       B = LHS.getOperand(1);
16081     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16082     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16083   } else {
16084     if (LHS.getOpcode() != ISD::UNDEF)
16085       A = LHS;
16086     for (unsigned i = 0; i != NumElts; ++i)
16087       LMask[i] = i;
16088   }
16089
16090   // Likewise, view RHS in the form
16091   //   RHS = VECTOR_SHUFFLE C, D, RMask
16092   SDValue C, D;
16093   SmallVector<int, 16> RMask(NumElts);
16094   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16095     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16096       C = RHS.getOperand(0);
16097     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16098       D = RHS.getOperand(1);
16099     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16100     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16101   } else {
16102     if (RHS.getOpcode() != ISD::UNDEF)
16103       C = RHS;
16104     for (unsigned i = 0; i != NumElts; ++i)
16105       RMask[i] = i;
16106   }
16107
16108   // Check that the shuffles are both shuffling the same vectors.
16109   if (!(A == C && B == D) && !(A == D && B == C))
16110     return false;
16111
16112   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16113   if (!A.getNode() && !B.getNode())
16114     return false;
16115
16116   // If A and B occur in reverse order in RHS, then "swap" them (which means
16117   // rewriting the mask).
16118   if (A != C)
16119     CommuteVectorShuffleMask(RMask, NumElts);
16120
16121   // At this point LHS and RHS are equivalent to
16122   //   LHS = VECTOR_SHUFFLE A, B, LMask
16123   //   RHS = VECTOR_SHUFFLE A, B, RMask
16124   // Check that the masks correspond to performing a horizontal operation.
16125   for (unsigned i = 0; i != NumElts; ++i) {
16126     int LIdx = LMask[i], RIdx = RMask[i];
16127
16128     // Ignore any UNDEF components.
16129     if (LIdx < 0 || RIdx < 0 ||
16130         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16131         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16132       continue;
16133
16134     // Check that successive elements are being operated on.  If not, this is
16135     // not a horizontal operation.
16136     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16137     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16138     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16139     if (!(LIdx == Index && RIdx == Index + 1) &&
16140         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16141       return false;
16142   }
16143
16144   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16145   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16146   return true;
16147 }
16148
16149 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16150 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16151                                   const X86Subtarget *Subtarget) {
16152   EVT VT = N->getValueType(0);
16153   SDValue LHS = N->getOperand(0);
16154   SDValue RHS = N->getOperand(1);
16155
16156   // Try to synthesize horizontal adds from adds of shuffles.
16157   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16158        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16159       isHorizontalBinOp(LHS, RHS, true))
16160     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16161   return SDValue();
16162 }
16163
16164 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16165 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16166                                   const X86Subtarget *Subtarget) {
16167   EVT VT = N->getValueType(0);
16168   SDValue LHS = N->getOperand(0);
16169   SDValue RHS = N->getOperand(1);
16170
16171   // Try to synthesize horizontal subs from subs of shuffles.
16172   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16173        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16174       isHorizontalBinOp(LHS, RHS, false))
16175     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16176   return SDValue();
16177 }
16178
16179 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16180 /// X86ISD::FXOR nodes.
16181 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16182   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16183   // F[X]OR(0.0, x) -> x
16184   // F[X]OR(x, 0.0) -> x
16185   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16186     if (C->getValueAPF().isPosZero())
16187       return N->getOperand(1);
16188   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16189     if (C->getValueAPF().isPosZero())
16190       return N->getOperand(0);
16191   return SDValue();
16192 }
16193
16194 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16195 /// X86ISD::FMAX nodes.
16196 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16197   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16198
16199   // Only perform optimizations if UnsafeMath is used.
16200   if (!DAG.getTarget().Options.UnsafeFPMath)
16201     return SDValue();
16202
16203   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16204   // into FMINC and FMAXC, which are Commutative operations.
16205   unsigned NewOp = 0;
16206   switch (N->getOpcode()) {
16207     default: llvm_unreachable("unknown opcode");
16208     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16209     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16210   }
16211
16212   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16213                      N->getOperand(0), N->getOperand(1));
16214 }
16215
16216
16217 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16218 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16219   // FAND(0.0, x) -> 0.0
16220   // FAND(x, 0.0) -> 0.0
16221   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16222     if (C->getValueAPF().isPosZero())
16223       return N->getOperand(0);
16224   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16225     if (C->getValueAPF().isPosZero())
16226       return N->getOperand(1);
16227   return SDValue();
16228 }
16229
16230 static SDValue PerformBTCombine(SDNode *N,
16231                                 SelectionDAG &DAG,
16232                                 TargetLowering::DAGCombinerInfo &DCI) {
16233   // BT ignores high bits in the bit index operand.
16234   SDValue Op1 = N->getOperand(1);
16235   if (Op1.hasOneUse()) {
16236     unsigned BitWidth = Op1.getValueSizeInBits();
16237     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16238     APInt KnownZero, KnownOne;
16239     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16240                                           !DCI.isBeforeLegalizeOps());
16241     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16242     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16243         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16244       DCI.CommitTargetLoweringOpt(TLO);
16245   }
16246   return SDValue();
16247 }
16248
16249 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16250   SDValue Op = N->getOperand(0);
16251   if (Op.getOpcode() == ISD::BITCAST)
16252     Op = Op.getOperand(0);
16253   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16254   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16255       VT.getVectorElementType().getSizeInBits() ==
16256       OpVT.getVectorElementType().getSizeInBits()) {
16257     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16258   }
16259   return SDValue();
16260 }
16261
16262 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16263                                   TargetLowering::DAGCombinerInfo &DCI,
16264                                   const X86Subtarget *Subtarget) {
16265   if (!DCI.isBeforeLegalizeOps())
16266     return SDValue();
16267
16268   if (!Subtarget->hasAVX())
16269     return SDValue();
16270
16271   EVT VT = N->getValueType(0);
16272   SDValue Op = N->getOperand(0);
16273   EVT OpVT = Op.getValueType();
16274   DebugLoc dl = N->getDebugLoc();
16275
16276   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16277       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16278
16279     if (Subtarget->hasAVX2())
16280       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16281
16282     // Optimize vectors in AVX mode
16283     // Sign extend  v8i16 to v8i32 and
16284     //              v4i32 to v4i64
16285     //
16286     // Divide input vector into two parts
16287     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16288     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16289     // concat the vectors to original VT
16290
16291     unsigned NumElems = OpVT.getVectorNumElements();
16292     SDValue Undef = DAG.getUNDEF(OpVT);
16293
16294     SmallVector<int,8> ShufMask1(NumElems, -1);
16295     for (unsigned i = 0; i != NumElems/2; ++i)
16296       ShufMask1[i] = i;
16297
16298     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16299
16300     SmallVector<int,8> ShufMask2(NumElems, -1);
16301     for (unsigned i = 0; i != NumElems/2; ++i)
16302       ShufMask2[i] = i + NumElems/2;
16303
16304     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16305
16306     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16307                                   VT.getVectorNumElements()/2);
16308
16309     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16310     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16311
16312     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16313   }
16314   return SDValue();
16315 }
16316
16317 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16318                                  const X86Subtarget* Subtarget) {
16319   DebugLoc dl = N->getDebugLoc();
16320   EVT VT = N->getValueType(0);
16321
16322   // Let legalize expand this if it isn't a legal type yet.
16323   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16324     return SDValue();
16325
16326   EVT ScalarVT = VT.getScalarType();
16327   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16328       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16329     return SDValue();
16330
16331   SDValue A = N->getOperand(0);
16332   SDValue B = N->getOperand(1);
16333   SDValue C = N->getOperand(2);
16334
16335   bool NegA = (A.getOpcode() == ISD::FNEG);
16336   bool NegB = (B.getOpcode() == ISD::FNEG);
16337   bool NegC = (C.getOpcode() == ISD::FNEG);
16338
16339   // Negative multiplication when NegA xor NegB
16340   bool NegMul = (NegA != NegB);
16341   if (NegA)
16342     A = A.getOperand(0);
16343   if (NegB)
16344     B = B.getOperand(0);
16345   if (NegC)
16346     C = C.getOperand(0);
16347
16348   unsigned Opcode;
16349   if (!NegMul)
16350     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16351   else
16352     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16353
16354   return DAG.getNode(Opcode, dl, VT, A, B, C);
16355 }
16356
16357 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16358                                   TargetLowering::DAGCombinerInfo &DCI,
16359                                   const X86Subtarget *Subtarget) {
16360   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16361   //           (and (i32 x86isd::setcc_carry), 1)
16362   // This eliminates the zext. This transformation is necessary because
16363   // ISD::SETCC is always legalized to i8.
16364   DebugLoc dl = N->getDebugLoc();
16365   SDValue N0 = N->getOperand(0);
16366   EVT VT = N->getValueType(0);
16367   EVT OpVT = N0.getValueType();
16368
16369   if (N0.getOpcode() == ISD::AND &&
16370       N0.hasOneUse() &&
16371       N0.getOperand(0).hasOneUse()) {
16372     SDValue N00 = N0.getOperand(0);
16373     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16374       return SDValue();
16375     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16376     if (!C || C->getZExtValue() != 1)
16377       return SDValue();
16378     return DAG.getNode(ISD::AND, dl, VT,
16379                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16380                                    N00.getOperand(0), N00.getOperand(1)),
16381                        DAG.getConstant(1, VT));
16382   }
16383
16384   // Optimize vectors in AVX mode:
16385   //
16386   //   v8i16 -> v8i32
16387   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16388   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16389   //   Concat upper and lower parts.
16390   //
16391   //   v4i32 -> v4i64
16392   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16393   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16394   //   Concat upper and lower parts.
16395   //
16396   if (!DCI.isBeforeLegalizeOps())
16397     return SDValue();
16398
16399   if (!Subtarget->hasAVX())
16400     return SDValue();
16401
16402   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16403       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16404
16405     if (Subtarget->hasAVX2())
16406       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16407
16408     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16409     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16410     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16411
16412     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16413                                VT.getVectorNumElements()/2);
16414
16415     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16416     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16417
16418     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16419   }
16420
16421   return SDValue();
16422 }
16423
16424 // Optimize x == -y --> x+y == 0
16425 //          x != -y --> x+y != 0
16426 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16427   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16428   SDValue LHS = N->getOperand(0);
16429   SDValue RHS = N->getOperand(1);
16430
16431   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16432     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16433       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16434         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16435                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16436         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16437                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16438       }
16439   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16441       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16442         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16443                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16444         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16445                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16446       }
16447   return SDValue();
16448 }
16449
16450 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16451 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16452                                    TargetLowering::DAGCombinerInfo &DCI,
16453                                    const X86Subtarget *Subtarget) {
16454   DebugLoc DL = N->getDebugLoc();
16455   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16456   SDValue EFLAGS = N->getOperand(1);
16457
16458   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16459   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16460   // cases.
16461   if (CC == X86::COND_B)
16462     return DAG.getNode(ISD::AND, DL, MVT::i8,
16463                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16464                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16465                        DAG.getConstant(1, MVT::i8));
16466
16467   SDValue Flags;
16468
16469   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16470   if (Flags.getNode()) {
16471     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16472     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16473   }
16474
16475   return SDValue();
16476 }
16477
16478 // Optimize branch condition evaluation.
16479 //
16480 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16481                                     TargetLowering::DAGCombinerInfo &DCI,
16482                                     const X86Subtarget *Subtarget) {
16483   DebugLoc DL = N->getDebugLoc();
16484   SDValue Chain = N->getOperand(0);
16485   SDValue Dest = N->getOperand(1);
16486   SDValue EFLAGS = N->getOperand(3);
16487   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16488
16489   SDValue Flags;
16490
16491   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16492   if (Flags.getNode()) {
16493     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16494     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16495                        Flags);
16496   }
16497
16498   return SDValue();
16499 }
16500
16501 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16502                                         const X86TargetLowering *XTLI) {
16503   SDValue Op0 = N->getOperand(0);
16504   EVT InVT = Op0->getValueType(0);
16505
16506   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16507   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16508     DebugLoc dl = N->getDebugLoc();
16509     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16510     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16511     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16512   }
16513
16514   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16515   // a 32-bit target where SSE doesn't support i64->FP operations.
16516   if (Op0.getOpcode() == ISD::LOAD) {
16517     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16518     EVT VT = Ld->getValueType(0);
16519     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16520         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16521         !XTLI->getSubtarget()->is64Bit() &&
16522         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16523       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16524                                           Ld->getChain(), Op0, DAG);
16525       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16526       return FILDChain;
16527     }
16528   }
16529   return SDValue();
16530 }
16531
16532 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16533 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16534                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16535   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16536   // the result is either zero or one (depending on the input carry bit).
16537   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16538   if (X86::isZeroNode(N->getOperand(0)) &&
16539       X86::isZeroNode(N->getOperand(1)) &&
16540       // We don't have a good way to replace an EFLAGS use, so only do this when
16541       // dead right now.
16542       SDValue(N, 1).use_empty()) {
16543     DebugLoc DL = N->getDebugLoc();
16544     EVT VT = N->getValueType(0);
16545     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16546     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16547                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16548                                            DAG.getConstant(X86::COND_B,MVT::i8),
16549                                            N->getOperand(2)),
16550                                DAG.getConstant(1, VT));
16551     return DCI.CombineTo(N, Res1, CarryOut);
16552   }
16553
16554   return SDValue();
16555 }
16556
16557 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16558 //      (add Y, (setne X, 0)) -> sbb -1, Y
16559 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16560 //      (sub (setne X, 0), Y) -> adc -1, Y
16561 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16562   DebugLoc DL = N->getDebugLoc();
16563
16564   // Look through ZExts.
16565   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16566   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16567     return SDValue();
16568
16569   SDValue SetCC = Ext.getOperand(0);
16570   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16571     return SDValue();
16572
16573   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16574   if (CC != X86::COND_E && CC != X86::COND_NE)
16575     return SDValue();
16576
16577   SDValue Cmp = SetCC.getOperand(1);
16578   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16579       !X86::isZeroNode(Cmp.getOperand(1)) ||
16580       !Cmp.getOperand(0).getValueType().isInteger())
16581     return SDValue();
16582
16583   SDValue CmpOp0 = Cmp.getOperand(0);
16584   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16585                                DAG.getConstant(1, CmpOp0.getValueType()));
16586
16587   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16588   if (CC == X86::COND_NE)
16589     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16590                        DL, OtherVal.getValueType(), OtherVal,
16591                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16592   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16593                      DL, OtherVal.getValueType(), OtherVal,
16594                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16595 }
16596
16597 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16598 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16599                                  const X86Subtarget *Subtarget) {
16600   EVT VT = N->getValueType(0);
16601   SDValue Op0 = N->getOperand(0);
16602   SDValue Op1 = N->getOperand(1);
16603
16604   // Try to synthesize horizontal adds from adds of shuffles.
16605   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16606        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16607       isHorizontalBinOp(Op0, Op1, true))
16608     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16609
16610   return OptimizeConditionalInDecrement(N, DAG);
16611 }
16612
16613 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16614                                  const X86Subtarget *Subtarget) {
16615   SDValue Op0 = N->getOperand(0);
16616   SDValue Op1 = N->getOperand(1);
16617
16618   // X86 can't encode an immediate LHS of a sub. See if we can push the
16619   // negation into a preceding instruction.
16620   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16621     // If the RHS of the sub is a XOR with one use and a constant, invert the
16622     // immediate. Then add one to the LHS of the sub so we can turn
16623     // X-Y -> X+~Y+1, saving one register.
16624     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16625         isa<ConstantSDNode>(Op1.getOperand(1))) {
16626       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16627       EVT VT = Op0.getValueType();
16628       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16629                                    Op1.getOperand(0),
16630                                    DAG.getConstant(~XorC, VT));
16631       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16632                          DAG.getConstant(C->getAPIntValue()+1, VT));
16633     }
16634   }
16635
16636   // Try to synthesize horizontal adds from adds of shuffles.
16637   EVT VT = N->getValueType(0);
16638   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16639        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16640       isHorizontalBinOp(Op0, Op1, true))
16641     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16642
16643   return OptimizeConditionalInDecrement(N, DAG);
16644 }
16645
16646 /// performVZEXTCombine - Performs build vector combines
16647 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16648                                         TargetLowering::DAGCombinerInfo &DCI,
16649                                         const X86Subtarget *Subtarget) {
16650   // (vzext (bitcast (vzext (x)) -> (vzext x)
16651   SDValue In = N->getOperand(0);
16652   while (In.getOpcode() == ISD::BITCAST)
16653     In = In.getOperand(0);
16654
16655   if (In.getOpcode() != X86ISD::VZEXT)
16656     return SDValue();
16657
16658   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16659 }
16660
16661 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16662                                              DAGCombinerInfo &DCI) const {
16663   SelectionDAG &DAG = DCI.DAG;
16664   switch (N->getOpcode()) {
16665   default: break;
16666   case ISD::EXTRACT_VECTOR_ELT:
16667     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16668   case ISD::VSELECT:
16669   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16670   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16671   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16672   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16673   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16674   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16675   case ISD::SHL:
16676   case ISD::SRA:
16677   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16678   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16679   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16680   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16681   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16682   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16683   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16684   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16685   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16686   case X86ISD::FXOR:
16687   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16688   case X86ISD::FMIN:
16689   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16690   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16691   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16692   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16693   case ISD::ANY_EXTEND:
16694   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16695   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16696   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16697   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16698   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16699   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16700   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
16701   case X86ISD::SHUFP:       // Handle all target specific shuffles
16702   case X86ISD::PALIGN:
16703   case X86ISD::UNPCKH:
16704   case X86ISD::UNPCKL:
16705   case X86ISD::MOVHLPS:
16706   case X86ISD::MOVLHPS:
16707   case X86ISD::PSHUFD:
16708   case X86ISD::PSHUFHW:
16709   case X86ISD::PSHUFLW:
16710   case X86ISD::MOVSS:
16711   case X86ISD::MOVSD:
16712   case X86ISD::VPERMILP:
16713   case X86ISD::VPERM2X128:
16714   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16715   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16716   }
16717
16718   return SDValue();
16719 }
16720
16721 /// isTypeDesirableForOp - Return true if the target has native support for
16722 /// the specified value type and it is 'desirable' to use the type for the
16723 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16724 /// instruction encodings are longer and some i16 instructions are slow.
16725 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16726   if (!isTypeLegal(VT))
16727     return false;
16728   if (VT != MVT::i16)
16729     return true;
16730
16731   switch (Opc) {
16732   default:
16733     return true;
16734   case ISD::LOAD:
16735   case ISD::SIGN_EXTEND:
16736   case ISD::ZERO_EXTEND:
16737   case ISD::ANY_EXTEND:
16738   case ISD::SHL:
16739   case ISD::SRL:
16740   case ISD::SUB:
16741   case ISD::ADD:
16742   case ISD::MUL:
16743   case ISD::AND:
16744   case ISD::OR:
16745   case ISD::XOR:
16746     return false;
16747   }
16748 }
16749
16750 /// IsDesirableToPromoteOp - This method query the target whether it is
16751 /// beneficial for dag combiner to promote the specified node. If true, it
16752 /// should return the desired promotion type by reference.
16753 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16754   EVT VT = Op.getValueType();
16755   if (VT != MVT::i16)
16756     return false;
16757
16758   bool Promote = false;
16759   bool Commute = false;
16760   switch (Op.getOpcode()) {
16761   default: break;
16762   case ISD::LOAD: {
16763     LoadSDNode *LD = cast<LoadSDNode>(Op);
16764     // If the non-extending load has a single use and it's not live out, then it
16765     // might be folded.
16766     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16767                                                      Op.hasOneUse()*/) {
16768       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16769              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16770         // The only case where we'd want to promote LOAD (rather then it being
16771         // promoted as an operand is when it's only use is liveout.
16772         if (UI->getOpcode() != ISD::CopyToReg)
16773           return false;
16774       }
16775     }
16776     Promote = true;
16777     break;
16778   }
16779   case ISD::SIGN_EXTEND:
16780   case ISD::ZERO_EXTEND:
16781   case ISD::ANY_EXTEND:
16782     Promote = true;
16783     break;
16784   case ISD::SHL:
16785   case ISD::SRL: {
16786     SDValue N0 = Op.getOperand(0);
16787     // Look out for (store (shl (load), x)).
16788     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16789       return false;
16790     Promote = true;
16791     break;
16792   }
16793   case ISD::ADD:
16794   case ISD::MUL:
16795   case ISD::AND:
16796   case ISD::OR:
16797   case ISD::XOR:
16798     Commute = true;
16799     // fallthrough
16800   case ISD::SUB: {
16801     SDValue N0 = Op.getOperand(0);
16802     SDValue N1 = Op.getOperand(1);
16803     if (!Commute && MayFoldLoad(N1))
16804       return false;
16805     // Avoid disabling potential load folding opportunities.
16806     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16807       return false;
16808     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16809       return false;
16810     Promote = true;
16811   }
16812   }
16813
16814   PVT = MVT::i32;
16815   return Promote;
16816 }
16817
16818 //===----------------------------------------------------------------------===//
16819 //                           X86 Inline Assembly Support
16820 //===----------------------------------------------------------------------===//
16821
16822 namespace {
16823   // Helper to match a string separated by whitespace.
16824   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16825     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16826
16827     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16828       StringRef piece(*args[i]);
16829       if (!s.startswith(piece)) // Check if the piece matches.
16830         return false;
16831
16832       s = s.substr(piece.size());
16833       StringRef::size_type pos = s.find_first_not_of(" \t");
16834       if (pos == 0) // We matched a prefix.
16835         return false;
16836
16837       s = s.substr(pos);
16838     }
16839
16840     return s.empty();
16841   }
16842   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16843 }
16844
16845 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16846   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16847
16848   std::string AsmStr = IA->getAsmString();
16849
16850   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16851   if (!Ty || Ty->getBitWidth() % 16 != 0)
16852     return false;
16853
16854   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16855   SmallVector<StringRef, 4> AsmPieces;
16856   SplitString(AsmStr, AsmPieces, ";\n");
16857
16858   switch (AsmPieces.size()) {
16859   default: return false;
16860   case 1:
16861     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16862     // we will turn this bswap into something that will be lowered to logical
16863     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16864     // lower so don't worry about this.
16865     // bswap $0
16866     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16867         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16868         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16869         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16870         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16871         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16872       // No need to check constraints, nothing other than the equivalent of
16873       // "=r,0" would be valid here.
16874       return IntrinsicLowering::LowerToByteSwap(CI);
16875     }
16876
16877     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16878     if (CI->getType()->isIntegerTy(16) &&
16879         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16880         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16881          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16882       AsmPieces.clear();
16883       const std::string &ConstraintsStr = IA->getConstraintString();
16884       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16885       std::sort(AsmPieces.begin(), AsmPieces.end());
16886       if (AsmPieces.size() == 4 &&
16887           AsmPieces[0] == "~{cc}" &&
16888           AsmPieces[1] == "~{dirflag}" &&
16889           AsmPieces[2] == "~{flags}" &&
16890           AsmPieces[3] == "~{fpsr}")
16891       return IntrinsicLowering::LowerToByteSwap(CI);
16892     }
16893     break;
16894   case 3:
16895     if (CI->getType()->isIntegerTy(32) &&
16896         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16897         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16898         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16899         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16900       AsmPieces.clear();
16901       const std::string &ConstraintsStr = IA->getConstraintString();
16902       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16903       std::sort(AsmPieces.begin(), AsmPieces.end());
16904       if (AsmPieces.size() == 4 &&
16905           AsmPieces[0] == "~{cc}" &&
16906           AsmPieces[1] == "~{dirflag}" &&
16907           AsmPieces[2] == "~{flags}" &&
16908           AsmPieces[3] == "~{fpsr}")
16909         return IntrinsicLowering::LowerToByteSwap(CI);
16910     }
16911
16912     if (CI->getType()->isIntegerTy(64)) {
16913       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16914       if (Constraints.size() >= 2 &&
16915           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16916           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16917         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16918         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16919             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16920             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16921           return IntrinsicLowering::LowerToByteSwap(CI);
16922       }
16923     }
16924     break;
16925   }
16926   return false;
16927 }
16928
16929
16930
16931 /// getConstraintType - Given a constraint letter, return the type of
16932 /// constraint it is for this target.
16933 X86TargetLowering::ConstraintType
16934 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16935   if (Constraint.size() == 1) {
16936     switch (Constraint[0]) {
16937     case 'R':
16938     case 'q':
16939     case 'Q':
16940     case 'f':
16941     case 't':
16942     case 'u':
16943     case 'y':
16944     case 'x':
16945     case 'Y':
16946     case 'l':
16947       return C_RegisterClass;
16948     case 'a':
16949     case 'b':
16950     case 'c':
16951     case 'd':
16952     case 'S':
16953     case 'D':
16954     case 'A':
16955       return C_Register;
16956     case 'I':
16957     case 'J':
16958     case 'K':
16959     case 'L':
16960     case 'M':
16961     case 'N':
16962     case 'G':
16963     case 'C':
16964     case 'e':
16965     case 'Z':
16966       return C_Other;
16967     default:
16968       break;
16969     }
16970   }
16971   return TargetLowering::getConstraintType(Constraint);
16972 }
16973
16974 /// Examine constraint type and operand type and determine a weight value.
16975 /// This object must already have been set up with the operand type
16976 /// and the current alternative constraint selected.
16977 TargetLowering::ConstraintWeight
16978   X86TargetLowering::getSingleConstraintMatchWeight(
16979     AsmOperandInfo &info, const char *constraint) const {
16980   ConstraintWeight weight = CW_Invalid;
16981   Value *CallOperandVal = info.CallOperandVal;
16982     // If we don't have a value, we can't do a match,
16983     // but allow it at the lowest weight.
16984   if (CallOperandVal == NULL)
16985     return CW_Default;
16986   Type *type = CallOperandVal->getType();
16987   // Look at the constraint type.
16988   switch (*constraint) {
16989   default:
16990     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16991   case 'R':
16992   case 'q':
16993   case 'Q':
16994   case 'a':
16995   case 'b':
16996   case 'c':
16997   case 'd':
16998   case 'S':
16999   case 'D':
17000   case 'A':
17001     if (CallOperandVal->getType()->isIntegerTy())
17002       weight = CW_SpecificReg;
17003     break;
17004   case 'f':
17005   case 't':
17006   case 'u':
17007       if (type->isFloatingPointTy())
17008         weight = CW_SpecificReg;
17009       break;
17010   case 'y':
17011       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17012         weight = CW_SpecificReg;
17013       break;
17014   case 'x':
17015   case 'Y':
17016     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17017         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17018       weight = CW_Register;
17019     break;
17020   case 'I':
17021     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17022       if (C->getZExtValue() <= 31)
17023         weight = CW_Constant;
17024     }
17025     break;
17026   case 'J':
17027     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17028       if (C->getZExtValue() <= 63)
17029         weight = CW_Constant;
17030     }
17031     break;
17032   case 'K':
17033     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17034       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17035         weight = CW_Constant;
17036     }
17037     break;
17038   case 'L':
17039     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17040       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17041         weight = CW_Constant;
17042     }
17043     break;
17044   case 'M':
17045     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17046       if (C->getZExtValue() <= 3)
17047         weight = CW_Constant;
17048     }
17049     break;
17050   case 'N':
17051     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17052       if (C->getZExtValue() <= 0xff)
17053         weight = CW_Constant;
17054     }
17055     break;
17056   case 'G':
17057   case 'C':
17058     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17059       weight = CW_Constant;
17060     }
17061     break;
17062   case 'e':
17063     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17064       if ((C->getSExtValue() >= -0x80000000LL) &&
17065           (C->getSExtValue() <= 0x7fffffffLL))
17066         weight = CW_Constant;
17067     }
17068     break;
17069   case 'Z':
17070     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17071       if (C->getZExtValue() <= 0xffffffff)
17072         weight = CW_Constant;
17073     }
17074     break;
17075   }
17076   return weight;
17077 }
17078
17079 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17080 /// with another that has more specific requirements based on the type of the
17081 /// corresponding operand.
17082 const char *X86TargetLowering::
17083 LowerXConstraint(EVT ConstraintVT) const {
17084   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17085   // 'f' like normal targets.
17086   if (ConstraintVT.isFloatingPoint()) {
17087     if (Subtarget->hasSSE2())
17088       return "Y";
17089     if (Subtarget->hasSSE1())
17090       return "x";
17091   }
17092
17093   return TargetLowering::LowerXConstraint(ConstraintVT);
17094 }
17095
17096 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17097 /// vector.  If it is invalid, don't add anything to Ops.
17098 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17099                                                      std::string &Constraint,
17100                                                      std::vector<SDValue>&Ops,
17101                                                      SelectionDAG &DAG) const {
17102   SDValue Result(0, 0);
17103
17104   // Only support length 1 constraints for now.
17105   if (Constraint.length() > 1) return;
17106
17107   char ConstraintLetter = Constraint[0];
17108   switch (ConstraintLetter) {
17109   default: break;
17110   case 'I':
17111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17112       if (C->getZExtValue() <= 31) {
17113         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17114         break;
17115       }
17116     }
17117     return;
17118   case 'J':
17119     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17120       if (C->getZExtValue() <= 63) {
17121         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17122         break;
17123       }
17124     }
17125     return;
17126   case 'K':
17127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17128       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17129         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17130         break;
17131       }
17132     }
17133     return;
17134   case 'N':
17135     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17136       if (C->getZExtValue() <= 255) {
17137         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17138         break;
17139       }
17140     }
17141     return;
17142   case 'e': {
17143     // 32-bit signed value
17144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17145       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17146                                            C->getSExtValue())) {
17147         // Widen to 64 bits here to get it sign extended.
17148         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17149         break;
17150       }
17151     // FIXME gcc accepts some relocatable values here too, but only in certain
17152     // memory models; it's complicated.
17153     }
17154     return;
17155   }
17156   case 'Z': {
17157     // 32-bit unsigned value
17158     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17159       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17160                                            C->getZExtValue())) {
17161         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17162         break;
17163       }
17164     }
17165     // FIXME gcc accepts some relocatable values here too, but only in certain
17166     // memory models; it's complicated.
17167     return;
17168   }
17169   case 'i': {
17170     // Literal immediates are always ok.
17171     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17172       // Widen to 64 bits here to get it sign extended.
17173       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17174       break;
17175     }
17176
17177     // In any sort of PIC mode addresses need to be computed at runtime by
17178     // adding in a register or some sort of table lookup.  These can't
17179     // be used as immediates.
17180     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17181       return;
17182
17183     // If we are in non-pic codegen mode, we allow the address of a global (with
17184     // an optional displacement) to be used with 'i'.
17185     GlobalAddressSDNode *GA = 0;
17186     int64_t Offset = 0;
17187
17188     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17189     while (1) {
17190       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17191         Offset += GA->getOffset();
17192         break;
17193       } else if (Op.getOpcode() == ISD::ADD) {
17194         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17195           Offset += C->getZExtValue();
17196           Op = Op.getOperand(0);
17197           continue;
17198         }
17199       } else if (Op.getOpcode() == ISD::SUB) {
17200         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17201           Offset += -C->getZExtValue();
17202           Op = Op.getOperand(0);
17203           continue;
17204         }
17205       }
17206
17207       // Otherwise, this isn't something we can handle, reject it.
17208       return;
17209     }
17210
17211     const GlobalValue *GV = GA->getGlobal();
17212     // If we require an extra load to get this address, as in PIC mode, we
17213     // can't accept it.
17214     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17215                                                         getTargetMachine())))
17216       return;
17217
17218     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17219                                         GA->getValueType(0), Offset);
17220     break;
17221   }
17222   }
17223
17224   if (Result.getNode()) {
17225     Ops.push_back(Result);
17226     return;
17227   }
17228   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17229 }
17230
17231 std::pair<unsigned, const TargetRegisterClass*>
17232 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17233                                                 EVT VT) const {
17234   // First, see if this is a constraint that directly corresponds to an LLVM
17235   // register class.
17236   if (Constraint.size() == 1) {
17237     // GCC Constraint Letters
17238     switch (Constraint[0]) {
17239     default: break;
17240       // TODO: Slight differences here in allocation order and leaving
17241       // RIP in the class. Do they matter any more here than they do
17242       // in the normal allocation?
17243     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17244       if (Subtarget->is64Bit()) {
17245         if (VT == MVT::i32 || VT == MVT::f32)
17246           return std::make_pair(0U, &X86::GR32RegClass);
17247         if (VT == MVT::i16)
17248           return std::make_pair(0U, &X86::GR16RegClass);
17249         if (VT == MVT::i8 || VT == MVT::i1)
17250           return std::make_pair(0U, &X86::GR8RegClass);
17251         if (VT == MVT::i64 || VT == MVT::f64)
17252           return std::make_pair(0U, &X86::GR64RegClass);
17253         break;
17254       }
17255       // 32-bit fallthrough
17256     case 'Q':   // Q_REGS
17257       if (VT == MVT::i32 || VT == MVT::f32)
17258         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17259       if (VT == MVT::i16)
17260         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17261       if (VT == MVT::i8 || VT == MVT::i1)
17262         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17263       if (VT == MVT::i64)
17264         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17265       break;
17266     case 'r':   // GENERAL_REGS
17267     case 'l':   // INDEX_REGS
17268       if (VT == MVT::i8 || VT == MVT::i1)
17269         return std::make_pair(0U, &X86::GR8RegClass);
17270       if (VT == MVT::i16)
17271         return std::make_pair(0U, &X86::GR16RegClass);
17272       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17273         return std::make_pair(0U, &X86::GR32RegClass);
17274       return std::make_pair(0U, &X86::GR64RegClass);
17275     case 'R':   // LEGACY_REGS
17276       if (VT == MVT::i8 || VT == MVT::i1)
17277         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17278       if (VT == MVT::i16)
17279         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17280       if (VT == MVT::i32 || !Subtarget->is64Bit())
17281         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17282       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17283     case 'f':  // FP Stack registers.
17284       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17285       // value to the correct fpstack register class.
17286       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17287         return std::make_pair(0U, &X86::RFP32RegClass);
17288       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17289         return std::make_pair(0U, &X86::RFP64RegClass);
17290       return std::make_pair(0U, &X86::RFP80RegClass);
17291     case 'y':   // MMX_REGS if MMX allowed.
17292       if (!Subtarget->hasMMX()) break;
17293       return std::make_pair(0U, &X86::VR64RegClass);
17294     case 'Y':   // SSE_REGS if SSE2 allowed
17295       if (!Subtarget->hasSSE2()) break;
17296       // FALL THROUGH.
17297     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17298       if (!Subtarget->hasSSE1()) break;
17299
17300       switch (VT.getSimpleVT().SimpleTy) {
17301       default: break;
17302       // Scalar SSE types.
17303       case MVT::f32:
17304       case MVT::i32:
17305         return std::make_pair(0U, &X86::FR32RegClass);
17306       case MVT::f64:
17307       case MVT::i64:
17308         return std::make_pair(0U, &X86::FR64RegClass);
17309       // Vector types.
17310       case MVT::v16i8:
17311       case MVT::v8i16:
17312       case MVT::v4i32:
17313       case MVT::v2i64:
17314       case MVT::v4f32:
17315       case MVT::v2f64:
17316         return std::make_pair(0U, &X86::VR128RegClass);
17317       // AVX types.
17318       case MVT::v32i8:
17319       case MVT::v16i16:
17320       case MVT::v8i32:
17321       case MVT::v4i64:
17322       case MVT::v8f32:
17323       case MVT::v4f64:
17324         return std::make_pair(0U, &X86::VR256RegClass);
17325       }
17326       break;
17327     }
17328   }
17329
17330   // Use the default implementation in TargetLowering to convert the register
17331   // constraint into a member of a register class.
17332   std::pair<unsigned, const TargetRegisterClass*> Res;
17333   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17334
17335   // Not found as a standard register?
17336   if (Res.second == 0) {
17337     // Map st(0) -> st(7) -> ST0
17338     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17339         tolower(Constraint[1]) == 's' &&
17340         tolower(Constraint[2]) == 't' &&
17341         Constraint[3] == '(' &&
17342         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17343         Constraint[5] == ')' &&
17344         Constraint[6] == '}') {
17345
17346       Res.first = X86::ST0+Constraint[4]-'0';
17347       Res.second = &X86::RFP80RegClass;
17348       return Res;
17349     }
17350
17351     // GCC allows "st(0)" to be called just plain "st".
17352     if (StringRef("{st}").equals_lower(Constraint)) {
17353       Res.first = X86::ST0;
17354       Res.second = &X86::RFP80RegClass;
17355       return Res;
17356     }
17357
17358     // flags -> EFLAGS
17359     if (StringRef("{flags}").equals_lower(Constraint)) {
17360       Res.first = X86::EFLAGS;
17361       Res.second = &X86::CCRRegClass;
17362       return Res;
17363     }
17364
17365     // 'A' means EAX + EDX.
17366     if (Constraint == "A") {
17367       Res.first = X86::EAX;
17368       Res.second = &X86::GR32_ADRegClass;
17369       return Res;
17370     }
17371     return Res;
17372   }
17373
17374   // Otherwise, check to see if this is a register class of the wrong value
17375   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17376   // turn into {ax},{dx}.
17377   if (Res.second->hasType(VT))
17378     return Res;   // Correct type already, nothing to do.
17379
17380   // All of the single-register GCC register classes map their values onto
17381   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17382   // really want an 8-bit or 32-bit register, map to the appropriate register
17383   // class and return the appropriate register.
17384   if (Res.second == &X86::GR16RegClass) {
17385     if (VT == MVT::i8) {
17386       unsigned DestReg = 0;
17387       switch (Res.first) {
17388       default: break;
17389       case X86::AX: DestReg = X86::AL; break;
17390       case X86::DX: DestReg = X86::DL; break;
17391       case X86::CX: DestReg = X86::CL; break;
17392       case X86::BX: DestReg = X86::BL; break;
17393       }
17394       if (DestReg) {
17395         Res.first = DestReg;
17396         Res.second = &X86::GR8RegClass;
17397       }
17398     } else if (VT == MVT::i32) {
17399       unsigned DestReg = 0;
17400       switch (Res.first) {
17401       default: break;
17402       case X86::AX: DestReg = X86::EAX; break;
17403       case X86::DX: DestReg = X86::EDX; break;
17404       case X86::CX: DestReg = X86::ECX; break;
17405       case X86::BX: DestReg = X86::EBX; break;
17406       case X86::SI: DestReg = X86::ESI; break;
17407       case X86::DI: DestReg = X86::EDI; break;
17408       case X86::BP: DestReg = X86::EBP; break;
17409       case X86::SP: DestReg = X86::ESP; break;
17410       }
17411       if (DestReg) {
17412         Res.first = DestReg;
17413         Res.second = &X86::GR32RegClass;
17414       }
17415     } else if (VT == MVT::i64) {
17416       unsigned DestReg = 0;
17417       switch (Res.first) {
17418       default: break;
17419       case X86::AX: DestReg = X86::RAX; break;
17420       case X86::DX: DestReg = X86::RDX; break;
17421       case X86::CX: DestReg = X86::RCX; break;
17422       case X86::BX: DestReg = X86::RBX; break;
17423       case X86::SI: DestReg = X86::RSI; break;
17424       case X86::DI: DestReg = X86::RDI; break;
17425       case X86::BP: DestReg = X86::RBP; break;
17426       case X86::SP: DestReg = X86::RSP; break;
17427       }
17428       if (DestReg) {
17429         Res.first = DestReg;
17430         Res.second = &X86::GR64RegClass;
17431       }
17432     }
17433   } else if (Res.second == &X86::FR32RegClass ||
17434              Res.second == &X86::FR64RegClass ||
17435              Res.second == &X86::VR128RegClass) {
17436     // Handle references to XMM physical registers that got mapped into the
17437     // wrong class.  This can happen with constraints like {xmm0} where the
17438     // target independent register mapper will just pick the first match it can
17439     // find, ignoring the required type.
17440
17441     if (VT == MVT::f32 || VT == MVT::i32)
17442       Res.second = &X86::FR32RegClass;
17443     else if (VT == MVT::f64 || VT == MVT::i64)
17444       Res.second = &X86::FR64RegClass;
17445     else if (X86::VR128RegClass.hasType(VT))
17446       Res.second = &X86::VR128RegClass;
17447     else if (X86::VR256RegClass.hasType(VT))
17448       Res.second = &X86::VR256RegClass;
17449   }
17450
17451   return Res;
17452 }