Fix an issue of pseudo atomic instruction DAG schedule
[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 "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.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
162   RegInfo = TM.getRegisterInfo();
163   TD = getDataLayout();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom())
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184   // Bypass i32 with i8 on Atom when compiling with O2
185   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186     addBypassSlowDiv(32, 8);
187
188   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189     // Setup Windows compiler runtime calls.
190     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192     setLibcallName(RTLIB::SREM_I64, "_allrem");
193     setLibcallName(RTLIB::UREM_I64, "_aullrem");
194     setLibcallName(RTLIB::MUL_I64, "_allmul");
195     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201     // The _ftol2 runtime function has an unusual calling conv, which
202     // is modeled by a special pseudo-instruction.
203     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207   }
208
209   if (Subtarget->isTargetDarwin()) {
210     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211     setUseUnderscoreSetJmp(false);
212     setUseUnderscoreLongJmp(false);
213   } else if (Subtarget->isTargetMingw()) {
214     // MS runtime is weird: it exports _setjmp, but longjmp!
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(false);
217   } else {
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(true);
220   }
221
222   // Set up the register classes.
223   addRegisterClass(MVT::i8, &X86::GR8RegClass);
224   addRegisterClass(MVT::i16, &X86::GR16RegClass);
225   addRegisterClass(MVT::i32, &X86::GR32RegClass);
226   if (Subtarget->is64Bit())
227     addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231   // We don't accept any truncstore of integer registers.
232   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239   // SETOEQ and SETUNE require checking two conditions.
240   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248   // operation.
249   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253   if (Subtarget->is64Bit()) {
254     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256   } else if (!TM.Options.UseSoftFloat) {
257     // We have an algorithm for SSE2->double, and we turn this into a
258     // 64-bit FILD followed by conditional FADD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260     // We have an algorithm for SSE2, and we turn this into a 64-bit
261     // FILD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263   }
264
265   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266   // this operation.
267   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270   if (!TM.Options.UseSoftFloat) {
271     // SSE has no i16 to fp conversion, only i32
272     if (X86ScalarSSEf32) {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274       // f32 and f64 cases are Legal, f80 case is not
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     } else {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     }
280   } else {
281     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283   }
284
285   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286   // are Legal, f80 is custom lowered.
287   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291   // this operation.
292   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295   if (X86ScalarSSEf32) {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297     // f32 and f64 cases are Legal, f80 case is not
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   } else {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   }
303
304   // Handle FP_TO_UINT by promoting the destination to a larger signed
305   // conversion.
306   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310   if (Subtarget->is64Bit()) {
311     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313   } else if (!TM.Options.UseSoftFloat) {
314     // Since AVX is a superset of SSE3, only check for SSE here.
315     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   if (isTargetFTOL()) {
327     // Use the _ftol2 runtime function, which has a pseudo-instruction
328     // to handle its weird calling convention.
329     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330   }
331
332   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333   if (!X86ScalarSSEf64) {
334     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336     if (Subtarget->is64Bit()) {
337       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338       // Without SSE, i64->f64 goes through memory.
339       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340     }
341   }
342
343   // Scalar integer divide and remainder are lowered to use operations that
344   // produce two results, to match the available instructions. This exposes
345   // the two-result form to trivial CSE, which is able to combine x/y and x%y
346   // into a single instruction.
347   //
348   // Scalar integer multiply-high is also lowered to use two-result
349   // operations, to match the available instructions. However, plain multiply
350   // (low) operations are left as Legal, as there are single-result
351   // instructions for this in x86. Using the two-result multiply instructions
352   // when both high and low results are needed must be arranged by dagcombine.
353   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354     MVT VT = IntVTs[i];
355     setOperationAction(ISD::MULHS, VT, Expand);
356     setOperationAction(ISD::MULHU, VT, Expand);
357     setOperationAction(ISD::SDIV, VT, Expand);
358     setOperationAction(ISD::UDIV, VT, Expand);
359     setOperationAction(ISD::SREM, VT, Expand);
360     setOperationAction(ISD::UREM, VT, Expand);
361
362     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363     setOperationAction(ISD::ADDC, VT, Custom);
364     setOperationAction(ISD::ADDE, VT, Custom);
365     setOperationAction(ISD::SUBC, VT, Custom);
366     setOperationAction(ISD::SUBE, VT, Custom);
367   }
368
369   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373   if (Subtarget->is64Bit())
374     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384   // Promote the i8 variants and force them on up to i32 which has a shorter
385   // encoding.
386   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390   if (Subtarget->hasBMI()) {
391     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395   } else {
396     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasLZCNT()) {
403     // When promoting the i8 variants, force them to i32 for a shorter
404     // encoding.
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411     if (Subtarget->is64Bit())
412       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413   } else {
414     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420     if (Subtarget->is64Bit()) {
421       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423     }
424   }
425
426   if (Subtarget->hasPOPCNT()) {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428   } else {
429     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432     if (Subtarget->is64Bit())
433       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434   }
435
436   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439   // These should be promoted to a larger select which is supported.
440   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441   // X86 wants to expand cmov itself.
442   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454   if (Subtarget->is64Bit()) {
455     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457   }
458   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461   // support continuation, user-level threading, and etc.. As a result, no
462   // other SjLj exception interfaces are implemented and please don't build
463   // your own exception handling based on them.
464   // LLVM/Clang supports zero-cost DWARF exception handling.
465   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468   // Darwin ABI issue.
469   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473   if (Subtarget->is64Bit())
474     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483   }
484   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasSSE1())
495     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500   // On X86 and X86-64, atomic operations are lowered to locked instructions.
501   // Locked instructions, in turn, have implicit fence semantics (all memory
502   // operations are flushed before issuing the locked instruction, and they
503   // are not buffered), so we can fold away the common pattern of
504   // fence-atomic-fence.
505   setShouldFoldAtomicFences(true);
506
507   // Expand certain atomics
508   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509     MVT VT = IntVTs[i];
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513   }
514
515   if (!Subtarget->is64Bit()) {
516     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528   }
529
530   if (Subtarget->hasCmpxchg16b()) {
531     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532   }
533
534   // FIXME - use subtarget debug flags
535   if (!Subtarget->isTargetDarwin() &&
536       !Subtarget->isTargetELF() &&
537       !Subtarget->isTargetCygMing()) {
538     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539   }
540
541   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545   if (Subtarget->is64Bit()) {
546     setExceptionPointerRegister(X86::RAX);
547     setExceptionSelectorRegister(X86::RDX);
548   } else {
549     setExceptionPointerRegister(X86::EAX);
550     setExceptionSelectorRegister(X86::EDX);
551   }
552   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730     MVT VT = (MVT::SimpleValueType)i;
731     setOperationAction(ISD::ADD , VT, Expand);
732     setOperationAction(ISD::SUB , VT, Expand);
733     setOperationAction(ISD::FADD, VT, Expand);
734     setOperationAction(ISD::FNEG, VT, Expand);
735     setOperationAction(ISD::FSUB, VT, Expand);
736     setOperationAction(ISD::MUL , VT, Expand);
737     setOperationAction(ISD::FMUL, VT, Expand);
738     setOperationAction(ISD::SDIV, VT, Expand);
739     setOperationAction(ISD::UDIV, VT, Expand);
740     setOperationAction(ISD::FDIV, VT, Expand);
741     setOperationAction(ISD::SREM, VT, Expand);
742     setOperationAction(ISD::UREM, VT, Expand);
743     setOperationAction(ISD::LOAD, VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749     setOperationAction(ISD::FABS, VT, Expand);
750     setOperationAction(ISD::FSIN, VT, Expand);
751     setOperationAction(ISD::FCOS, VT, Expand);
752     setOperationAction(ISD::FREM, VT, Expand);
753     setOperationAction(ISD::FMA,  VT, Expand);
754     setOperationAction(ISD::FPOWI, VT, Expand);
755     setOperationAction(ISD::FSQRT, VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757     setOperationAction(ISD::FFLOOR, VT, Expand);
758     setOperationAction(ISD::FCEIL, VT, Expand);
759     setOperationAction(ISD::FTRUNC, VT, Expand);
760     setOperationAction(ISD::FRINT, VT, Expand);
761     setOperationAction(ISD::FNEARBYINT, VT, Expand);
762     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::SDIVREM, VT, Expand);
765     setOperationAction(ISD::UDIVREM, VT, Expand);
766     setOperationAction(ISD::FPOW, VT, Expand);
767     setOperationAction(ISD::CTPOP, VT, Expand);
768     setOperationAction(ISD::CTTZ, VT, Expand);
769     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770     setOperationAction(ISD::CTLZ, VT, Expand);
771     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772     setOperationAction(ISD::SHL, VT, Expand);
773     setOperationAction(ISD::SRA, VT, Expand);
774     setOperationAction(ISD::SRL, VT, Expand);
775     setOperationAction(ISD::ROTL, VT, Expand);
776     setOperationAction(ISD::ROTR, VT, Expand);
777     setOperationAction(ISD::BSWAP, VT, Expand);
778     setOperationAction(ISD::SETCC, VT, Expand);
779     setOperationAction(ISD::FLOG, VT, Expand);
780     setOperationAction(ISD::FLOG2, VT, Expand);
781     setOperationAction(ISD::FLOG10, VT, Expand);
782     setOperationAction(ISD::FEXP, VT, Expand);
783     setOperationAction(ISD::FEXP2, VT, Expand);
784     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789     setOperationAction(ISD::TRUNCATE, VT, Expand);
790     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793     setOperationAction(ISD::VSELECT, VT, Expand);
794     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796       setTruncStoreAction(VT,
797                           (MVT::SimpleValueType)InnerVT, Expand);
798     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801   }
802
803   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804   // with -msoft-float, disable use of MMX as well.
805   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807     // No operations on x86mmx supported, everything uses intrinsics.
808   }
809
810   // MMX-sized vectors (other than x86mmx) are expected to be expanded
811   // into smaller operations.
812   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857   }
858
859   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863     // registers cannot be used even for integer operations.
864     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
874     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
875     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
876     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
877     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
878     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
879     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
880     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
881     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
882     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
883     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
884     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
885     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
886     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
887
888     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
889     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
890     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
891     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
892
893     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
895     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
898
899     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901       MVT VT = (MVT::SimpleValueType)i;
902       // Do not attempt to custom lower non-power-of-2 vectors
903       if (!isPowerOf2_32(VT.getVectorNumElements()))
904         continue;
905       // Do not attempt to custom lower non-128-bit vectors
906       if (!VT.is128BitVector())
907         continue;
908       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911     }
912
913     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919
920     if (Subtarget->is64Bit()) {
921       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
922       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
923     }
924
925     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927       MVT VT = (MVT::SimpleValueType)i;
928
929       // Do not attempt to promote non-128-bit vectors
930       if (!VT.is128BitVector())
931         continue;
932
933       setOperationAction(ISD::AND,    VT, Promote);
934       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
935       setOperationAction(ISD::OR,     VT, Promote);
936       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
937       setOperationAction(ISD::XOR,    VT, Promote);
938       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
939       setOperationAction(ISD::LOAD,   VT, Promote);
940       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
941       setOperationAction(ISD::SELECT, VT, Promote);
942       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
943     }
944
945     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946
947     // Custom lower v2i64 and v2f64 selects.
948     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
950     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
951     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
952
953     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
954     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
955
956     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
957     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
958     // As there is no 64-bit GPR available, we need build a special custom
959     // sequence to convert from v2i32 to v2f32.
960     if (!Subtarget->is64Bit())
961       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
962
963     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
964     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
965
966     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
967   }
968
969   if (Subtarget->hasSSE41()) {
970     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
971     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
972     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
973     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
974     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
975     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
976     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
977     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
978     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
979     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
980
981     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
982     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
983     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
984     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
985     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
986     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
987     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
988     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
989     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
990     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
991
992     // FIXME: Do we need to handle scalar-to-vector here?
993     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
994
995     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
996     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
997     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
998     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
999     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1000
1001     // i8 and i16 vectors are custom , because the source register and source
1002     // source memory operand types are not the same width.  f32 vectors are
1003     // custom since the immediate controlling the insert encodes additional
1004     // information.
1005     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015     // FIXME: these should be Legal but thats only for the case where
1016     // the index is constant.  For now custom expand to deal with that.
1017     if (Subtarget->is64Bit()) {
1018       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020     }
1021   }
1022
1023   if (Subtarget->hasSSE2()) {
1024     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1029
1030     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1031     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1032
1033     if (Subtarget->hasInt256()) {
1034       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1035       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1036
1037       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1038       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1039
1040       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1041     } else {
1042       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1043       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1044
1045       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1046       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1047
1048       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1049     }
1050     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1051     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1052   }
1053
1054   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1055     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1057     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1059     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1060     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1061
1062     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1065
1066     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1069     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1070     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1076     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1077     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1078
1079     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1082     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1083     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1087     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1088     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1089     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1090     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1091
1092     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1093     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1094
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1096
1097     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1098     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1102     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1103     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1104
1105     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1106
1107     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1117
1118     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1119     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1120     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1121     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1122
1123     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1124     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1125     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1126
1127     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1128     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1129     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1130     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1131
1132     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1133     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1134     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1135     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1136     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1137     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1138
1139     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1140       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1141       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1142       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1143       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1144       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1145       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1146     }
1147
1148     if (Subtarget->hasInt256()) {
1149       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1150       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1153
1154       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1155       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1156       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1157       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1158
1159       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1160       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1161       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1162       // Don't lower v32i8 because there is no 128-bit byte mul
1163
1164       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1165
1166       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1167       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1168
1169       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1170       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1171
1172       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1173
1174       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1175     } else {
1176       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1185
1186       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1188       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1189       // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1193
1194       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1196
1197       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1198     }
1199
1200     // Custom lower several nodes for 256-bit types.
1201     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1202              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1203       MVT VT = (MVT::SimpleValueType)i;
1204
1205       // Extract subvector is special because the value type
1206       // (result) is 128-bit but the source is 256-bit wide.
1207       if (VT.is128BitVector())
1208         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1209
1210       // Do not attempt to custom lower other non-256-bit vectors
1211       if (!VT.is256BitVector())
1212         continue;
1213
1214       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1215       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1216       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1217       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1218       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1219       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1220       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1221     }
1222
1223     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1224     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1225       MVT VT = (MVT::SimpleValueType)i;
1226
1227       // Do not attempt to promote non-256-bit vectors
1228       if (!VT.is256BitVector())
1229         continue;
1230
1231       setOperationAction(ISD::AND,    VT, Promote);
1232       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1233       setOperationAction(ISD::OR,     VT, Promote);
1234       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1235       setOperationAction(ISD::XOR,    VT, Promote);
1236       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1237       setOperationAction(ISD::LOAD,   VT, Promote);
1238       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1239       setOperationAction(ISD::SELECT, VT, Promote);
1240       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1241     }
1242   }
1243
1244   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1245   // of this type with custom code.
1246   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1247            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1248     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1249                        Custom);
1250   }
1251
1252   // We want to custom lower some of our intrinsics.
1253   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1254   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1255
1256   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1257   // handle type legalization for these operations here.
1258   //
1259   // FIXME: We really should do custom legalization for addition and
1260   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1261   // than generic legalization for 64-bit multiplication-with-overflow, though.
1262   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1263     // Add/Sub/Mul with overflow operations are custom lowered.
1264     MVT VT = IntVTs[i];
1265     setOperationAction(ISD::SADDO, VT, Custom);
1266     setOperationAction(ISD::UADDO, VT, Custom);
1267     setOperationAction(ISD::SSUBO, VT, Custom);
1268     setOperationAction(ISD::USUBO, VT, Custom);
1269     setOperationAction(ISD::SMULO, VT, Custom);
1270     setOperationAction(ISD::UMULO, VT, Custom);
1271   }
1272
1273   // There are no 8-bit 3-address imul/mul instructions
1274   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1275   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1276
1277   if (!Subtarget->is64Bit()) {
1278     // These libcalls are not available in 32-bit.
1279     setLibcallName(RTLIB::SHL_I128, 0);
1280     setLibcallName(RTLIB::SRL_I128, 0);
1281     setLibcallName(RTLIB::SRA_I128, 0);
1282   }
1283
1284   // We have target-specific dag combine patterns for the following nodes:
1285   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1286   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1287   setTargetDAGCombine(ISD::VSELECT);
1288   setTargetDAGCombine(ISD::SELECT);
1289   setTargetDAGCombine(ISD::SHL);
1290   setTargetDAGCombine(ISD::SRA);
1291   setTargetDAGCombine(ISD::SRL);
1292   setTargetDAGCombine(ISD::OR);
1293   setTargetDAGCombine(ISD::AND);
1294   setTargetDAGCombine(ISD::ADD);
1295   setTargetDAGCombine(ISD::FADD);
1296   setTargetDAGCombine(ISD::FSUB);
1297   setTargetDAGCombine(ISD::FMA);
1298   setTargetDAGCombine(ISD::SUB);
1299   setTargetDAGCombine(ISD::LOAD);
1300   setTargetDAGCombine(ISD::STORE);
1301   setTargetDAGCombine(ISD::ZERO_EXTEND);
1302   setTargetDAGCombine(ISD::ANY_EXTEND);
1303   setTargetDAGCombine(ISD::SIGN_EXTEND);
1304   setTargetDAGCombine(ISD::TRUNCATE);
1305   setTargetDAGCombine(ISD::SINT_TO_FP);
1306   setTargetDAGCombine(ISD::SETCC);
1307   if (Subtarget->is64Bit())
1308     setTargetDAGCombine(ISD::MUL);
1309   setTargetDAGCombine(ISD::XOR);
1310
1311   computeRegisterProperties();
1312
1313   // On Darwin, -Os means optimize for size without hurting performance,
1314   // do not reduce the limit.
1315   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1316   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1317   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1318   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1319   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1320   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1321   setPrefLoopAlignment(4); // 2^4 bytes.
1322   benefitFromCodePlacementOpt = true;
1323
1324   // Predictable cmov don't hurt on atom because it's in-order.
1325   predictableSelectIsExpensive = !Subtarget->isAtom();
1326
1327   setPrefFunctionAlignment(4); // 2^4 bytes.
1328 }
1329
1330 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1331   if (!VT.isVector()) return MVT::i8;
1332   return VT.changeVectorElementTypeToInteger();
1333 }
1334
1335 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336 /// the desired ByVal argument alignment.
1337 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1338   if (MaxAlign == 16)
1339     return;
1340   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341     if (VTy->getBitWidth() == 128)
1342       MaxAlign = 16;
1343   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1344     unsigned EltAlign = 0;
1345     getMaxByValAlign(ATy->getElementType(), EltAlign);
1346     if (EltAlign > MaxAlign)
1347       MaxAlign = EltAlign;
1348   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1349     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1350       unsigned EltAlign = 0;
1351       getMaxByValAlign(STy->getElementType(i), EltAlign);
1352       if (EltAlign > MaxAlign)
1353         MaxAlign = EltAlign;
1354       if (MaxAlign == 16)
1355         break;
1356     }
1357   }
1358 }
1359
1360 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1361 /// function arguments in the caller parameter area. For X86, aggregates
1362 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1363 /// are at 4-byte boundaries.
1364 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1365   if (Subtarget->is64Bit()) {
1366     // Max of 8 and alignment of type.
1367     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1368     if (TyAlign > 8)
1369       return TyAlign;
1370     return 8;
1371   }
1372
1373   unsigned Align = 4;
1374   if (Subtarget->hasSSE1())
1375     getMaxByValAlign(Ty, Align);
1376   return Align;
1377 }
1378
1379 /// getOptimalMemOpType - Returns the target specific optimal type for load
1380 /// and store operations as a result of memset, memcpy, and memmove
1381 /// lowering. If DstAlign is zero that means it's safe to destination
1382 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1383 /// means there isn't a need to check it against alignment requirement,
1384 /// probably because the source does not need to be loaded. If 'IsMemset' is
1385 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1386 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1387 /// source is constant so it does not need to be loaded.
1388 /// It returns EVT::Other if the type should be determined using generic
1389 /// target-independent logic.
1390 EVT
1391 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1392                                        unsigned DstAlign, unsigned SrcAlign,
1393                                        bool IsMemset, bool ZeroMemset,
1394                                        bool MemcpyStrSrc,
1395                                        MachineFunction &MF) const {
1396   const Function *F = MF.getFunction();
1397   if ((!IsMemset || ZeroMemset) &&
1398       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1399                                        Attribute::NoImplicitFloat)) {
1400     if (Size >= 16 &&
1401         (Subtarget->isUnalignedMemAccessFast() ||
1402          ((DstAlign == 0 || DstAlign >= 16) &&
1403           (SrcAlign == 0 || SrcAlign >= 16)))) {
1404       if (Size >= 32) {
1405         if (Subtarget->hasInt256())
1406           return MVT::v8i32;
1407         if (Subtarget->hasFp256())
1408           return MVT::v8f32;
1409       }
1410       if (Subtarget->hasSSE2())
1411         return MVT::v4i32;
1412       if (Subtarget->hasSSE1())
1413         return MVT::v4f32;
1414     } else if (!MemcpyStrSrc && Size >= 8 &&
1415                !Subtarget->is64Bit() &&
1416                Subtarget->hasSSE2()) {
1417       // Do not use f64 to lower memcpy if source is string constant. It's
1418       // better to use i32 to avoid the loads.
1419       return MVT::f64;
1420     }
1421   }
1422   if (Subtarget->is64Bit() && Size >= 8)
1423     return MVT::i64;
1424   return MVT::i32;
1425 }
1426
1427 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1428   if (VT == MVT::f32)
1429     return X86ScalarSSEf32;
1430   else if (VT == MVT::f64)
1431     return X86ScalarSSEf64;
1432   return true;
1433 }
1434
1435 bool
1436 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1437   if (Fast)
1438     *Fast = Subtarget->isUnalignedMemAccessFast();
1439   return true;
1440 }
1441
1442 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1443 /// current function.  The returned value is a member of the
1444 /// MachineJumpTableInfo::JTEntryKind enum.
1445 unsigned X86TargetLowering::getJumpTableEncoding() const {
1446   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1447   // symbol.
1448   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449       Subtarget->isPICStyleGOT())
1450     return MachineJumpTableInfo::EK_Custom32;
1451
1452   // Otherwise, use the normal jump table encoding heuristics.
1453   return TargetLowering::getJumpTableEncoding();
1454 }
1455
1456 const MCExpr *
1457 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1458                                              const MachineBasicBlock *MBB,
1459                                              unsigned uid,MCContext &Ctx) const{
1460   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1461          Subtarget->isPICStyleGOT());
1462   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1463   // entries.
1464   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1465                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1466 }
1467
1468 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1469 /// jumptable.
1470 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1471                                                     SelectionDAG &DAG) const {
1472   if (!Subtarget->is64Bit())
1473     // This doesn't have DebugLoc associated with it, but is not really the
1474     // same as a Register.
1475     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1476   return Table;
1477 }
1478
1479 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1480 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1481 /// MCExpr.
1482 const MCExpr *X86TargetLowering::
1483 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1484                              MCContext &Ctx) const {
1485   // X86-64 uses RIP relative addressing based on the jump table label.
1486   if (Subtarget->isPICStyleRIPRel())
1487     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1488
1489   // Otherwise, the reference is relative to the PIC base.
1490   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1491 }
1492
1493 // FIXME: Why this routine is here? Move to RegInfo!
1494 std::pair<const TargetRegisterClass*, uint8_t>
1495 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1496   const TargetRegisterClass *RRC = 0;
1497   uint8_t Cost = 1;
1498   switch (VT.SimpleTy) {
1499   default:
1500     return TargetLowering::findRepresentativeClass(VT);
1501   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1502     RRC = Subtarget->is64Bit() ?
1503       (const TargetRegisterClass*)&X86::GR64RegClass :
1504       (const TargetRegisterClass*)&X86::GR32RegClass;
1505     break;
1506   case MVT::x86mmx:
1507     RRC = &X86::VR64RegClass;
1508     break;
1509   case MVT::f32: case MVT::f64:
1510   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511   case MVT::v4f32: case MVT::v2f64:
1512   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1513   case MVT::v4f64:
1514     RRC = &X86::VR128RegClass;
1515     break;
1516   }
1517   return std::make_pair(RRC, Cost);
1518 }
1519
1520 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1521                                                unsigned &Offset) const {
1522   if (!Subtarget->isTargetLinux())
1523     return false;
1524
1525   if (Subtarget->is64Bit()) {
1526     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1527     Offset = 0x28;
1528     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1529       AddressSpace = 256;
1530     else
1531       AddressSpace = 257;
1532   } else {
1533     // %gs:0x14 on i386
1534     Offset = 0x14;
1535     AddressSpace = 256;
1536   }
1537   return true;
1538 }
1539
1540 //===----------------------------------------------------------------------===//
1541 //               Return Value Calling Convention Implementation
1542 //===----------------------------------------------------------------------===//
1543
1544 #include "X86GenCallingConv.inc"
1545
1546 bool
1547 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1548                                   MachineFunction &MF, bool isVarArg,
1549                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1550                         LLVMContext &Context) const {
1551   SmallVector<CCValAssign, 16> RVLocs;
1552   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553                  RVLocs, Context);
1554   return CCInfo.CheckReturn(Outs, RetCC_X86);
1555 }
1556
1557 SDValue
1558 X86TargetLowering::LowerReturn(SDValue Chain,
1559                                CallingConv::ID CallConv, bool isVarArg,
1560                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1561                                const SmallVectorImpl<SDValue> &OutVals,
1562                                DebugLoc dl, SelectionDAG &DAG) const {
1563   MachineFunction &MF = DAG.getMachineFunction();
1564   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1565
1566   SmallVector<CCValAssign, 16> RVLocs;
1567   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1568                  RVLocs, *DAG.getContext());
1569   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1570
1571   // Add the regs to the liveout set for the function.
1572   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1573   for (unsigned i = 0; i != RVLocs.size(); ++i)
1574     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1575       MRI.addLiveOut(RVLocs[i].getLocReg());
1576
1577   SDValue Flag;
1578
1579   SmallVector<SDValue, 6> RetOps;
1580   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1581   // Operand #1 = Bytes To Pop
1582   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1583                    MVT::i16));
1584
1585   // Copy the result values into the output registers.
1586   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1587     CCValAssign &VA = RVLocs[i];
1588     assert(VA.isRegLoc() && "Can only return in registers!");
1589     SDValue ValToCopy = OutVals[i];
1590     EVT ValVT = ValToCopy.getValueType();
1591
1592     // Promote values to the appropriate types
1593     if (VA.getLocInfo() == CCValAssign::SExt)
1594       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1595     else if (VA.getLocInfo() == CCValAssign::ZExt)
1596       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1597     else if (VA.getLocInfo() == CCValAssign::AExt)
1598       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1599     else if (VA.getLocInfo() == CCValAssign::BCvt)
1600       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1601
1602     // If this is x86-64, and we disabled SSE, we can't return FP values,
1603     // or SSE or MMX vectors.
1604     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1605          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1606           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1607       report_fatal_error("SSE register return with SSE disabled");
1608     }
1609     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1610     // llvm-gcc has never done it right and no one has noticed, so this
1611     // should be OK for now.
1612     if (ValVT == MVT::f64 &&
1613         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1614       report_fatal_error("SSE2 register return with SSE2 disabled");
1615
1616     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1617     // the RET instruction and handled by the FP Stackifier.
1618     if (VA.getLocReg() == X86::ST0 ||
1619         VA.getLocReg() == X86::ST1) {
1620       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1621       // change the value to the FP stack register class.
1622       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1623         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1624       RetOps.push_back(ValToCopy);
1625       // Don't emit a copytoreg.
1626       continue;
1627     }
1628
1629     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1630     // which is returned in RAX / RDX.
1631     if (Subtarget->is64Bit()) {
1632       if (ValVT == MVT::x86mmx) {
1633         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1634           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1635           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1636                                   ValToCopy);
1637           // If we don't have SSE2 available, convert to v4f32 so the generated
1638           // register is legal.
1639           if (!Subtarget->hasSSE2())
1640             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1641         }
1642       }
1643     }
1644
1645     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1646     Flag = Chain.getValue(1);
1647   }
1648
1649   // The x86-64 ABI for returning structs by value requires that we copy
1650   // the sret argument into %rax for the return. We saved the argument into
1651   // a virtual register in the entry block, so now we copy the value out
1652   // and into %rax.
1653   if (Subtarget->is64Bit() &&
1654       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1655     MachineFunction &MF = DAG.getMachineFunction();
1656     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657     unsigned Reg = FuncInfo->getSRetReturnReg();
1658     assert(Reg &&
1659            "SRetReturnReg should have been set in LowerFormalArguments().");
1660     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1661
1662     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1663     Flag = Chain.getValue(1);
1664
1665     // RAX now acts like a return value.
1666     MRI.addLiveOut(X86::RAX);
1667   }
1668
1669   RetOps[0] = Chain;  // Update chain.
1670
1671   // Add the flag if we have it.
1672   if (Flag.getNode())
1673     RetOps.push_back(Flag);
1674
1675   return DAG.getNode(X86ISD::RET_FLAG, dl,
1676                      MVT::Other, &RetOps[0], RetOps.size());
1677 }
1678
1679 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1680   if (N->getNumValues() != 1)
1681     return false;
1682   if (!N->hasNUsesOfValue(1, 0))
1683     return false;
1684
1685   SDValue TCChain = Chain;
1686   SDNode *Copy = *N->use_begin();
1687   if (Copy->getOpcode() == ISD::CopyToReg) {
1688     // If the copy has a glue operand, we conservatively assume it isn't safe to
1689     // perform a tail call.
1690     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1691       return false;
1692     TCChain = Copy->getOperand(0);
1693   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1694     return false;
1695
1696   bool HasRet = false;
1697   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1698        UI != UE; ++UI) {
1699     if (UI->getOpcode() != X86ISD::RET_FLAG)
1700       return false;
1701     HasRet = true;
1702   }
1703
1704   if (!HasRet)
1705     return false;
1706
1707   Chain = TCChain;
1708   return true;
1709 }
1710
1711 MVT
1712 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1713                                             ISD::NodeType ExtendKind) const {
1714   MVT ReturnMVT;
1715   // TODO: Is this also valid on 32-bit?
1716   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1717     ReturnMVT = MVT::i8;
1718   else
1719     ReturnMVT = MVT::i32;
1720
1721   MVT MinVT = getRegisterType(ReturnMVT);
1722   return VT.bitsLT(MinVT) ? MinVT : VT;
1723 }
1724
1725 /// LowerCallResult - Lower the result values of a call into the
1726 /// appropriate copies out of appropriate physical registers.
1727 ///
1728 SDValue
1729 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1730                                    CallingConv::ID CallConv, bool isVarArg,
1731                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1732                                    DebugLoc dl, SelectionDAG &DAG,
1733                                    SmallVectorImpl<SDValue> &InVals) const {
1734
1735   // Assign locations to each value returned by this call.
1736   SmallVector<CCValAssign, 16> RVLocs;
1737   bool Is64Bit = Subtarget->is64Bit();
1738   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1739                  getTargetMachine(), RVLocs, *DAG.getContext());
1740   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1741
1742   // Copy all of the result registers out of their specified physreg.
1743   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1744     CCValAssign &VA = RVLocs[i];
1745     EVT CopyVT = VA.getValVT();
1746
1747     // If this is x86-64, and we disabled SSE, we can't return FP values
1748     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1749         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1750       report_fatal_error("SSE register return with SSE disabled");
1751     }
1752
1753     SDValue Val;
1754
1755     // If this is a call to a function that returns an fp value on the floating
1756     // point stack, we must guarantee the value is popped from the stack, so
1757     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1758     // if the return value is not used. We use the FpPOP_RETVAL instruction
1759     // instead.
1760     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1761       // If we prefer to use the value in xmm registers, copy it out as f80 and
1762       // use a truncate to move it from fp stack reg to xmm reg.
1763       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1764       SDValue Ops[] = { Chain, InFlag };
1765       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1766                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1767       Val = Chain.getValue(0);
1768
1769       // Round the f80 to the right size, which also moves it to the appropriate
1770       // xmm register.
1771       if (CopyVT != VA.getValVT())
1772         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1773                           // This truncation won't change the value.
1774                           DAG.getIntPtrConstant(1));
1775     } else {
1776       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1777                                  CopyVT, InFlag).getValue(1);
1778       Val = Chain.getValue(0);
1779     }
1780     InFlag = Chain.getValue(2);
1781     InVals.push_back(Val);
1782   }
1783
1784   return Chain;
1785 }
1786
1787 //===----------------------------------------------------------------------===//
1788 //                C & StdCall & Fast Calling Convention implementation
1789 //===----------------------------------------------------------------------===//
1790 //  StdCall calling convention seems to be standard for many Windows' API
1791 //  routines and around. It differs from C calling convention just a little:
1792 //  callee should clean up the stack, not caller. Symbols should be also
1793 //  decorated in some fancy way :) It doesn't support any vector arguments.
1794 //  For info on fast calling convention see Fast Calling Convention (tail call)
1795 //  implementation LowerX86_32FastCCCallTo.
1796
1797 /// CallIsStructReturn - Determines whether a call uses struct return
1798 /// semantics.
1799 enum StructReturnType {
1800   NotStructReturn,
1801   RegStructReturn,
1802   StackStructReturn
1803 };
1804 static StructReturnType
1805 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1806   if (Outs.empty())
1807     return NotStructReturn;
1808
1809   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1810   if (!Flags.isSRet())
1811     return NotStructReturn;
1812   if (Flags.isInReg())
1813     return RegStructReturn;
1814   return StackStructReturn;
1815 }
1816
1817 /// ArgsAreStructReturn - Determines whether a function uses struct
1818 /// return semantics.
1819 static StructReturnType
1820 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1821   if (Ins.empty())
1822     return NotStructReturn;
1823
1824   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1825   if (!Flags.isSRet())
1826     return NotStructReturn;
1827   if (Flags.isInReg())
1828     return RegStructReturn;
1829   return StackStructReturn;
1830 }
1831
1832 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1833 /// by "Src" to address "Dst" with size and alignment information specified by
1834 /// the specific parameter attribute. The copy will be passed as a byval
1835 /// function parameter.
1836 static SDValue
1837 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1838                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1839                           DebugLoc dl) {
1840   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1841
1842   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1843                        /*isVolatile*/false, /*AlwaysInline=*/true,
1844                        MachinePointerInfo(), MachinePointerInfo());
1845 }
1846
1847 /// IsTailCallConvention - Return true if the calling convention is one that
1848 /// supports tail call optimization.
1849 static bool IsTailCallConvention(CallingConv::ID CC) {
1850   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1851           CC == CallingConv::HiPE);
1852 }
1853
1854 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1855   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1856     return false;
1857
1858   CallSite CS(CI);
1859   CallingConv::ID CalleeCC = CS.getCallingConv();
1860   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1861     return false;
1862
1863   return true;
1864 }
1865
1866 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1867 /// a tailcall target by changing its ABI.
1868 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1869                                    bool GuaranteedTailCallOpt) {
1870   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1871 }
1872
1873 SDValue
1874 X86TargetLowering::LowerMemArgument(SDValue Chain,
1875                                     CallingConv::ID CallConv,
1876                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1877                                     DebugLoc dl, SelectionDAG &DAG,
1878                                     const CCValAssign &VA,
1879                                     MachineFrameInfo *MFI,
1880                                     unsigned i) const {
1881   // Create the nodes corresponding to a load from this parameter slot.
1882   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1883   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1884                               getTargetMachine().Options.GuaranteedTailCallOpt);
1885   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1886   EVT ValVT;
1887
1888   // If value is passed by pointer we have address passed instead of the value
1889   // itself.
1890   if (VA.getLocInfo() == CCValAssign::Indirect)
1891     ValVT = VA.getLocVT();
1892   else
1893     ValVT = VA.getValVT();
1894
1895   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1896   // changed with more analysis.
1897   // In case of tail call optimization mark all arguments mutable. Since they
1898   // could be overwritten by lowering of arguments in case of a tail call.
1899   if (Flags.isByVal()) {
1900     unsigned Bytes = Flags.getByValSize();
1901     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1902     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1903     return DAG.getFrameIndex(FI, getPointerTy());
1904   } else {
1905     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1906                                     VA.getLocMemOffset(), isImmutable);
1907     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1908     return DAG.getLoad(ValVT, dl, Chain, FIN,
1909                        MachinePointerInfo::getFixedStack(FI),
1910                        false, false, false, 0);
1911   }
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1916                                         CallingConv::ID CallConv,
1917                                         bool isVarArg,
1918                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1919                                         DebugLoc dl,
1920                                         SelectionDAG &DAG,
1921                                         SmallVectorImpl<SDValue> &InVals)
1922                                           const {
1923   MachineFunction &MF = DAG.getMachineFunction();
1924   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925
1926   const Function* Fn = MF.getFunction();
1927   if (Fn->hasExternalLinkage() &&
1928       Subtarget->isTargetCygMing() &&
1929       Fn->getName() == "main")
1930     FuncInfo->setForceFramePointer(true);
1931
1932   MachineFrameInfo *MFI = MF.getFrameInfo();
1933   bool Is64Bit = Subtarget->is64Bit();
1934   bool IsWindows = Subtarget->isTargetWindows();
1935   bool IsWin64 = Subtarget->isTargetWin64();
1936
1937   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1938          "Var args not supported with calling convention fastcc, ghc or hipe");
1939
1940   // Assign locations to all of the incoming arguments.
1941   SmallVector<CCValAssign, 16> ArgLocs;
1942   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1943                  ArgLocs, *DAG.getContext());
1944
1945   // Allocate shadow area for Win64
1946   if (IsWin64) {
1947     CCInfo.AllocateStack(32, 8);
1948   }
1949
1950   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1951
1952   unsigned LastVal = ~0U;
1953   SDValue ArgValue;
1954   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = ArgLocs[i];
1956     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1957     // places.
1958     assert(VA.getValNo() != LastVal &&
1959            "Don't support value assigned to multiple locs yet");
1960     (void)LastVal;
1961     LastVal = VA.getValNo();
1962
1963     if (VA.isRegLoc()) {
1964       EVT RegVT = VA.getLocVT();
1965       const TargetRegisterClass *RC;
1966       if (RegVT == MVT::i32)
1967         RC = &X86::GR32RegClass;
1968       else if (Is64Bit && RegVT == MVT::i64)
1969         RC = &X86::GR64RegClass;
1970       else if (RegVT == MVT::f32)
1971         RC = &X86::FR32RegClass;
1972       else if (RegVT == MVT::f64)
1973         RC = &X86::FR64RegClass;
1974       else if (RegVT.is256BitVector())
1975         RC = &X86::VR256RegClass;
1976       else if (RegVT.is128BitVector())
1977         RC = &X86::VR128RegClass;
1978       else if (RegVT == MVT::x86mmx)
1979         RC = &X86::VR64RegClass;
1980       else
1981         llvm_unreachable("Unknown argument type!");
1982
1983       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1984       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1985
1986       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1987       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1988       // right size.
1989       if (VA.getLocInfo() == CCValAssign::SExt)
1990         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1991                                DAG.getValueType(VA.getValVT()));
1992       else if (VA.getLocInfo() == CCValAssign::ZExt)
1993         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1994                                DAG.getValueType(VA.getValVT()));
1995       else if (VA.getLocInfo() == CCValAssign::BCvt)
1996         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1997
1998       if (VA.isExtInLoc()) {
1999         // Handle MMX values passed in XMM regs.
2000         if (RegVT.isVector())
2001           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2002         else
2003           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2004       }
2005     } else {
2006       assert(VA.isMemLoc());
2007       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2008     }
2009
2010     // If value is passed via pointer - do a load.
2011     if (VA.getLocInfo() == CCValAssign::Indirect)
2012       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2013                              MachinePointerInfo(), false, false, false, 0);
2014
2015     InVals.push_back(ArgValue);
2016   }
2017
2018   // The x86-64 ABI for returning structs by value requires that we copy
2019   // the sret argument into %rax for the return. Save the argument into
2020   // a virtual register so that we can access it from the return points.
2021   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2022     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2023     unsigned Reg = FuncInfo->getSRetReturnReg();
2024     if (!Reg) {
2025       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2026       FuncInfo->setSRetReturnReg(Reg);
2027     }
2028     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2029     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2030   }
2031
2032   unsigned StackSize = CCInfo.getNextStackOffset();
2033   // Align stack specially for tail calls.
2034   if (FuncIsMadeTailCallSafe(CallConv,
2035                              MF.getTarget().Options.GuaranteedTailCallOpt))
2036     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2037
2038   // If the function takes variable number of arguments, make a frame index for
2039   // the start of the first vararg value... for expansion of llvm.va_start.
2040   if (isVarArg) {
2041     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2042                     CallConv != CallingConv::X86_ThisCall)) {
2043       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2044     }
2045     if (Is64Bit) {
2046       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2047
2048       // FIXME: We should really autogenerate these arrays
2049       static const uint16_t GPR64ArgRegsWin64[] = {
2050         X86::RCX, X86::RDX, X86::R8,  X86::R9
2051       };
2052       static const uint16_t GPR64ArgRegs64Bit[] = {
2053         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2054       };
2055       static const uint16_t XMMArgRegs64Bit[] = {
2056         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2057         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2058       };
2059       const uint16_t *GPR64ArgRegs;
2060       unsigned NumXMMRegs = 0;
2061
2062       if (IsWin64) {
2063         // The XMM registers which might contain var arg parameters are shadowed
2064         // in their paired GPR.  So we only need to save the GPR to their home
2065         // slots.
2066         TotalNumIntRegs = 4;
2067         GPR64ArgRegs = GPR64ArgRegsWin64;
2068       } else {
2069         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2070         GPR64ArgRegs = GPR64ArgRegs64Bit;
2071
2072         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2073                                                 TotalNumXMMRegs);
2074       }
2075       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2076                                                        TotalNumIntRegs);
2077
2078       bool NoImplicitFloatOps = Fn->getAttributes().
2079         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2080       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2081              "SSE register cannot be used when SSE is disabled!");
2082       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2083                NoImplicitFloatOps) &&
2084              "SSE register cannot be used when SSE is disabled!");
2085       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2086           !Subtarget->hasSSE1())
2087         // Kernel mode asks for SSE to be disabled, so don't push them
2088         // on the stack.
2089         TotalNumXMMRegs = 0;
2090
2091       if (IsWin64) {
2092         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2093         // Get to the caller-allocated home save location.  Add 8 to account
2094         // for the return address.
2095         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2096         FuncInfo->setRegSaveFrameIndex(
2097           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2098         // Fixup to set vararg frame on shadow area (4 x i64).
2099         if (NumIntRegs < 4)
2100           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2101       } else {
2102         // For X86-64, if there are vararg parameters that are passed via
2103         // registers, then we must store them to their spots on the stack so
2104         // they may be loaded by deferencing the result of va_next.
2105         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2106         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2107         FuncInfo->setRegSaveFrameIndex(
2108           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2109                                false));
2110       }
2111
2112       // Store the integer parameter registers.
2113       SmallVector<SDValue, 8> MemOps;
2114       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2115                                         getPointerTy());
2116       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2117       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2118         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2119                                   DAG.getIntPtrConstant(Offset));
2120         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2121                                      &X86::GR64RegClass);
2122         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2123         SDValue Store =
2124           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2125                        MachinePointerInfo::getFixedStack(
2126                          FuncInfo->getRegSaveFrameIndex(), Offset),
2127                        false, false, 0);
2128         MemOps.push_back(Store);
2129         Offset += 8;
2130       }
2131
2132       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2133         // Now store the XMM (fp + vector) parameter registers.
2134         SmallVector<SDValue, 11> SaveXMMOps;
2135         SaveXMMOps.push_back(Chain);
2136
2137         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2138         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2139         SaveXMMOps.push_back(ALVal);
2140
2141         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2142                                FuncInfo->getRegSaveFrameIndex()));
2143         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2144                                FuncInfo->getVarArgsFPOffset()));
2145
2146         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2147           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2148                                        &X86::VR128RegClass);
2149           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2150           SaveXMMOps.push_back(Val);
2151         }
2152         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2153                                      MVT::Other,
2154                                      &SaveXMMOps[0], SaveXMMOps.size()));
2155       }
2156
2157       if (!MemOps.empty())
2158         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2159                             &MemOps[0], MemOps.size());
2160     }
2161   }
2162
2163   // Some CCs need callee pop.
2164   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2165                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2166     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2167   } else {
2168     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2169     // If this is an sret function, the return should pop the hidden pointer.
2170     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2171         argsAreStructReturn(Ins) == StackStructReturn)
2172       FuncInfo->setBytesToPopOnReturn(4);
2173   }
2174
2175   if (!Is64Bit) {
2176     // RegSaveFrameIndex is X86-64 only.
2177     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2178     if (CallConv == CallingConv::X86_FastCall ||
2179         CallConv == CallingConv::X86_ThisCall)
2180       // fastcc functions can't have varargs.
2181       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2182   }
2183
2184   FuncInfo->setArgumentStackSize(StackSize);
2185
2186   return Chain;
2187 }
2188
2189 SDValue
2190 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2191                                     SDValue StackPtr, SDValue Arg,
2192                                     DebugLoc dl, SelectionDAG &DAG,
2193                                     const CCValAssign &VA,
2194                                     ISD::ArgFlagsTy Flags) const {
2195   unsigned LocMemOffset = VA.getLocMemOffset();
2196   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2197   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2198   if (Flags.isByVal())
2199     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2200
2201   return DAG.getStore(Chain, dl, Arg, PtrOff,
2202                       MachinePointerInfo::getStack(LocMemOffset),
2203                       false, false, 0);
2204 }
2205
2206 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2207 /// optimization is performed and it is required.
2208 SDValue
2209 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2210                                            SDValue &OutRetAddr, SDValue Chain,
2211                                            bool IsTailCall, bool Is64Bit,
2212                                            int FPDiff, DebugLoc dl) const {
2213   // Adjust the Return address stack slot.
2214   EVT VT = getPointerTy();
2215   OutRetAddr = getReturnAddressFrameIndex(DAG);
2216
2217   // Load the "old" Return address.
2218   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2219                            false, false, false, 0);
2220   return SDValue(OutRetAddr.getNode(), 1);
2221 }
2222
2223 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2224 /// optimization is performed and it is required (FPDiff!=0).
2225 static SDValue
2226 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2227                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2228                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2229   // Store the return address to the appropriate stack slot.
2230   if (!FPDiff) return Chain;
2231   // Calculate the new stack slot for the return address.
2232   int NewReturnAddrFI =
2233     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2234   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2235   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2236                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2237                        false, false, 0);
2238   return Chain;
2239 }
2240
2241 SDValue
2242 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2243                              SmallVectorImpl<SDValue> &InVals) const {
2244   SelectionDAG &DAG                     = CLI.DAG;
2245   DebugLoc &dl                          = CLI.DL;
2246   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2247   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2248   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2249   SDValue Chain                         = CLI.Chain;
2250   SDValue Callee                        = CLI.Callee;
2251   CallingConv::ID CallConv              = CLI.CallConv;
2252   bool &isTailCall                      = CLI.IsTailCall;
2253   bool isVarArg                         = CLI.IsVarArg;
2254
2255   MachineFunction &MF = DAG.getMachineFunction();
2256   bool Is64Bit        = Subtarget->is64Bit();
2257   bool IsWin64        = Subtarget->isTargetWin64();
2258   bool IsWindows      = Subtarget->isTargetWindows();
2259   StructReturnType SR = callIsStructReturn(Outs);
2260   bool IsSibcall      = false;
2261
2262   if (MF.getTarget().Options.DisableTailCalls)
2263     isTailCall = false;
2264
2265   if (isTailCall) {
2266     // Check if it's really possible to do a tail call.
2267     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2268                     isVarArg, SR != NotStructReturn,
2269                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2270                     Outs, OutVals, Ins, DAG);
2271
2272     // Sibcalls are automatically detected tailcalls which do not require
2273     // ABI changes.
2274     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2275       IsSibcall = true;
2276
2277     if (isTailCall)
2278       ++NumTailCalls;
2279   }
2280
2281   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2282          "Var args not supported with calling convention fastcc, ghc or hipe");
2283
2284   // Analyze operands of the call, assigning locations to each operand.
2285   SmallVector<CCValAssign, 16> ArgLocs;
2286   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2287                  ArgLocs, *DAG.getContext());
2288
2289   // Allocate shadow area for Win64
2290   if (IsWin64) {
2291     CCInfo.AllocateStack(32, 8);
2292   }
2293
2294   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2295
2296   // Get a count of how many bytes are to be pushed on the stack.
2297   unsigned NumBytes = CCInfo.getNextStackOffset();
2298   if (IsSibcall)
2299     // This is a sibcall. The memory operands are available in caller's
2300     // own caller's stack.
2301     NumBytes = 0;
2302   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2303            IsTailCallConvention(CallConv))
2304     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2305
2306   int FPDiff = 0;
2307   if (isTailCall && !IsSibcall) {
2308     // Lower arguments at fp - stackoffset + fpdiff.
2309     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2310     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2311
2312     FPDiff = NumBytesCallerPushed - NumBytes;
2313
2314     // Set the delta of movement of the returnaddr stackslot.
2315     // But only set if delta is greater than previous delta.
2316     if (FPDiff < X86Info->getTCReturnAddrDelta())
2317       X86Info->setTCReturnAddrDelta(FPDiff);
2318   }
2319
2320   if (!IsSibcall)
2321     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2322
2323   SDValue RetAddrFrIdx;
2324   // Load return address for tail calls.
2325   if (isTailCall && FPDiff)
2326     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2327                                     Is64Bit, FPDiff, dl);
2328
2329   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2330   SmallVector<SDValue, 8> MemOpChains;
2331   SDValue StackPtr;
2332
2333   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2334   // of tail call optimization arguments are handle later.
2335   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2336     CCValAssign &VA = ArgLocs[i];
2337     EVT RegVT = VA.getLocVT();
2338     SDValue Arg = OutVals[i];
2339     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2340     bool isByVal = Flags.isByVal();
2341
2342     // Promote the value if needed.
2343     switch (VA.getLocInfo()) {
2344     default: llvm_unreachable("Unknown loc info!");
2345     case CCValAssign::Full: break;
2346     case CCValAssign::SExt:
2347       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2348       break;
2349     case CCValAssign::ZExt:
2350       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2351       break;
2352     case CCValAssign::AExt:
2353       if (RegVT.is128BitVector()) {
2354         // Special case: passing MMX values in XMM registers.
2355         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2356         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2357         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2358       } else
2359         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2360       break;
2361     case CCValAssign::BCvt:
2362       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2363       break;
2364     case CCValAssign::Indirect: {
2365       // Store the argument.
2366       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2367       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2368       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2369                            MachinePointerInfo::getFixedStack(FI),
2370                            false, false, 0);
2371       Arg = SpillSlot;
2372       break;
2373     }
2374     }
2375
2376     if (VA.isRegLoc()) {
2377       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2378       if (isVarArg && IsWin64) {
2379         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2380         // shadow reg if callee is a varargs function.
2381         unsigned ShadowReg = 0;
2382         switch (VA.getLocReg()) {
2383         case X86::XMM0: ShadowReg = X86::RCX; break;
2384         case X86::XMM1: ShadowReg = X86::RDX; break;
2385         case X86::XMM2: ShadowReg = X86::R8; break;
2386         case X86::XMM3: ShadowReg = X86::R9; break;
2387         }
2388         if (ShadowReg)
2389           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2390       }
2391     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2392       assert(VA.isMemLoc());
2393       if (StackPtr.getNode() == 0)
2394         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2395                                       getPointerTy());
2396       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2397                                              dl, DAG, VA, Flags));
2398     }
2399   }
2400
2401   if (!MemOpChains.empty())
2402     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2403                         &MemOpChains[0], MemOpChains.size());
2404
2405   if (Subtarget->isPICStyleGOT()) {
2406     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2407     // GOT pointer.
2408     if (!isTailCall) {
2409       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2410                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2411     } else {
2412       // If we are tail calling and generating PIC/GOT style code load the
2413       // address of the callee into ECX. The value in ecx is used as target of
2414       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2415       // for tail calls on PIC/GOT architectures. Normally we would just put the
2416       // address of GOT into ebx and then call target@PLT. But for tail calls
2417       // ebx would be restored (since ebx is callee saved) before jumping to the
2418       // target@PLT.
2419
2420       // Note: The actual moving to ECX is done further down.
2421       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2422       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2423           !G->getGlobal()->hasProtectedVisibility())
2424         Callee = LowerGlobalAddress(Callee, DAG);
2425       else if (isa<ExternalSymbolSDNode>(Callee))
2426         Callee = LowerExternalSymbol(Callee, DAG);
2427     }
2428   }
2429
2430   if (Is64Bit && isVarArg && !IsWin64) {
2431     // From AMD64 ABI document:
2432     // For calls that may call functions that use varargs or stdargs
2433     // (prototype-less calls or calls to functions containing ellipsis (...) in
2434     // the declaration) %al is used as hidden argument to specify the number
2435     // of SSE registers used. The contents of %al do not need to match exactly
2436     // the number of registers, but must be an ubound on the number of SSE
2437     // registers used and is in the range 0 - 8 inclusive.
2438
2439     // Count the number of XMM registers allocated.
2440     static const uint16_t XMMArgRegs[] = {
2441       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2442       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2443     };
2444     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2445     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2446            && "SSE registers cannot be used when SSE is disabled");
2447
2448     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2449                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2450   }
2451
2452   // For tail calls lower the arguments to the 'real' stack slot.
2453   if (isTailCall) {
2454     // Force all the incoming stack arguments to be loaded from the stack
2455     // before any new outgoing arguments are stored to the stack, because the
2456     // outgoing stack slots may alias the incoming argument stack slots, and
2457     // the alias isn't otherwise explicit. This is slightly more conservative
2458     // than necessary, because it means that each store effectively depends
2459     // on every argument instead of just those arguments it would clobber.
2460     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2461
2462     SmallVector<SDValue, 8> MemOpChains2;
2463     SDValue FIN;
2464     int FI = 0;
2465     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2466       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2467         CCValAssign &VA = ArgLocs[i];
2468         if (VA.isRegLoc())
2469           continue;
2470         assert(VA.isMemLoc());
2471         SDValue Arg = OutVals[i];
2472         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2473         // Create frame index.
2474         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2475         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2476         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2477         FIN = DAG.getFrameIndex(FI, getPointerTy());
2478
2479         if (Flags.isByVal()) {
2480           // Copy relative to framepointer.
2481           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2482           if (StackPtr.getNode() == 0)
2483             StackPtr = DAG.getCopyFromReg(Chain, dl,
2484                                           RegInfo->getStackRegister(),
2485                                           getPointerTy());
2486           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2487
2488           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2489                                                            ArgChain,
2490                                                            Flags, DAG, dl));
2491         } else {
2492           // Store relative to framepointer.
2493           MemOpChains2.push_back(
2494             DAG.getStore(ArgChain, dl, Arg, FIN,
2495                          MachinePointerInfo::getFixedStack(FI),
2496                          false, false, 0));
2497         }
2498       }
2499     }
2500
2501     if (!MemOpChains2.empty())
2502       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2503                           &MemOpChains2[0], MemOpChains2.size());
2504
2505     // Store the return address to the appropriate stack slot.
2506     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2507                                      getPointerTy(), RegInfo->getSlotSize(),
2508                                      FPDiff, dl);
2509   }
2510
2511   // Build a sequence of copy-to-reg nodes chained together with token chain
2512   // and flag operands which copy the outgoing args into registers.
2513   SDValue InFlag;
2514   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2515     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2516                              RegsToPass[i].second, InFlag);
2517     InFlag = Chain.getValue(1);
2518   }
2519
2520   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2521     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2522     // In the 64-bit large code model, we have to make all calls
2523     // through a register, since the call instruction's 32-bit
2524     // pc-relative offset may not be large enough to hold the whole
2525     // address.
2526   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2527     // If the callee is a GlobalAddress node (quite common, every direct call
2528     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2529     // it.
2530
2531     // We should use extra load for direct calls to dllimported functions in
2532     // non-JIT mode.
2533     const GlobalValue *GV = G->getGlobal();
2534     if (!GV->hasDLLImportLinkage()) {
2535       unsigned char OpFlags = 0;
2536       bool ExtraLoad = false;
2537       unsigned WrapperKind = ISD::DELETED_NODE;
2538
2539       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2540       // external symbols most go through the PLT in PIC mode.  If the symbol
2541       // has hidden or protected visibility, or if it is static or local, then
2542       // we don't need to use the PLT - we can directly call it.
2543       if (Subtarget->isTargetELF() &&
2544           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2545           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2546         OpFlags = X86II::MO_PLT;
2547       } else if (Subtarget->isPICStyleStubAny() &&
2548                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2549                  (!Subtarget->getTargetTriple().isMacOSX() ||
2550                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2551         // PC-relative references to external symbols should go through $stub,
2552         // unless we're building with the leopard linker or later, which
2553         // automatically synthesizes these stubs.
2554         OpFlags = X86II::MO_DARWIN_STUB;
2555       } else if (Subtarget->isPICStyleRIPRel() &&
2556                  isa<Function>(GV) &&
2557                  cast<Function>(GV)->getAttributes().
2558                    hasAttribute(AttributeSet::FunctionIndex,
2559                                 Attribute::NonLazyBind)) {
2560         // If the function is marked as non-lazy, generate an indirect call
2561         // which loads from the GOT directly. This avoids runtime overhead
2562         // at the cost of eager binding (and one extra byte of encoding).
2563         OpFlags = X86II::MO_GOTPCREL;
2564         WrapperKind = X86ISD::WrapperRIP;
2565         ExtraLoad = true;
2566       }
2567
2568       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2569                                           G->getOffset(), OpFlags);
2570
2571       // Add a wrapper if needed.
2572       if (WrapperKind != ISD::DELETED_NODE)
2573         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2574       // Add extra indirection if needed.
2575       if (ExtraLoad)
2576         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2577                              MachinePointerInfo::getGOT(),
2578                              false, false, false, 0);
2579     }
2580   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2581     unsigned char OpFlags = 0;
2582
2583     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2584     // external symbols should go through the PLT.
2585     if (Subtarget->isTargetELF() &&
2586         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2587       OpFlags = X86II::MO_PLT;
2588     } else if (Subtarget->isPICStyleStubAny() &&
2589                (!Subtarget->getTargetTriple().isMacOSX() ||
2590                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591       // PC-relative references to external symbols should go through $stub,
2592       // unless we're building with the leopard linker or later, which
2593       // automatically synthesizes these stubs.
2594       OpFlags = X86II::MO_DARWIN_STUB;
2595     }
2596
2597     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2598                                          OpFlags);
2599   }
2600
2601   // Returns a chain & a flag for retval copy to use.
2602   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2603   SmallVector<SDValue, 8> Ops;
2604
2605   if (!IsSibcall && isTailCall) {
2606     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2607                            DAG.getIntPtrConstant(0, true), InFlag);
2608     InFlag = Chain.getValue(1);
2609   }
2610
2611   Ops.push_back(Chain);
2612   Ops.push_back(Callee);
2613
2614   if (isTailCall)
2615     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2616
2617   // Add argument registers to the end of the list so that they are known live
2618   // into the call.
2619   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2620     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2621                                   RegsToPass[i].second.getValueType()));
2622
2623   // Add a register mask operand representing the call-preserved registers.
2624   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2625   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2626   assert(Mask && "Missing call preserved mask for calling convention");
2627   Ops.push_back(DAG.getRegisterMask(Mask));
2628
2629   if (InFlag.getNode())
2630     Ops.push_back(InFlag);
2631
2632   if (isTailCall) {
2633     // We used to do:
2634     //// If this is the first return lowered for this function, add the regs
2635     //// to the liveout set for the function.
2636     // This isn't right, although it's probably harmless on x86; liveouts
2637     // should be computed from returns not tail calls.  Consider a void
2638     // function making a tail call to a function returning int.
2639     return DAG.getNode(X86ISD::TC_RETURN, dl,
2640                        NodeTys, &Ops[0], Ops.size());
2641   }
2642
2643   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2644   InFlag = Chain.getValue(1);
2645
2646   // Create the CALLSEQ_END node.
2647   unsigned NumBytesForCalleeToPush;
2648   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2649                        getTargetMachine().Options.GuaranteedTailCallOpt))
2650     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2651   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2652            SR == StackStructReturn)
2653     // If this is a call to a struct-return function, the callee
2654     // pops the hidden struct pointer, so we have to push it back.
2655     // This is common for Darwin/X86, Linux & Mingw32 targets.
2656     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2657     NumBytesForCalleeToPush = 4;
2658   else
2659     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2660
2661   // Returns a flag for retval copy to use.
2662   if (!IsSibcall) {
2663     Chain = DAG.getCALLSEQ_END(Chain,
2664                                DAG.getIntPtrConstant(NumBytes, true),
2665                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2666                                                      true),
2667                                InFlag);
2668     InFlag = Chain.getValue(1);
2669   }
2670
2671   // Handle result values, copying them out of physregs into vregs that we
2672   // return.
2673   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2674                          Ins, dl, DAG, InVals);
2675 }
2676
2677 //===----------------------------------------------------------------------===//
2678 //                Fast Calling Convention (tail call) implementation
2679 //===----------------------------------------------------------------------===//
2680
2681 //  Like std call, callee cleans arguments, convention except that ECX is
2682 //  reserved for storing the tail called function address. Only 2 registers are
2683 //  free for argument passing (inreg). Tail call optimization is performed
2684 //  provided:
2685 //                * tailcallopt is enabled
2686 //                * caller/callee are fastcc
2687 //  On X86_64 architecture with GOT-style position independent code only local
2688 //  (within module) calls are supported at the moment.
2689 //  To keep the stack aligned according to platform abi the function
2690 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2691 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2692 //  If a tail called function callee has more arguments than the caller the
2693 //  caller needs to make sure that there is room to move the RETADDR to. This is
2694 //  achieved by reserving an area the size of the argument delta right after the
2695 //  original REtADDR, but before the saved framepointer or the spilled registers
2696 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2697 //  stack layout:
2698 //    arg1
2699 //    arg2
2700 //    RETADDR
2701 //    [ new RETADDR
2702 //      move area ]
2703 //    (possible EBP)
2704 //    ESI
2705 //    EDI
2706 //    local1 ..
2707
2708 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2709 /// for a 16 byte align requirement.
2710 unsigned
2711 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2712                                                SelectionDAG& DAG) const {
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   const TargetMachine &TM = MF.getTarget();
2715   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2716   unsigned StackAlignment = TFI.getStackAlignment();
2717   uint64_t AlignMask = StackAlignment - 1;
2718   int64_t Offset = StackSize;
2719   unsigned SlotSize = RegInfo->getSlotSize();
2720   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2721     // Number smaller than 12 so just add the difference.
2722     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2723   } else {
2724     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2725     Offset = ((~AlignMask) & Offset) + StackAlignment +
2726       (StackAlignment-SlotSize);
2727   }
2728   return Offset;
2729 }
2730
2731 /// MatchingStackOffset - Return true if the given stack call argument is
2732 /// already available in the same position (relatively) of the caller's
2733 /// incoming argument stack.
2734 static
2735 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2736                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2737                          const X86InstrInfo *TII) {
2738   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2739   int FI = INT_MAX;
2740   if (Arg.getOpcode() == ISD::CopyFromReg) {
2741     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2742     if (!TargetRegisterInfo::isVirtualRegister(VR))
2743       return false;
2744     MachineInstr *Def = MRI->getVRegDef(VR);
2745     if (!Def)
2746       return false;
2747     if (!Flags.isByVal()) {
2748       if (!TII->isLoadFromStackSlot(Def, FI))
2749         return false;
2750     } else {
2751       unsigned Opcode = Def->getOpcode();
2752       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2753           Def->getOperand(1).isFI()) {
2754         FI = Def->getOperand(1).getIndex();
2755         Bytes = Flags.getByValSize();
2756       } else
2757         return false;
2758     }
2759   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2760     if (Flags.isByVal())
2761       // ByVal argument is passed in as a pointer but it's now being
2762       // dereferenced. e.g.
2763       // define @foo(%struct.X* %A) {
2764       //   tail call @bar(%struct.X* byval %A)
2765       // }
2766       return false;
2767     SDValue Ptr = Ld->getBasePtr();
2768     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2769     if (!FINode)
2770       return false;
2771     FI = FINode->getIndex();
2772   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2773     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2774     FI = FINode->getIndex();
2775     Bytes = Flags.getByValSize();
2776   } else
2777     return false;
2778
2779   assert(FI != INT_MAX);
2780   if (!MFI->isFixedObjectIndex(FI))
2781     return false;
2782   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2783 }
2784
2785 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2786 /// for tail call optimization. Targets which want to do tail call
2787 /// optimization should implement this function.
2788 bool
2789 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2790                                                      CallingConv::ID CalleeCC,
2791                                                      bool isVarArg,
2792                                                      bool isCalleeStructRet,
2793                                                      bool isCallerStructRet,
2794                                                      Type *RetTy,
2795                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2796                                     const SmallVectorImpl<SDValue> &OutVals,
2797                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2798                                                      SelectionDAG& DAG) const {
2799   if (!IsTailCallConvention(CalleeCC) &&
2800       CalleeCC != CallingConv::C)
2801     return false;
2802
2803   // If -tailcallopt is specified, make fastcc functions tail-callable.
2804   const MachineFunction &MF = DAG.getMachineFunction();
2805   const Function *CallerF = DAG.getMachineFunction().getFunction();
2806
2807   // If the function return type is x86_fp80 and the callee return type is not,
2808   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2809   // perform a tailcall optimization here.
2810   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2811     return false;
2812
2813   CallingConv::ID CallerCC = CallerF->getCallingConv();
2814   bool CCMatch = CallerCC == CalleeCC;
2815
2816   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2817     if (IsTailCallConvention(CalleeCC) && CCMatch)
2818       return true;
2819     return false;
2820   }
2821
2822   // Look for obvious safe cases to perform tail call optimization that do not
2823   // require ABI changes. This is what gcc calls sibcall.
2824
2825   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2826   // emit a special epilogue.
2827   if (RegInfo->needsStackRealignment(MF))
2828     return false;
2829
2830   // Also avoid sibcall optimization if either caller or callee uses struct
2831   // return semantics.
2832   if (isCalleeStructRet || isCallerStructRet)
2833     return false;
2834
2835   // An stdcall caller is expected to clean up its arguments; the callee
2836   // isn't going to do that.
2837   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2838     return false;
2839
2840   // Do not sibcall optimize vararg calls unless all arguments are passed via
2841   // registers.
2842   if (isVarArg && !Outs.empty()) {
2843
2844     // Optimizing for varargs on Win64 is unlikely to be safe without
2845     // additional testing.
2846     if (Subtarget->isTargetWin64())
2847       return false;
2848
2849     SmallVector<CCValAssign, 16> ArgLocs;
2850     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2851                    getTargetMachine(), ArgLocs, *DAG.getContext());
2852
2853     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2854     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2855       if (!ArgLocs[i].isRegLoc())
2856         return false;
2857   }
2858
2859   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2860   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2861   // this into a sibcall.
2862   bool Unused = false;
2863   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2864     if (!Ins[i].Used) {
2865       Unused = true;
2866       break;
2867     }
2868   }
2869   if (Unused) {
2870     SmallVector<CCValAssign, 16> RVLocs;
2871     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2872                    getTargetMachine(), RVLocs, *DAG.getContext());
2873     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2874     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2875       CCValAssign &VA = RVLocs[i];
2876       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2877         return false;
2878     }
2879   }
2880
2881   // If the calling conventions do not match, then we'd better make sure the
2882   // results are returned in the same way as what the caller expects.
2883   if (!CCMatch) {
2884     SmallVector<CCValAssign, 16> RVLocs1;
2885     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2886                     getTargetMachine(), RVLocs1, *DAG.getContext());
2887     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2888
2889     SmallVector<CCValAssign, 16> RVLocs2;
2890     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2891                     getTargetMachine(), RVLocs2, *DAG.getContext());
2892     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2893
2894     if (RVLocs1.size() != RVLocs2.size())
2895       return false;
2896     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2897       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2898         return false;
2899       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2900         return false;
2901       if (RVLocs1[i].isRegLoc()) {
2902         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2903           return false;
2904       } else {
2905         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2906           return false;
2907       }
2908     }
2909   }
2910
2911   // If the callee takes no arguments then go on to check the results of the
2912   // call.
2913   if (!Outs.empty()) {
2914     // Check if stack adjustment is needed. For now, do not do this if any
2915     // argument is passed on the stack.
2916     SmallVector<CCValAssign, 16> ArgLocs;
2917     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2918                    getTargetMachine(), ArgLocs, *DAG.getContext());
2919
2920     // Allocate shadow area for Win64
2921     if (Subtarget->isTargetWin64()) {
2922       CCInfo.AllocateStack(32, 8);
2923     }
2924
2925     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2926     if (CCInfo.getNextStackOffset()) {
2927       MachineFunction &MF = DAG.getMachineFunction();
2928       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2929         return false;
2930
2931       // Check if the arguments are already laid out in the right way as
2932       // the caller's fixed stack objects.
2933       MachineFrameInfo *MFI = MF.getFrameInfo();
2934       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2935       const X86InstrInfo *TII =
2936         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2937       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938         CCValAssign &VA = ArgLocs[i];
2939         SDValue Arg = OutVals[i];
2940         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2941         if (VA.getLocInfo() == CCValAssign::Indirect)
2942           return false;
2943         if (!VA.isRegLoc()) {
2944           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2945                                    MFI, MRI, TII))
2946             return false;
2947         }
2948       }
2949     }
2950
2951     // If the tailcall address may be in a register, then make sure it's
2952     // possible to register allocate for it. In 32-bit, the call address can
2953     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2954     // callee-saved registers are restored. These happen to be the same
2955     // registers used to pass 'inreg' arguments so watch out for those.
2956     if (!Subtarget->is64Bit() &&
2957         !isa<GlobalAddressSDNode>(Callee) &&
2958         !isa<ExternalSymbolSDNode>(Callee)) {
2959       unsigned NumInRegs = 0;
2960       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2961         CCValAssign &VA = ArgLocs[i];
2962         if (!VA.isRegLoc())
2963           continue;
2964         unsigned Reg = VA.getLocReg();
2965         switch (Reg) {
2966         default: break;
2967         case X86::EAX: case X86::EDX: case X86::ECX:
2968           if (++NumInRegs == 3)
2969             return false;
2970           break;
2971         }
2972       }
2973     }
2974   }
2975
2976   return true;
2977 }
2978
2979 FastISel *
2980 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2981                                   const TargetLibraryInfo *libInfo) const {
2982   return X86::createFastISel(funcInfo, libInfo);
2983 }
2984
2985 //===----------------------------------------------------------------------===//
2986 //                           Other Lowering Hooks
2987 //===----------------------------------------------------------------------===//
2988
2989 static bool MayFoldLoad(SDValue Op) {
2990   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2991 }
2992
2993 static bool MayFoldIntoStore(SDValue Op) {
2994   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2995 }
2996
2997 static bool isTargetShuffle(unsigned Opcode) {
2998   switch(Opcode) {
2999   default: return false;
3000   case X86ISD::PSHUFD:
3001   case X86ISD::PSHUFHW:
3002   case X86ISD::PSHUFLW:
3003   case X86ISD::SHUFP:
3004   case X86ISD::PALIGN:
3005   case X86ISD::MOVLHPS:
3006   case X86ISD::MOVLHPD:
3007   case X86ISD::MOVHLPS:
3008   case X86ISD::MOVLPS:
3009   case X86ISD::MOVLPD:
3010   case X86ISD::MOVSHDUP:
3011   case X86ISD::MOVSLDUP:
3012   case X86ISD::MOVDDUP:
3013   case X86ISD::MOVSS:
3014   case X86ISD::MOVSD:
3015   case X86ISD::UNPCKL:
3016   case X86ISD::UNPCKH:
3017   case X86ISD::VPERMILP:
3018   case X86ISD::VPERM2X128:
3019   case X86ISD::VPERMI:
3020     return true;
3021   }
3022 }
3023
3024 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3025                                     SDValue V1, SelectionDAG &DAG) {
3026   switch(Opc) {
3027   default: llvm_unreachable("Unknown x86 shuffle node");
3028   case X86ISD::MOVSHDUP:
3029   case X86ISD::MOVSLDUP:
3030   case X86ISD::MOVDDUP:
3031     return DAG.getNode(Opc, dl, VT, V1);
3032   }
3033 }
3034
3035 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3036                                     SDValue V1, unsigned TargetMask,
3037                                     SelectionDAG &DAG) {
3038   switch(Opc) {
3039   default: llvm_unreachable("Unknown x86 shuffle node");
3040   case X86ISD::PSHUFD:
3041   case X86ISD::PSHUFHW:
3042   case X86ISD::PSHUFLW:
3043   case X86ISD::VPERMILP:
3044   case X86ISD::VPERMI:
3045     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3046   }
3047 }
3048
3049 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3050                                     SDValue V1, SDValue V2, unsigned TargetMask,
3051                                     SelectionDAG &DAG) {
3052   switch(Opc) {
3053   default: llvm_unreachable("Unknown x86 shuffle node");
3054   case X86ISD::PALIGN:
3055   case X86ISD::SHUFP:
3056   case X86ISD::VPERM2X128:
3057     return DAG.getNode(Opc, dl, VT, V1, V2,
3058                        DAG.getConstant(TargetMask, MVT::i8));
3059   }
3060 }
3061
3062 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3063                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3064   switch(Opc) {
3065   default: llvm_unreachable("Unknown x86 shuffle node");
3066   case X86ISD::MOVLHPS:
3067   case X86ISD::MOVLHPD:
3068   case X86ISD::MOVHLPS:
3069   case X86ISD::MOVLPS:
3070   case X86ISD::MOVLPD:
3071   case X86ISD::MOVSS:
3072   case X86ISD::MOVSD:
3073   case X86ISD::UNPCKL:
3074   case X86ISD::UNPCKH:
3075     return DAG.getNode(Opc, dl, VT, V1, V2);
3076   }
3077 }
3078
3079 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3080   MachineFunction &MF = DAG.getMachineFunction();
3081   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3082   int ReturnAddrIndex = FuncInfo->getRAIndex();
3083
3084   if (ReturnAddrIndex == 0) {
3085     // Set up a frame object for the return address.
3086     unsigned SlotSize = RegInfo->getSlotSize();
3087     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3088                                                            false);
3089     FuncInfo->setRAIndex(ReturnAddrIndex);
3090   }
3091
3092   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3093 }
3094
3095 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3096                                        bool hasSymbolicDisplacement) {
3097   // Offset should fit into 32 bit immediate field.
3098   if (!isInt<32>(Offset))
3099     return false;
3100
3101   // If we don't have a symbolic displacement - we don't have any extra
3102   // restrictions.
3103   if (!hasSymbolicDisplacement)
3104     return true;
3105
3106   // FIXME: Some tweaks might be needed for medium code model.
3107   if (M != CodeModel::Small && M != CodeModel::Kernel)
3108     return false;
3109
3110   // For small code model we assume that latest object is 16MB before end of 31
3111   // bits boundary. We may also accept pretty large negative constants knowing
3112   // that all objects are in the positive half of address space.
3113   if (M == CodeModel::Small && Offset < 16*1024*1024)
3114     return true;
3115
3116   // For kernel code model we know that all object resist in the negative half
3117   // of 32bits address space. We may not accept negative offsets, since they may
3118   // be just off and we may accept pretty large positive ones.
3119   if (M == CodeModel::Kernel && Offset > 0)
3120     return true;
3121
3122   return false;
3123 }
3124
3125 /// isCalleePop - Determines whether the callee is required to pop its
3126 /// own arguments. Callee pop is necessary to support tail calls.
3127 bool X86::isCalleePop(CallingConv::ID CallingConv,
3128                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3129   if (IsVarArg)
3130     return false;
3131
3132   switch (CallingConv) {
3133   default:
3134     return false;
3135   case CallingConv::X86_StdCall:
3136     return !is64Bit;
3137   case CallingConv::X86_FastCall:
3138     return !is64Bit;
3139   case CallingConv::X86_ThisCall:
3140     return !is64Bit;
3141   case CallingConv::Fast:
3142     return TailCallOpt;
3143   case CallingConv::GHC:
3144     return TailCallOpt;
3145   case CallingConv::HiPE:
3146     return TailCallOpt;
3147   }
3148 }
3149
3150 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3151 /// specific condition code, returning the condition code and the LHS/RHS of the
3152 /// comparison to make.
3153 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3154                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3155   if (!isFP) {
3156     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3157       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3158         // X > -1   -> X == 0, jump !sign.
3159         RHS = DAG.getConstant(0, RHS.getValueType());
3160         return X86::COND_NS;
3161       }
3162       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3163         // X < 0   -> X == 0, jump on sign.
3164         return X86::COND_S;
3165       }
3166       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3167         // X < 1   -> X <= 0
3168         RHS = DAG.getConstant(0, RHS.getValueType());
3169         return X86::COND_LE;
3170       }
3171     }
3172
3173     switch (SetCCOpcode) {
3174     default: llvm_unreachable("Invalid integer condition!");
3175     case ISD::SETEQ:  return X86::COND_E;
3176     case ISD::SETGT:  return X86::COND_G;
3177     case ISD::SETGE:  return X86::COND_GE;
3178     case ISD::SETLT:  return X86::COND_L;
3179     case ISD::SETLE:  return X86::COND_LE;
3180     case ISD::SETNE:  return X86::COND_NE;
3181     case ISD::SETULT: return X86::COND_B;
3182     case ISD::SETUGT: return X86::COND_A;
3183     case ISD::SETULE: return X86::COND_BE;
3184     case ISD::SETUGE: return X86::COND_AE;
3185     }
3186   }
3187
3188   // First determine if it is required or is profitable to flip the operands.
3189
3190   // If LHS is a foldable load, but RHS is not, flip the condition.
3191   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3192       !ISD::isNON_EXTLoad(RHS.getNode())) {
3193     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3194     std::swap(LHS, RHS);
3195   }
3196
3197   switch (SetCCOpcode) {
3198   default: break;
3199   case ISD::SETOLT:
3200   case ISD::SETOLE:
3201   case ISD::SETUGT:
3202   case ISD::SETUGE:
3203     std::swap(LHS, RHS);
3204     break;
3205   }
3206
3207   // On a floating point condition, the flags are set as follows:
3208   // ZF  PF  CF   op
3209   //  0 | 0 | 0 | X > Y
3210   //  0 | 0 | 1 | X < Y
3211   //  1 | 0 | 0 | X == Y
3212   //  1 | 1 | 1 | unordered
3213   switch (SetCCOpcode) {
3214   default: llvm_unreachable("Condcode should be pre-legalized away");
3215   case ISD::SETUEQ:
3216   case ISD::SETEQ:   return X86::COND_E;
3217   case ISD::SETOLT:              // flipped
3218   case ISD::SETOGT:
3219   case ISD::SETGT:   return X86::COND_A;
3220   case ISD::SETOLE:              // flipped
3221   case ISD::SETOGE:
3222   case ISD::SETGE:   return X86::COND_AE;
3223   case ISD::SETUGT:              // flipped
3224   case ISD::SETULT:
3225   case ISD::SETLT:   return X86::COND_B;
3226   case ISD::SETUGE:              // flipped
3227   case ISD::SETULE:
3228   case ISD::SETLE:   return X86::COND_BE;
3229   case ISD::SETONE:
3230   case ISD::SETNE:   return X86::COND_NE;
3231   case ISD::SETUO:   return X86::COND_P;
3232   case ISD::SETO:    return X86::COND_NP;
3233   case ISD::SETOEQ:
3234   case ISD::SETUNE:  return X86::COND_INVALID;
3235   }
3236 }
3237
3238 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3239 /// code. Current x86 isa includes the following FP cmov instructions:
3240 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3241 static bool hasFPCMov(unsigned X86CC) {
3242   switch (X86CC) {
3243   default:
3244     return false;
3245   case X86::COND_B:
3246   case X86::COND_BE:
3247   case X86::COND_E:
3248   case X86::COND_P:
3249   case X86::COND_A:
3250   case X86::COND_AE:
3251   case X86::COND_NE:
3252   case X86::COND_NP:
3253     return true;
3254   }
3255 }
3256
3257 /// isFPImmLegal - Returns true if the target can instruction select the
3258 /// specified FP immediate natively. If false, the legalizer will
3259 /// materialize the FP immediate as a load from a constant pool.
3260 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3261   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3262     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3263       return true;
3264   }
3265   return false;
3266 }
3267
3268 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3269 /// the specified range (L, H].
3270 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3271   return (Val < 0) || (Val >= Low && Val < Hi);
3272 }
3273
3274 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3275 /// specified value.
3276 static bool isUndefOrEqual(int Val, int CmpVal) {
3277   return (Val < 0 || Val == CmpVal);
3278 }
3279
3280 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3281 /// from position Pos and ending in Pos+Size, falls within the specified
3282 /// sequential range (L, L+Pos]. or is undef.
3283 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3284                                        unsigned Pos, unsigned Size, int Low) {
3285   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3286     if (!isUndefOrEqual(Mask[i], Low))
3287       return false;
3288   return true;
3289 }
3290
3291 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3292 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3293 /// the second operand.
3294 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3295   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3296     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3297   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3298     return (Mask[0] < 2 && Mask[1] < 2);
3299   return false;
3300 }
3301
3302 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3303 /// is suitable for input to PSHUFHW.
3304 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3305   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3306     return false;
3307
3308   // Lower quadword copied in order or undef.
3309   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3310     return false;
3311
3312   // Upper quadword shuffled.
3313   for (unsigned i = 4; i != 8; ++i)
3314     if (!isUndefOrInRange(Mask[i], 4, 8))
3315       return false;
3316
3317   if (VT == MVT::v16i16) {
3318     // Lower quadword copied in order or undef.
3319     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3320       return false;
3321
3322     // Upper quadword shuffled.
3323     for (unsigned i = 12; i != 16; ++i)
3324       if (!isUndefOrInRange(Mask[i], 12, 16))
3325         return false;
3326   }
3327
3328   return true;
3329 }
3330
3331 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3332 /// is suitable for input to PSHUFLW.
3333 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3334   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3335     return false;
3336
3337   // Upper quadword copied in order.
3338   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3339     return false;
3340
3341   // Lower quadword shuffled.
3342   for (unsigned i = 0; i != 4; ++i)
3343     if (!isUndefOrInRange(Mask[i], 0, 4))
3344       return false;
3345
3346   if (VT == MVT::v16i16) {
3347     // Upper quadword copied in order.
3348     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3349       return false;
3350
3351     // Lower quadword shuffled.
3352     for (unsigned i = 8; i != 12; ++i)
3353       if (!isUndefOrInRange(Mask[i], 8, 12))
3354         return false;
3355   }
3356
3357   return true;
3358 }
3359
3360 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3361 /// is suitable for input to PALIGNR.
3362 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3363                           const X86Subtarget *Subtarget) {
3364   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3365       (VT.is256BitVector() && !Subtarget->hasInt256()))
3366     return false;
3367
3368   unsigned NumElts = VT.getVectorNumElements();
3369   unsigned NumLanes = VT.getSizeInBits()/128;
3370   unsigned NumLaneElts = NumElts/NumLanes;
3371
3372   // Do not handle 64-bit element shuffles with palignr.
3373   if (NumLaneElts == 2)
3374     return false;
3375
3376   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3377     unsigned i;
3378     for (i = 0; i != NumLaneElts; ++i) {
3379       if (Mask[i+l] >= 0)
3380         break;
3381     }
3382
3383     // Lane is all undef, go to next lane
3384     if (i == NumLaneElts)
3385       continue;
3386
3387     int Start = Mask[i+l];
3388
3389     // Make sure its in this lane in one of the sources
3390     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3391         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3392       return false;
3393
3394     // If not lane 0, then we must match lane 0
3395     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3396       return false;
3397
3398     // Correct second source to be contiguous with first source
3399     if (Start >= (int)NumElts)
3400       Start -= NumElts - NumLaneElts;
3401
3402     // Make sure we're shifting in the right direction.
3403     if (Start <= (int)(i+l))
3404       return false;
3405
3406     Start -= i;
3407
3408     // Check the rest of the elements to see if they are consecutive.
3409     for (++i; i != NumLaneElts; ++i) {
3410       int Idx = Mask[i+l];
3411
3412       // Make sure its in this lane
3413       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3414           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3415         return false;
3416
3417       // If not lane 0, then we must match lane 0
3418       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3419         return false;
3420
3421       if (Idx >= (int)NumElts)
3422         Idx -= NumElts - NumLaneElts;
3423
3424       if (!isUndefOrEqual(Idx, Start+i))
3425         return false;
3426
3427     }
3428   }
3429
3430   return true;
3431 }
3432
3433 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3434 /// the two vector operands have swapped position.
3435 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3436                                      unsigned NumElems) {
3437   for (unsigned i = 0; i != NumElems; ++i) {
3438     int idx = Mask[i];
3439     if (idx < 0)
3440       continue;
3441     else if (idx < (int)NumElems)
3442       Mask[i] = idx + NumElems;
3443     else
3444       Mask[i] = idx - NumElems;
3445   }
3446 }
3447
3448 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3449 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3450 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3451 /// reverse of what x86 shuffles want.
3452 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3453                         bool Commuted = false) {
3454   if (!HasFp256 && VT.is256BitVector())
3455     return false;
3456
3457   unsigned NumElems = VT.getVectorNumElements();
3458   unsigned NumLanes = VT.getSizeInBits()/128;
3459   unsigned NumLaneElems = NumElems/NumLanes;
3460
3461   if (NumLaneElems != 2 && NumLaneElems != 4)
3462     return false;
3463
3464   // VSHUFPSY divides the resulting vector into 4 chunks.
3465   // The sources are also splitted into 4 chunks, and each destination
3466   // chunk must come from a different source chunk.
3467   //
3468   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3469   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3470   //
3471   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3472   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3473   //
3474   // VSHUFPDY divides the resulting vector into 4 chunks.
3475   // The sources are also splitted into 4 chunks, and each destination
3476   // chunk must come from a different source chunk.
3477   //
3478   //  SRC1 =>      X3       X2       X1       X0
3479   //  SRC2 =>      Y3       Y2       Y1       Y0
3480   //
3481   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3482   //
3483   unsigned HalfLaneElems = NumLaneElems/2;
3484   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3485     for (unsigned i = 0; i != NumLaneElems; ++i) {
3486       int Idx = Mask[i+l];
3487       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3488       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3489         return false;
3490       // For VSHUFPSY, the mask of the second half must be the same as the
3491       // first but with the appropriate offsets. This works in the same way as
3492       // VPERMILPS works with masks.
3493       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3494         continue;
3495       if (!isUndefOrEqual(Idx, Mask[i]+l))
3496         return false;
3497     }
3498   }
3499
3500   return true;
3501 }
3502
3503 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3504 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3505 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3506   if (!VT.is128BitVector())
3507     return false;
3508
3509   unsigned NumElems = VT.getVectorNumElements();
3510
3511   if (NumElems != 4)
3512     return false;
3513
3514   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3515   return isUndefOrEqual(Mask[0], 6) &&
3516          isUndefOrEqual(Mask[1], 7) &&
3517          isUndefOrEqual(Mask[2], 2) &&
3518          isUndefOrEqual(Mask[3], 3);
3519 }
3520
3521 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3522 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3523 /// <2, 3, 2, 3>
3524 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3525   if (!VT.is128BitVector())
3526     return false;
3527
3528   unsigned NumElems = VT.getVectorNumElements();
3529
3530   if (NumElems != 4)
3531     return false;
3532
3533   return isUndefOrEqual(Mask[0], 2) &&
3534          isUndefOrEqual(Mask[1], 3) &&
3535          isUndefOrEqual(Mask[2], 2) &&
3536          isUndefOrEqual(Mask[3], 3);
3537 }
3538
3539 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3540 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3541 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3542   if (!VT.is128BitVector())
3543     return false;
3544
3545   unsigned NumElems = VT.getVectorNumElements();
3546
3547   if (NumElems != 2 && NumElems != 4)
3548     return false;
3549
3550   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3551     if (!isUndefOrEqual(Mask[i], i + NumElems))
3552       return false;
3553
3554   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3555     if (!isUndefOrEqual(Mask[i], i))
3556       return false;
3557
3558   return true;
3559 }
3560
3561 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3562 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3563 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3564   if (!VT.is128BitVector())
3565     return false;
3566
3567   unsigned NumElems = VT.getVectorNumElements();
3568
3569   if (NumElems != 2 && NumElems != 4)
3570     return false;
3571
3572   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3573     if (!isUndefOrEqual(Mask[i], i))
3574       return false;
3575
3576   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3577     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3578       return false;
3579
3580   return true;
3581 }
3582
3583 //
3584 // Some special combinations that can be optimized.
3585 //
3586 static
3587 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3588                                SelectionDAG &DAG) {
3589   MVT VT = SVOp->getValueType(0).getSimpleVT();
3590   DebugLoc dl = SVOp->getDebugLoc();
3591
3592   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3593     return SDValue();
3594
3595   ArrayRef<int> Mask = SVOp->getMask();
3596
3597   // These are the special masks that may be optimized.
3598   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3599   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3600   bool MatchEvenMask = true;
3601   bool MatchOddMask  = true;
3602   for (int i=0; i<8; ++i) {
3603     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3604       MatchEvenMask = false;
3605     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3606       MatchOddMask = false;
3607   }
3608
3609   if (!MatchEvenMask && !MatchOddMask)
3610     return SDValue();
3611
3612   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3613
3614   SDValue Op0 = SVOp->getOperand(0);
3615   SDValue Op1 = SVOp->getOperand(1);
3616
3617   if (MatchEvenMask) {
3618     // Shift the second operand right to 32 bits.
3619     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3620     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3621   } else {
3622     // Shift the first operand left to 32 bits.
3623     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3624     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3625   }
3626   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3627   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3628 }
3629
3630 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3631 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3632 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3633                          bool HasInt256, bool V2IsSplat = false) {
3634   unsigned NumElts = VT.getVectorNumElements();
3635
3636   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3637          "Unsupported vector type for unpckh");
3638
3639   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3640       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3641     return false;
3642
3643   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3644   // independently on 128-bit lanes.
3645   unsigned NumLanes = VT.getSizeInBits()/128;
3646   unsigned NumLaneElts = NumElts/NumLanes;
3647
3648   for (unsigned l = 0; l != NumLanes; ++l) {
3649     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3650          i != (l+1)*NumLaneElts;
3651          i += 2, ++j) {
3652       int BitI  = Mask[i];
3653       int BitI1 = Mask[i+1];
3654       if (!isUndefOrEqual(BitI, j))
3655         return false;
3656       if (V2IsSplat) {
3657         if (!isUndefOrEqual(BitI1, NumElts))
3658           return false;
3659       } else {
3660         if (!isUndefOrEqual(BitI1, j + NumElts))
3661           return false;
3662       }
3663     }
3664   }
3665
3666   return true;
3667 }
3668
3669 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3670 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3671 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3672                          bool HasInt256, bool V2IsSplat = false) {
3673   unsigned NumElts = VT.getVectorNumElements();
3674
3675   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3676          "Unsupported vector type for unpckh");
3677
3678   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3679       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3680     return false;
3681
3682   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3683   // independently on 128-bit lanes.
3684   unsigned NumLanes = VT.getSizeInBits()/128;
3685   unsigned NumLaneElts = NumElts/NumLanes;
3686
3687   for (unsigned l = 0; l != NumLanes; ++l) {
3688     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3689          i != (l+1)*NumLaneElts; i += 2, ++j) {
3690       int BitI  = Mask[i];
3691       int BitI1 = Mask[i+1];
3692       if (!isUndefOrEqual(BitI, j))
3693         return false;
3694       if (V2IsSplat) {
3695         if (isUndefOrEqual(BitI1, NumElts))
3696           return false;
3697       } else {
3698         if (!isUndefOrEqual(BitI1, j+NumElts))
3699           return false;
3700       }
3701     }
3702   }
3703   return true;
3704 }
3705
3706 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3707 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3708 /// <0, 0, 1, 1>
3709 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3710   unsigned NumElts = VT.getVectorNumElements();
3711   bool Is256BitVec = VT.is256BitVector();
3712
3713   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3714          "Unsupported vector type for unpckh");
3715
3716   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3717       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3718     return false;
3719
3720   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3721   // FIXME: Need a better way to get rid of this, there's no latency difference
3722   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3723   // the former later. We should also remove the "_undef" special mask.
3724   if (NumElts == 4 && Is256BitVec)
3725     return false;
3726
3727   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3728   // independently on 128-bit lanes.
3729   unsigned NumLanes = VT.getSizeInBits()/128;
3730   unsigned NumLaneElts = NumElts/NumLanes;
3731
3732   for (unsigned l = 0; l != NumLanes; ++l) {
3733     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3734          i != (l+1)*NumLaneElts;
3735          i += 2, ++j) {
3736       int BitI  = Mask[i];
3737       int BitI1 = Mask[i+1];
3738
3739       if (!isUndefOrEqual(BitI, j))
3740         return false;
3741       if (!isUndefOrEqual(BitI1, j))
3742         return false;
3743     }
3744   }
3745
3746   return true;
3747 }
3748
3749 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3750 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3751 /// <2, 2, 3, 3>
3752 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3753   unsigned NumElts = VT.getVectorNumElements();
3754
3755   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3756          "Unsupported vector type for unpckh");
3757
3758   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3759       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3760     return false;
3761
3762   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3763   // independently on 128-bit lanes.
3764   unsigned NumLanes = VT.getSizeInBits()/128;
3765   unsigned NumLaneElts = NumElts/NumLanes;
3766
3767   for (unsigned l = 0; l != NumLanes; ++l) {
3768     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3769          i != (l+1)*NumLaneElts; i += 2, ++j) {
3770       int BitI  = Mask[i];
3771       int BitI1 = Mask[i+1];
3772       if (!isUndefOrEqual(BitI, j))
3773         return false;
3774       if (!isUndefOrEqual(BitI1, j))
3775         return false;
3776     }
3777   }
3778   return true;
3779 }
3780
3781 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3782 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3783 /// MOVSD, and MOVD, i.e. setting the lowest element.
3784 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3785   if (VT.getVectorElementType().getSizeInBits() < 32)
3786     return false;
3787   if (!VT.is128BitVector())
3788     return false;
3789
3790   unsigned NumElts = VT.getVectorNumElements();
3791
3792   if (!isUndefOrEqual(Mask[0], NumElts))
3793     return false;
3794
3795   for (unsigned i = 1; i != NumElts; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3803 /// as permutations between 128-bit chunks or halves. As an example: this
3804 /// shuffle bellow:
3805 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3806 /// The first half comes from the second half of V1 and the second half from the
3807 /// the second half of V2.
3808 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3809   if (!HasFp256 || !VT.is256BitVector())
3810     return false;
3811
3812   // The shuffle result is divided into half A and half B. In total the two
3813   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3814   // B must come from C, D, E or F.
3815   unsigned HalfSize = VT.getVectorNumElements()/2;
3816   bool MatchA = false, MatchB = false;
3817
3818   // Check if A comes from one of C, D, E, F.
3819   for (unsigned Half = 0; Half != 4; ++Half) {
3820     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3821       MatchA = true;
3822       break;
3823     }
3824   }
3825
3826   // Check if B comes from one of C, D, E, F.
3827   for (unsigned Half = 0; Half != 4; ++Half) {
3828     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3829       MatchB = true;
3830       break;
3831     }
3832   }
3833
3834   return MatchA && MatchB;
3835 }
3836
3837 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3838 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3839 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3840   MVT VT = SVOp->getValueType(0).getSimpleVT();
3841
3842   unsigned HalfSize = VT.getVectorNumElements()/2;
3843
3844   unsigned FstHalf = 0, SndHalf = 0;
3845   for (unsigned i = 0; i < HalfSize; ++i) {
3846     if (SVOp->getMaskElt(i) > 0) {
3847       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3848       break;
3849     }
3850   }
3851   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3852     if (SVOp->getMaskElt(i) > 0) {
3853       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3854       break;
3855     }
3856   }
3857
3858   return (FstHalf | (SndHalf << 4));
3859 }
3860
3861 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3862 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3863 /// Note that VPERMIL mask matching is different depending whether theunderlying
3864 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3865 /// to the same elements of the low, but to the higher half of the source.
3866 /// In VPERMILPD the two lanes could be shuffled independently of each other
3867 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3868 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3869   if (!HasFp256)
3870     return false;
3871
3872   unsigned NumElts = VT.getVectorNumElements();
3873   // Only match 256-bit with 32/64-bit types
3874   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3875     return false;
3876
3877   unsigned NumLanes = VT.getSizeInBits()/128;
3878   unsigned LaneSize = NumElts/NumLanes;
3879   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3880     for (unsigned i = 0; i != LaneSize; ++i) {
3881       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3882         return false;
3883       if (NumElts != 8 || l == 0)
3884         continue;
3885       // VPERMILPS handling
3886       if (Mask[i] < 0)
3887         continue;
3888       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3889         return false;
3890     }
3891   }
3892
3893   return true;
3894 }
3895
3896 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3897 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3898 /// element of vector 2 and the other elements to come from vector 1 in order.
3899 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3900                                bool V2IsSplat = false, bool V2IsUndef = false) {
3901   if (!VT.is128BitVector())
3902     return false;
3903
3904   unsigned NumOps = VT.getVectorNumElements();
3905   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3906     return false;
3907
3908   if (!isUndefOrEqual(Mask[0], 0))
3909     return false;
3910
3911   for (unsigned i = 1; i != NumOps; ++i)
3912     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3913           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3914           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3915       return false;
3916
3917   return true;
3918 }
3919
3920 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3921 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3922 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3923 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3924                            const X86Subtarget *Subtarget) {
3925   if (!Subtarget->hasSSE3())
3926     return false;
3927
3928   unsigned NumElems = VT.getVectorNumElements();
3929
3930   if ((VT.is128BitVector() && NumElems != 4) ||
3931       (VT.is256BitVector() && NumElems != 8))
3932     return false;
3933
3934   // "i+1" is the value the indexed mask element must have
3935   for (unsigned i = 0; i != NumElems; i += 2)
3936     if (!isUndefOrEqual(Mask[i], i+1) ||
3937         !isUndefOrEqual(Mask[i+1], i+1))
3938       return false;
3939
3940   return true;
3941 }
3942
3943 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3945 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3946 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3947                            const X86Subtarget *Subtarget) {
3948   if (!Subtarget->hasSSE3())
3949     return false;
3950
3951   unsigned NumElems = VT.getVectorNumElements();
3952
3953   if ((VT.is128BitVector() && NumElems != 4) ||
3954       (VT.is256BitVector() && NumElems != 8))
3955     return false;
3956
3957   // "i" is the value the indexed mask element must have
3958   for (unsigned i = 0; i != NumElems; i += 2)
3959     if (!isUndefOrEqual(Mask[i], i) ||
3960         !isUndefOrEqual(Mask[i+1], i))
3961       return false;
3962
3963   return true;
3964 }
3965
3966 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3967 /// specifies a shuffle of elements that is suitable for input to 256-bit
3968 /// version of MOVDDUP.
3969 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3970   if (!HasFp256 || !VT.is256BitVector())
3971     return false;
3972
3973   unsigned NumElts = VT.getVectorNumElements();
3974   if (NumElts != 4)
3975     return false;
3976
3977   for (unsigned i = 0; i != NumElts/2; ++i)
3978     if (!isUndefOrEqual(Mask[i], 0))
3979       return false;
3980   for (unsigned i = NumElts/2; i != NumElts; ++i)
3981     if (!isUndefOrEqual(Mask[i], NumElts/2))
3982       return false;
3983   return true;
3984 }
3985
3986 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3987 /// specifies a shuffle of elements that is suitable for input to 128-bit
3988 /// version of MOVDDUP.
3989 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3990   if (!VT.is128BitVector())
3991     return false;
3992
3993   unsigned e = VT.getVectorNumElements() / 2;
3994   for (unsigned i = 0; i != e; ++i)
3995     if (!isUndefOrEqual(Mask[i], i))
3996       return false;
3997   for (unsigned i = 0; i != e; ++i)
3998     if (!isUndefOrEqual(Mask[e+i], i))
3999       return false;
4000   return true;
4001 }
4002
4003 /// isVEXTRACTF128Index - Return true if the specified
4004 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4005 /// suitable for input to VEXTRACTF128.
4006 bool X86::isVEXTRACTF128Index(SDNode *N) {
4007   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4008     return false;
4009
4010   // The index should be aligned on a 128-bit boundary.
4011   uint64_t Index =
4012     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4013
4014   MVT VT = N->getValueType(0).getSimpleVT();
4015   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4016   bool Result = (Index * ElSize) % 128 == 0;
4017
4018   return Result;
4019 }
4020
4021 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4022 /// operand specifies a subvector insert that is suitable for input to
4023 /// VINSERTF128.
4024 bool X86::isVINSERTF128Index(SDNode *N) {
4025   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4026     return false;
4027
4028   // The index should be aligned on a 128-bit boundary.
4029   uint64_t Index =
4030     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4031
4032   MVT VT = N->getValueType(0).getSimpleVT();
4033   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4034   bool Result = (Index * ElSize) % 128 == 0;
4035
4036   return Result;
4037 }
4038
4039 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4040 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4041 /// Handles 128-bit and 256-bit.
4042 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4043   MVT VT = N->getValueType(0).getSimpleVT();
4044
4045   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4046          "Unsupported vector type for PSHUF/SHUFP");
4047
4048   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4049   // independently on 128-bit lanes.
4050   unsigned NumElts = VT.getVectorNumElements();
4051   unsigned NumLanes = VT.getSizeInBits()/128;
4052   unsigned NumLaneElts = NumElts/NumLanes;
4053
4054   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4055          "Only supports 2 or 4 elements per lane");
4056
4057   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4058   unsigned Mask = 0;
4059   for (unsigned i = 0; i != NumElts; ++i) {
4060     int Elt = N->getMaskElt(i);
4061     if (Elt < 0) continue;
4062     Elt &= NumLaneElts - 1;
4063     unsigned ShAmt = (i << Shift) % 8;
4064     Mask |= Elt << ShAmt;
4065   }
4066
4067   return Mask;
4068 }
4069
4070 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4072 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4073   MVT VT = N->getValueType(0).getSimpleVT();
4074
4075   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4076          "Unsupported vector type for PSHUFHW");
4077
4078   unsigned NumElts = VT.getVectorNumElements();
4079
4080   unsigned Mask = 0;
4081   for (unsigned l = 0; l != NumElts; l += 8) {
4082     // 8 nodes per lane, but we only care about the last 4.
4083     for (unsigned i = 0; i < 4; ++i) {
4084       int Elt = N->getMaskElt(l+i+4);
4085       if (Elt < 0) continue;
4086       Elt &= 0x3; // only 2-bits.
4087       Mask |= Elt << (i * 2);
4088     }
4089   }
4090
4091   return Mask;
4092 }
4093
4094 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4095 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4096 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4097   MVT VT = N->getValueType(0).getSimpleVT();
4098
4099   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4100          "Unsupported vector type for PSHUFHW");
4101
4102   unsigned NumElts = VT.getVectorNumElements();
4103
4104   unsigned Mask = 0;
4105   for (unsigned l = 0; l != NumElts; l += 8) {
4106     // 8 nodes per lane, but we only care about the first 4.
4107     for (unsigned i = 0; i < 4; ++i) {
4108       int Elt = N->getMaskElt(l+i);
4109       if (Elt < 0) continue;
4110       Elt &= 0x3; // only 2-bits
4111       Mask |= Elt << (i * 2);
4112     }
4113   }
4114
4115   return Mask;
4116 }
4117
4118 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4119 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4120 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4121   MVT VT = SVOp->getValueType(0).getSimpleVT();
4122   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4123
4124   unsigned NumElts = VT.getVectorNumElements();
4125   unsigned NumLanes = VT.getSizeInBits()/128;
4126   unsigned NumLaneElts = NumElts/NumLanes;
4127
4128   int Val = 0;
4129   unsigned i;
4130   for (i = 0; i != NumElts; ++i) {
4131     Val = SVOp->getMaskElt(i);
4132     if (Val >= 0)
4133       break;
4134   }
4135   if (Val >= (int)NumElts)
4136     Val -= NumElts - NumLaneElts;
4137
4138   assert(Val - i > 0 && "PALIGNR imm should be positive");
4139   return (Val - i) * EltSize;
4140 }
4141
4142 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4143 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4144 /// instructions.
4145 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4146   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4147     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4148
4149   uint64_t Index =
4150     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4151
4152   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4153   MVT ElVT = VecVT.getVectorElementType();
4154
4155   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4156   return Index / NumElemsPerChunk;
4157 }
4158
4159 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4160 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4161 /// instructions.
4162 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4163   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4164     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4165
4166   uint64_t Index =
4167     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4168
4169   MVT VecVT = N->getValueType(0).getSimpleVT();
4170   MVT ElVT = VecVT.getVectorElementType();
4171
4172   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4173   return Index / NumElemsPerChunk;
4174 }
4175
4176 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4177 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4178 /// Handles 256-bit.
4179 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4180   MVT VT = N->getValueType(0).getSimpleVT();
4181
4182   unsigned NumElts = VT.getVectorNumElements();
4183
4184   assert((VT.is256BitVector() && NumElts == 4) &&
4185          "Unsupported vector type for VPERMQ/VPERMPD");
4186
4187   unsigned Mask = 0;
4188   for (unsigned i = 0; i != NumElts; ++i) {
4189     int Elt = N->getMaskElt(i);
4190     if (Elt < 0)
4191       continue;
4192     Mask |= Elt << (i*2);
4193   }
4194
4195   return Mask;
4196 }
4197 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4198 /// constant +0.0.
4199 bool X86::isZeroNode(SDValue Elt) {
4200   return ((isa<ConstantSDNode>(Elt) &&
4201            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4202           (isa<ConstantFPSDNode>(Elt) &&
4203            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4204 }
4205
4206 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4207 /// their permute mask.
4208 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4209                                     SelectionDAG &DAG) {
4210   MVT VT = SVOp->getValueType(0).getSimpleVT();
4211   unsigned NumElems = VT.getVectorNumElements();
4212   SmallVector<int, 8> MaskVec;
4213
4214   for (unsigned i = 0; i != NumElems; ++i) {
4215     int Idx = SVOp->getMaskElt(i);
4216     if (Idx >= 0) {
4217       if (Idx < (int)NumElems)
4218         Idx += NumElems;
4219       else
4220         Idx -= NumElems;
4221     }
4222     MaskVec.push_back(Idx);
4223   }
4224   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4225                               SVOp->getOperand(0), &MaskVec[0]);
4226 }
4227
4228 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4229 /// match movhlps. The lower half elements should come from upper half of
4230 /// V1 (and in order), and the upper half elements should come from the upper
4231 /// half of V2 (and in order).
4232 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4233   if (!VT.is128BitVector())
4234     return false;
4235   if (VT.getVectorNumElements() != 4)
4236     return false;
4237   for (unsigned i = 0, e = 2; i != e; ++i)
4238     if (!isUndefOrEqual(Mask[i], i+2))
4239       return false;
4240   for (unsigned i = 2; i != 4; ++i)
4241     if (!isUndefOrEqual(Mask[i], i+4))
4242       return false;
4243   return true;
4244 }
4245
4246 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4247 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4248 /// required.
4249 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4250   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4251     return false;
4252   N = N->getOperand(0).getNode();
4253   if (!ISD::isNON_EXTLoad(N))
4254     return false;
4255   if (LD)
4256     *LD = cast<LoadSDNode>(N);
4257   return true;
4258 }
4259
4260 // Test whether the given value is a vector value which will be legalized
4261 // into a load.
4262 static bool WillBeConstantPoolLoad(SDNode *N) {
4263   if (N->getOpcode() != ISD::BUILD_VECTOR)
4264     return false;
4265
4266   // Check for any non-constant elements.
4267   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4268     switch (N->getOperand(i).getNode()->getOpcode()) {
4269     case ISD::UNDEF:
4270     case ISD::ConstantFP:
4271     case ISD::Constant:
4272       break;
4273     default:
4274       return false;
4275     }
4276
4277   // Vectors of all-zeros and all-ones are materialized with special
4278   // instructions rather than being loaded.
4279   return !ISD::isBuildVectorAllZeros(N) &&
4280          !ISD::isBuildVectorAllOnes(N);
4281 }
4282
4283 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4284 /// match movlp{s|d}. The lower half elements should come from lower half of
4285 /// V1 (and in order), and the upper half elements should come from the upper
4286 /// half of V2 (and in order). And since V1 will become the source of the
4287 /// MOVLP, it must be either a vector load or a scalar load to vector.
4288 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4289                                ArrayRef<int> Mask, EVT VT) {
4290   if (!VT.is128BitVector())
4291     return false;
4292
4293   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4294     return false;
4295   // Is V2 is a vector load, don't do this transformation. We will try to use
4296   // load folding shufps op.
4297   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4298     return false;
4299
4300   unsigned NumElems = VT.getVectorNumElements();
4301
4302   if (NumElems != 2 && NumElems != 4)
4303     return false;
4304   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4305     if (!isUndefOrEqual(Mask[i], i))
4306       return false;
4307   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4308     if (!isUndefOrEqual(Mask[i], i+NumElems))
4309       return false;
4310   return true;
4311 }
4312
4313 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4314 /// all the same.
4315 static bool isSplatVector(SDNode *N) {
4316   if (N->getOpcode() != ISD::BUILD_VECTOR)
4317     return false;
4318
4319   SDValue SplatValue = N->getOperand(0);
4320   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4321     if (N->getOperand(i) != SplatValue)
4322       return false;
4323   return true;
4324 }
4325
4326 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4327 /// to an zero vector.
4328 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4329 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4330   SDValue V1 = N->getOperand(0);
4331   SDValue V2 = N->getOperand(1);
4332   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4333   for (unsigned i = 0; i != NumElems; ++i) {
4334     int Idx = N->getMaskElt(i);
4335     if (Idx >= (int)NumElems) {
4336       unsigned Opc = V2.getOpcode();
4337       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4338         continue;
4339       if (Opc != ISD::BUILD_VECTOR ||
4340           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4341         return false;
4342     } else if (Idx >= 0) {
4343       unsigned Opc = V1.getOpcode();
4344       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4345         continue;
4346       if (Opc != ISD::BUILD_VECTOR ||
4347           !X86::isZeroNode(V1.getOperand(Idx)))
4348         return false;
4349     }
4350   }
4351   return true;
4352 }
4353
4354 /// getZeroVector - Returns a vector of specified type with all zero elements.
4355 ///
4356 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4357                              SelectionDAG &DAG, DebugLoc dl) {
4358   assert(VT.isVector() && "Expected a vector type");
4359
4360   // Always build SSE zero vectors as <4 x i32> bitcasted
4361   // to their dest type. This ensures they get CSE'd.
4362   SDValue Vec;
4363   if (VT.is128BitVector()) {  // SSE
4364     if (Subtarget->hasSSE2()) {  // SSE2
4365       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4366       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4367     } else { // SSE1
4368       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4369       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4370     }
4371   } else if (VT.is256BitVector()) { // AVX
4372     if (Subtarget->hasInt256()) { // AVX2
4373       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4374       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4376     } else {
4377       // 256-bit logic and arithmetic instructions in AVX are all
4378       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4379       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4380       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4381       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4382     }
4383   } else
4384     llvm_unreachable("Unexpected vector type");
4385
4386   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4387 }
4388
4389 /// getOnesVector - Returns a vector of specified type with all bits set.
4390 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4391 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4392 /// Then bitcast to their original type, ensuring they get CSE'd.
4393 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4394                              DebugLoc dl) {
4395   assert(VT.isVector() && "Expected a vector type");
4396
4397   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4398   SDValue Vec;
4399   if (VT.is256BitVector()) {
4400     if (HasInt256) { // AVX2
4401       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4403     } else { // AVX
4404       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4405       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4406     }
4407   } else if (VT.is128BitVector()) {
4408     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4409   } else
4410     llvm_unreachable("Unexpected vector type");
4411
4412   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4413 }
4414
4415 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4416 /// that point to V2 points to its first element.
4417 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4418   for (unsigned i = 0; i != NumElems; ++i) {
4419     if (Mask[i] > (int)NumElems) {
4420       Mask[i] = NumElems;
4421     }
4422   }
4423 }
4424
4425 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4426 /// operation of specified width.
4427 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4428                        SDValue V2) {
4429   unsigned NumElems = VT.getVectorNumElements();
4430   SmallVector<int, 8> Mask;
4431   Mask.push_back(NumElems);
4432   for (unsigned i = 1; i != NumElems; ++i)
4433     Mask.push_back(i);
4434   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4435 }
4436
4437 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4438 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4439                           SDValue V2) {
4440   unsigned NumElems = VT.getVectorNumElements();
4441   SmallVector<int, 8> Mask;
4442   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4443     Mask.push_back(i);
4444     Mask.push_back(i + NumElems);
4445   }
4446   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4447 }
4448
4449 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4450 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4451                           SDValue V2) {
4452   unsigned NumElems = VT.getVectorNumElements();
4453   SmallVector<int, 8> Mask;
4454   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4455     Mask.push_back(i + Half);
4456     Mask.push_back(i + NumElems + Half);
4457   }
4458   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4459 }
4460
4461 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4462 // a generic shuffle instruction because the target has no such instructions.
4463 // Generate shuffles which repeat i16 and i8 several times until they can be
4464 // represented by v4f32 and then be manipulated by target suported shuffles.
4465 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4466   EVT VT = V.getValueType();
4467   int NumElems = VT.getVectorNumElements();
4468   DebugLoc dl = V.getDebugLoc();
4469
4470   while (NumElems > 4) {
4471     if (EltNo < NumElems/2) {
4472       V = getUnpackl(DAG, dl, VT, V, V);
4473     } else {
4474       V = getUnpackh(DAG, dl, VT, V, V);
4475       EltNo -= NumElems/2;
4476     }
4477     NumElems >>= 1;
4478   }
4479   return V;
4480 }
4481
4482 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4483 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4484   EVT VT = V.getValueType();
4485   DebugLoc dl = V.getDebugLoc();
4486
4487   if (VT.is128BitVector()) {
4488     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4489     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4490     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4491                              &SplatMask[0]);
4492   } else if (VT.is256BitVector()) {
4493     // To use VPERMILPS to splat scalars, the second half of indicies must
4494     // refer to the higher part, which is a duplication of the lower one,
4495     // because VPERMILPS can only handle in-lane permutations.
4496     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4497                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4498
4499     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4500     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4501                              &SplatMask[0]);
4502   } else
4503     llvm_unreachable("Vector size not supported");
4504
4505   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4506 }
4507
4508 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4509 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4510   EVT SrcVT = SV->getValueType(0);
4511   SDValue V1 = SV->getOperand(0);
4512   DebugLoc dl = SV->getDebugLoc();
4513
4514   int EltNo = SV->getSplatIndex();
4515   int NumElems = SrcVT.getVectorNumElements();
4516   bool Is256BitVec = SrcVT.is256BitVector();
4517
4518   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4519          "Unknown how to promote splat for type");
4520
4521   // Extract the 128-bit part containing the splat element and update
4522   // the splat element index when it refers to the higher register.
4523   if (Is256BitVec) {
4524     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4525     if (EltNo >= NumElems/2)
4526       EltNo -= NumElems/2;
4527   }
4528
4529   // All i16 and i8 vector types can't be used directly by a generic shuffle
4530   // instruction because the target has no such instruction. Generate shuffles
4531   // which repeat i16 and i8 several times until they fit in i32, and then can
4532   // be manipulated by target suported shuffles.
4533   EVT EltVT = SrcVT.getVectorElementType();
4534   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4535     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4536
4537   // Recreate the 256-bit vector and place the same 128-bit vector
4538   // into the low and high part. This is necessary because we want
4539   // to use VPERM* to shuffle the vectors
4540   if (Is256BitVec) {
4541     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4542   }
4543
4544   return getLegalSplat(DAG, V1, EltNo);
4545 }
4546
4547 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4548 /// vector of zero or undef vector.  This produces a shuffle where the low
4549 /// element of V2 is swizzled into the zero/undef vector, landing at element
4550 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4551 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4552                                            bool IsZero,
4553                                            const X86Subtarget *Subtarget,
4554                                            SelectionDAG &DAG) {
4555   EVT VT = V2.getValueType();
4556   SDValue V1 = IsZero
4557     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4558   unsigned NumElems = VT.getVectorNumElements();
4559   SmallVector<int, 16> MaskVec;
4560   for (unsigned i = 0; i != NumElems; ++i)
4561     // If this is the insertion idx, put the low elt of V2 here.
4562     MaskVec.push_back(i == Idx ? NumElems : i);
4563   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4564 }
4565
4566 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4567 /// target specific opcode. Returns true if the Mask could be calculated.
4568 /// Sets IsUnary to true if only uses one source.
4569 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4570                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4571   unsigned NumElems = VT.getVectorNumElements();
4572   SDValue ImmN;
4573
4574   IsUnary = false;
4575   switch(N->getOpcode()) {
4576   case X86ISD::SHUFP:
4577     ImmN = N->getOperand(N->getNumOperands()-1);
4578     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4579     break;
4580   case X86ISD::UNPCKH:
4581     DecodeUNPCKHMask(VT, Mask);
4582     break;
4583   case X86ISD::UNPCKL:
4584     DecodeUNPCKLMask(VT, Mask);
4585     break;
4586   case X86ISD::MOVHLPS:
4587     DecodeMOVHLPSMask(NumElems, Mask);
4588     break;
4589   case X86ISD::MOVLHPS:
4590     DecodeMOVLHPSMask(NumElems, Mask);
4591     break;
4592   case X86ISD::PSHUFD:
4593   case X86ISD::VPERMILP:
4594     ImmN = N->getOperand(N->getNumOperands()-1);
4595     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596     IsUnary = true;
4597     break;
4598   case X86ISD::PSHUFHW:
4599     ImmN = N->getOperand(N->getNumOperands()-1);
4600     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601     IsUnary = true;
4602     break;
4603   case X86ISD::PSHUFLW:
4604     ImmN = N->getOperand(N->getNumOperands()-1);
4605     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606     IsUnary = true;
4607     break;
4608   case X86ISD::VPERMI:
4609     ImmN = N->getOperand(N->getNumOperands()-1);
4610     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611     IsUnary = true;
4612     break;
4613   case X86ISD::MOVSS:
4614   case X86ISD::MOVSD: {
4615     // The index 0 always comes from the first element of the second source,
4616     // this is why MOVSS and MOVSD are used in the first place. The other
4617     // elements come from the other positions of the first source vector
4618     Mask.push_back(NumElems);
4619     for (unsigned i = 1; i != NumElems; ++i) {
4620       Mask.push_back(i);
4621     }
4622     break;
4623   }
4624   case X86ISD::VPERM2X128:
4625     ImmN = N->getOperand(N->getNumOperands()-1);
4626     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627     if (Mask.empty()) return false;
4628     break;
4629   case X86ISD::MOVDDUP:
4630   case X86ISD::MOVLHPD:
4631   case X86ISD::MOVLPD:
4632   case X86ISD::MOVLPS:
4633   case X86ISD::MOVSHDUP:
4634   case X86ISD::MOVSLDUP:
4635   case X86ISD::PALIGN:
4636     // Not yet implemented
4637     return false;
4638   default: llvm_unreachable("unknown target shuffle node");
4639   }
4640
4641   return true;
4642 }
4643
4644 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4645 /// element of the result of the vector shuffle.
4646 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4647                                    unsigned Depth) {
4648   if (Depth == 6)
4649     return SDValue();  // Limit search depth.
4650
4651   SDValue V = SDValue(N, 0);
4652   EVT VT = V.getValueType();
4653   unsigned Opcode = V.getOpcode();
4654
4655   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4656   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4657     int Elt = SV->getMaskElt(Index);
4658
4659     if (Elt < 0)
4660       return DAG.getUNDEF(VT.getVectorElementType());
4661
4662     unsigned NumElems = VT.getVectorNumElements();
4663     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4664                                          : SV->getOperand(1);
4665     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4666   }
4667
4668   // Recurse into target specific vector shuffles to find scalars.
4669   if (isTargetShuffle(Opcode)) {
4670     MVT ShufVT = V.getValueType().getSimpleVT();
4671     unsigned NumElems = ShufVT.getVectorNumElements();
4672     SmallVector<int, 16> ShuffleMask;
4673     bool IsUnary;
4674
4675     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4676       return SDValue();
4677
4678     int Elt = ShuffleMask[Index];
4679     if (Elt < 0)
4680       return DAG.getUNDEF(ShufVT.getVectorElementType());
4681
4682     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4683                                          : N->getOperand(1);
4684     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4685                                Depth+1);
4686   }
4687
4688   // Actual nodes that may contain scalar elements
4689   if (Opcode == ISD::BITCAST) {
4690     V = V.getOperand(0);
4691     EVT SrcVT = V.getValueType();
4692     unsigned NumElems = VT.getVectorNumElements();
4693
4694     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4695       return SDValue();
4696   }
4697
4698   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4699     return (Index == 0) ? V.getOperand(0)
4700                         : DAG.getUNDEF(VT.getVectorElementType());
4701
4702   if (V.getOpcode() == ISD::BUILD_VECTOR)
4703     return V.getOperand(Index);
4704
4705   return SDValue();
4706 }
4707
4708 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4709 /// shuffle operation which come from a consecutively from a zero. The
4710 /// search can start in two different directions, from left or right.
4711 static
4712 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4713                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4714   unsigned i;
4715   for (i = 0; i != NumElems; ++i) {
4716     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4717     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4718     if (!(Elt.getNode() &&
4719          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4720       break;
4721   }
4722
4723   return i;
4724 }
4725
4726 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4727 /// correspond consecutively to elements from one of the vector operands,
4728 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4729 static
4730 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4731                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4732                               unsigned NumElems, unsigned &OpNum) {
4733   bool SeenV1 = false;
4734   bool SeenV2 = false;
4735
4736   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4737     int Idx = SVOp->getMaskElt(i);
4738     // Ignore undef indicies
4739     if (Idx < 0)
4740       continue;
4741
4742     if (Idx < (int)NumElems)
4743       SeenV1 = true;
4744     else
4745       SeenV2 = true;
4746
4747     // Only accept consecutive elements from the same vector
4748     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4749       return false;
4750   }
4751
4752   OpNum = SeenV1 ? 0 : 1;
4753   return true;
4754 }
4755
4756 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4757 /// logical left shift of a vector.
4758 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4759                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4760   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4761   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4762               false /* check zeros from right */, DAG);
4763   unsigned OpSrc;
4764
4765   if (!NumZeros)
4766     return false;
4767
4768   // Considering the elements in the mask that are not consecutive zeros,
4769   // check if they consecutively come from only one of the source vectors.
4770   //
4771   //               V1 = {X, A, B, C}     0
4772   //                         \  \  \    /
4773   //   vector_shuffle V1, V2 <1, 2, 3, X>
4774   //
4775   if (!isShuffleMaskConsecutive(SVOp,
4776             0,                   // Mask Start Index
4777             NumElems-NumZeros,   // Mask End Index(exclusive)
4778             NumZeros,            // Where to start looking in the src vector
4779             NumElems,            // Number of elements in vector
4780             OpSrc))              // Which source operand ?
4781     return false;
4782
4783   isLeft = false;
4784   ShAmt = NumZeros;
4785   ShVal = SVOp->getOperand(OpSrc);
4786   return true;
4787 }
4788
4789 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4790 /// logical left shift of a vector.
4791 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4792                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4793   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4794   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4795               true /* check zeros from left */, DAG);
4796   unsigned OpSrc;
4797
4798   if (!NumZeros)
4799     return false;
4800
4801   // Considering the elements in the mask that are not consecutive zeros,
4802   // check if they consecutively come from only one of the source vectors.
4803   //
4804   //                           0    { A, B, X, X } = V2
4805   //                          / \    /  /
4806   //   vector_shuffle V1, V2 <X, X, 4, 5>
4807   //
4808   if (!isShuffleMaskConsecutive(SVOp,
4809             NumZeros,     // Mask Start Index
4810             NumElems,     // Mask End Index(exclusive)
4811             0,            // Where to start looking in the src vector
4812             NumElems,     // Number of elements in vector
4813             OpSrc))       // Which source operand ?
4814     return false;
4815
4816   isLeft = true;
4817   ShAmt = NumZeros;
4818   ShVal = SVOp->getOperand(OpSrc);
4819   return true;
4820 }
4821
4822 /// isVectorShift - Returns true if the shuffle can be implemented as a
4823 /// logical left or right shift of a vector.
4824 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4825                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4826   // Although the logic below support any bitwidth size, there are no
4827   // shift instructions which handle more than 128-bit vectors.
4828   if (!SVOp->getValueType(0).is128BitVector())
4829     return false;
4830
4831   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4832       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4833     return true;
4834
4835   return false;
4836 }
4837
4838 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4839 ///
4840 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4841                                        unsigned NumNonZero, unsigned NumZero,
4842                                        SelectionDAG &DAG,
4843                                        const X86Subtarget* Subtarget,
4844                                        const TargetLowering &TLI) {
4845   if (NumNonZero > 8)
4846     return SDValue();
4847
4848   DebugLoc dl = Op.getDebugLoc();
4849   SDValue V(0, 0);
4850   bool First = true;
4851   for (unsigned i = 0; i < 16; ++i) {
4852     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4853     if (ThisIsNonZero && First) {
4854       if (NumZero)
4855         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4856       else
4857         V = DAG.getUNDEF(MVT::v8i16);
4858       First = false;
4859     }
4860
4861     if ((i & 1) != 0) {
4862       SDValue ThisElt(0, 0), LastElt(0, 0);
4863       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4864       if (LastIsNonZero) {
4865         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4866                               MVT::i16, Op.getOperand(i-1));
4867       }
4868       if (ThisIsNonZero) {
4869         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4870         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4871                               ThisElt, DAG.getConstant(8, MVT::i8));
4872         if (LastIsNonZero)
4873           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4874       } else
4875         ThisElt = LastElt;
4876
4877       if (ThisElt.getNode())
4878         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4879                         DAG.getIntPtrConstant(i/2));
4880     }
4881   }
4882
4883   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4884 }
4885
4886 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4887 ///
4888 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4889                                      unsigned NumNonZero, unsigned NumZero,
4890                                      SelectionDAG &DAG,
4891                                      const X86Subtarget* Subtarget,
4892                                      const TargetLowering &TLI) {
4893   if (NumNonZero > 4)
4894     return SDValue();
4895
4896   DebugLoc dl = Op.getDebugLoc();
4897   SDValue V(0, 0);
4898   bool First = true;
4899   for (unsigned i = 0; i < 8; ++i) {
4900     bool isNonZero = (NonZeros & (1 << i)) != 0;
4901     if (isNonZero) {
4902       if (First) {
4903         if (NumZero)
4904           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4905         else
4906           V = DAG.getUNDEF(MVT::v8i16);
4907         First = false;
4908       }
4909       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4910                       MVT::v8i16, V, Op.getOperand(i),
4911                       DAG.getIntPtrConstant(i));
4912     }
4913   }
4914
4915   return V;
4916 }
4917
4918 /// getVShift - Return a vector logical shift node.
4919 ///
4920 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4921                          unsigned NumBits, SelectionDAG &DAG,
4922                          const TargetLowering &TLI, DebugLoc dl) {
4923   assert(VT.is128BitVector() && "Unknown type for VShift");
4924   EVT ShVT = MVT::v2i64;
4925   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4926   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4927   return DAG.getNode(ISD::BITCAST, dl, VT,
4928                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4929                              DAG.getConstant(NumBits,
4930                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4931 }
4932
4933 SDValue
4934 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4935                                           SelectionDAG &DAG) const {
4936
4937   // Check if the scalar load can be widened into a vector load. And if
4938   // the address is "base + cst" see if the cst can be "absorbed" into
4939   // the shuffle mask.
4940   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4941     SDValue Ptr = LD->getBasePtr();
4942     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4943       return SDValue();
4944     EVT PVT = LD->getValueType(0);
4945     if (PVT != MVT::i32 && PVT != MVT::f32)
4946       return SDValue();
4947
4948     int FI = -1;
4949     int64_t Offset = 0;
4950     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4951       FI = FINode->getIndex();
4952       Offset = 0;
4953     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4954                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4955       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4956       Offset = Ptr.getConstantOperandVal(1);
4957       Ptr = Ptr.getOperand(0);
4958     } else {
4959       return SDValue();
4960     }
4961
4962     // FIXME: 256-bit vector instructions don't require a strict alignment,
4963     // improve this code to support it better.
4964     unsigned RequiredAlign = VT.getSizeInBits()/8;
4965     SDValue Chain = LD->getChain();
4966     // Make sure the stack object alignment is at least 16 or 32.
4967     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4968     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4969       if (MFI->isFixedObjectIndex(FI)) {
4970         // Can't change the alignment. FIXME: It's possible to compute
4971         // the exact stack offset and reference FI + adjust offset instead.
4972         // If someone *really* cares about this. That's the way to implement it.
4973         return SDValue();
4974       } else {
4975         MFI->setObjectAlignment(FI, RequiredAlign);
4976       }
4977     }
4978
4979     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4980     // Ptr + (Offset & ~15).
4981     if (Offset < 0)
4982       return SDValue();
4983     if ((Offset % RequiredAlign) & 3)
4984       return SDValue();
4985     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4986     if (StartOffset)
4987       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4988                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4989
4990     int EltNo = (Offset - StartOffset) >> 2;
4991     unsigned NumElems = VT.getVectorNumElements();
4992
4993     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4994     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4995                              LD->getPointerInfo().getWithOffset(StartOffset),
4996                              false, false, false, 0);
4997
4998     SmallVector<int, 8> Mask;
4999     for (unsigned i = 0; i != NumElems; ++i)
5000       Mask.push_back(EltNo);
5001
5002     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5003   }
5004
5005   return SDValue();
5006 }
5007
5008 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5009 /// vector of type 'VT', see if the elements can be replaced by a single large
5010 /// load which has the same value as a build_vector whose operands are 'elts'.
5011 ///
5012 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5013 ///
5014 /// FIXME: we'd also like to handle the case where the last elements are zero
5015 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5016 /// There's even a handy isZeroNode for that purpose.
5017 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5018                                         DebugLoc &DL, SelectionDAG &DAG) {
5019   EVT EltVT = VT.getVectorElementType();
5020   unsigned NumElems = Elts.size();
5021
5022   LoadSDNode *LDBase = NULL;
5023   unsigned LastLoadedElt = -1U;
5024
5025   // For each element in the initializer, see if we've found a load or an undef.
5026   // If we don't find an initial load element, or later load elements are
5027   // non-consecutive, bail out.
5028   for (unsigned i = 0; i < NumElems; ++i) {
5029     SDValue Elt = Elts[i];
5030
5031     if (!Elt.getNode() ||
5032         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5033       return SDValue();
5034     if (!LDBase) {
5035       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5036         return SDValue();
5037       LDBase = cast<LoadSDNode>(Elt.getNode());
5038       LastLoadedElt = i;
5039       continue;
5040     }
5041     if (Elt.getOpcode() == ISD::UNDEF)
5042       continue;
5043
5044     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5045     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5046       return SDValue();
5047     LastLoadedElt = i;
5048   }
5049
5050   // If we have found an entire vector of loads and undefs, then return a large
5051   // load of the entire vector width starting at the base pointer.  If we found
5052   // consecutive loads for the low half, generate a vzext_load node.
5053   if (LastLoadedElt == NumElems - 1) {
5054     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5055       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5056                          LDBase->getPointerInfo(),
5057                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5058                          LDBase->isInvariant(), 0);
5059     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5060                        LDBase->getPointerInfo(),
5061                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5062                        LDBase->isInvariant(), LDBase->getAlignment());
5063   }
5064   if (NumElems == 4 && LastLoadedElt == 1 &&
5065       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5066     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5067     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5068     SDValue ResNode =
5069         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5070                                 LDBase->getPointerInfo(),
5071                                 LDBase->getAlignment(),
5072                                 false/*isVolatile*/, true/*ReadMem*/,
5073                                 false/*WriteMem*/);
5074
5075     // Make sure the newly-created LOAD is in the same position as LDBase in
5076     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5077     // update uses of LDBase's output chain to use the TokenFactor.
5078     if (LDBase->hasAnyUseOfValue(1)) {
5079       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5080                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5081       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5082       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5083                              SDValue(ResNode.getNode(), 1));
5084     }
5085
5086     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5087   }
5088   return SDValue();
5089 }
5090
5091 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5092 /// to generate a splat value for the following cases:
5093 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5094 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5095 /// a scalar load, or a constant.
5096 /// The VBROADCAST node is returned when a pattern is found,
5097 /// or SDValue() otherwise.
5098 SDValue
5099 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5100   if (!Subtarget->hasFp256())
5101     return SDValue();
5102
5103   MVT VT = Op.getValueType().getSimpleVT();
5104   DebugLoc dl = Op.getDebugLoc();
5105
5106   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5107          "Unsupported vector type for broadcast.");
5108
5109   SDValue Ld;
5110   bool ConstSplatVal;
5111
5112   switch (Op.getOpcode()) {
5113     default:
5114       // Unknown pattern found.
5115       return SDValue();
5116
5117     case ISD::BUILD_VECTOR: {
5118       // The BUILD_VECTOR node must be a splat.
5119       if (!isSplatVector(Op.getNode()))
5120         return SDValue();
5121
5122       Ld = Op.getOperand(0);
5123       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5124                      Ld.getOpcode() == ISD::ConstantFP);
5125
5126       // The suspected load node has several users. Make sure that all
5127       // of its users are from the BUILD_VECTOR node.
5128       // Constants may have multiple users.
5129       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5130         return SDValue();
5131       break;
5132     }
5133
5134     case ISD::VECTOR_SHUFFLE: {
5135       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5136
5137       // Shuffles must have a splat mask where the first element is
5138       // broadcasted.
5139       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5140         return SDValue();
5141
5142       SDValue Sc = Op.getOperand(0);
5143       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5144           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5145
5146         if (!Subtarget->hasInt256())
5147           return SDValue();
5148
5149         // Use the register form of the broadcast instruction available on AVX2.
5150         if (VT.is256BitVector())
5151           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5152         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5153       }
5154
5155       Ld = Sc.getOperand(0);
5156       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5157                        Ld.getOpcode() == ISD::ConstantFP);
5158
5159       // The scalar_to_vector node and the suspected
5160       // load node must have exactly one user.
5161       // Constants may have multiple users.
5162       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5163         return SDValue();
5164       break;
5165     }
5166   }
5167
5168   bool Is256 = VT.is256BitVector();
5169
5170   // Handle the broadcasting a single constant scalar from the constant pool
5171   // into a vector. On Sandybridge it is still better to load a constant vector
5172   // from the constant pool and not to broadcast it from a scalar.
5173   if (ConstSplatVal && Subtarget->hasInt256()) {
5174     EVT CVT = Ld.getValueType();
5175     assert(!CVT.isVector() && "Must not broadcast a vector type");
5176     unsigned ScalarSize = CVT.getSizeInBits();
5177
5178     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5179       const Constant *C = 0;
5180       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5181         C = CI->getConstantIntValue();
5182       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5183         C = CF->getConstantFPValue();
5184
5185       assert(C && "Invalid constant type");
5186
5187       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5188       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5189       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5190                        MachinePointerInfo::getConstantPool(),
5191                        false, false, false, Alignment);
5192
5193       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5194     }
5195   }
5196
5197   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5198   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5199
5200   // Handle AVX2 in-register broadcasts.
5201   if (!IsLoad && Subtarget->hasInt256() &&
5202       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5203     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5204
5205   // The scalar source must be a normal load.
5206   if (!IsLoad)
5207     return SDValue();
5208
5209   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5210     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5211
5212   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5213   // double since there is no vbroadcastsd xmm
5214   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5215     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5216       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5217   }
5218
5219   // Unsupported broadcast.
5220   return SDValue();
5221 }
5222
5223 SDValue
5224 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5225   EVT VT = Op.getValueType();
5226
5227   // Skip if insert_vec_elt is not supported.
5228   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5229     return SDValue();
5230
5231   DebugLoc DL = Op.getDebugLoc();
5232   unsigned NumElems = Op.getNumOperands();
5233
5234   SDValue VecIn1;
5235   SDValue VecIn2;
5236   SmallVector<unsigned, 4> InsertIndices;
5237   SmallVector<int, 8> Mask(NumElems, -1);
5238
5239   for (unsigned i = 0; i != NumElems; ++i) {
5240     unsigned Opc = Op.getOperand(i).getOpcode();
5241
5242     if (Opc == ISD::UNDEF)
5243       continue;
5244
5245     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5246       // Quit if more than 1 elements need inserting.
5247       if (InsertIndices.size() > 1)
5248         return SDValue();
5249
5250       InsertIndices.push_back(i);
5251       continue;
5252     }
5253
5254     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5255     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5256
5257     // Quit if extracted from vector of different type.
5258     if (ExtractedFromVec.getValueType() != VT)
5259       return SDValue();
5260
5261     // Quit if non-constant index.
5262     if (!isa<ConstantSDNode>(ExtIdx))
5263       return SDValue();
5264
5265     if (VecIn1.getNode() == 0)
5266       VecIn1 = ExtractedFromVec;
5267     else if (VecIn1 != ExtractedFromVec) {
5268       if (VecIn2.getNode() == 0)
5269         VecIn2 = ExtractedFromVec;
5270       else if (VecIn2 != ExtractedFromVec)
5271         // Quit if more than 2 vectors to shuffle
5272         return SDValue();
5273     }
5274
5275     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5276
5277     if (ExtractedFromVec == VecIn1)
5278       Mask[i] = Idx;
5279     else if (ExtractedFromVec == VecIn2)
5280       Mask[i] = Idx + NumElems;
5281   }
5282
5283   if (VecIn1.getNode() == 0)
5284     return SDValue();
5285
5286   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5287   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5288   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5289     unsigned Idx = InsertIndices[i];
5290     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5291                      DAG.getIntPtrConstant(Idx));
5292   }
5293
5294   return NV;
5295 }
5296
5297 SDValue
5298 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5299   DebugLoc dl = Op.getDebugLoc();
5300
5301   MVT VT = Op.getValueType().getSimpleVT();
5302   MVT ExtVT = VT.getVectorElementType();
5303   unsigned NumElems = Op.getNumOperands();
5304
5305   // Vectors containing all zeros can be matched by pxor and xorps later
5306   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5307     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5308     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5309     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5310       return Op;
5311
5312     return getZeroVector(VT, Subtarget, DAG, dl);
5313   }
5314
5315   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5316   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5317   // vpcmpeqd on 256-bit vectors.
5318   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5319     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5320       return Op;
5321
5322     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5323   }
5324
5325   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5326   if (Broadcast.getNode())
5327     return Broadcast;
5328
5329   unsigned EVTBits = ExtVT.getSizeInBits();
5330
5331   unsigned NumZero  = 0;
5332   unsigned NumNonZero = 0;
5333   unsigned NonZeros = 0;
5334   bool IsAllConstants = true;
5335   SmallSet<SDValue, 8> Values;
5336   for (unsigned i = 0; i < NumElems; ++i) {
5337     SDValue Elt = Op.getOperand(i);
5338     if (Elt.getOpcode() == ISD::UNDEF)
5339       continue;
5340     Values.insert(Elt);
5341     if (Elt.getOpcode() != ISD::Constant &&
5342         Elt.getOpcode() != ISD::ConstantFP)
5343       IsAllConstants = false;
5344     if (X86::isZeroNode(Elt))
5345       NumZero++;
5346     else {
5347       NonZeros |= (1 << i);
5348       NumNonZero++;
5349     }
5350   }
5351
5352   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5353   if (NumNonZero == 0)
5354     return DAG.getUNDEF(VT);
5355
5356   // Special case for single non-zero, non-undef, element.
5357   if (NumNonZero == 1) {
5358     unsigned Idx = CountTrailingZeros_32(NonZeros);
5359     SDValue Item = Op.getOperand(Idx);
5360
5361     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5362     // the value are obviously zero, truncate the value to i32 and do the
5363     // insertion that way.  Only do this if the value is non-constant or if the
5364     // value is a constant being inserted into element 0.  It is cheaper to do
5365     // a constant pool load than it is to do a movd + shuffle.
5366     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5367         (!IsAllConstants || Idx == 0)) {
5368       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5369         // Handle SSE only.
5370         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5371         EVT VecVT = MVT::v4i32;
5372         unsigned VecElts = 4;
5373
5374         // Truncate the value (which may itself be a constant) to i32, and
5375         // convert it to a vector with movd (S2V+shuffle to zero extend).
5376         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5377         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5378         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5379
5380         // Now we have our 32-bit value zero extended in the low element of
5381         // a vector.  If Idx != 0, swizzle it into place.
5382         if (Idx != 0) {
5383           SmallVector<int, 4> Mask;
5384           Mask.push_back(Idx);
5385           for (unsigned i = 1; i != VecElts; ++i)
5386             Mask.push_back(i);
5387           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5388                                       &Mask[0]);
5389         }
5390         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5391       }
5392     }
5393
5394     // If we have a constant or non-constant insertion into the low element of
5395     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5396     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5397     // depending on what the source datatype is.
5398     if (Idx == 0) {
5399       if (NumZero == 0)
5400         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5401
5402       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5403           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5404         if (VT.is256BitVector()) {
5405           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5406           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5407                              Item, DAG.getIntPtrConstant(0));
5408         }
5409         assert(VT.is128BitVector() && "Expected an SSE value type!");
5410         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5411         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5412         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5413       }
5414
5415       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5416         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5417         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5418         if (VT.is256BitVector()) {
5419           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5420           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5421         } else {
5422           assert(VT.is128BitVector() && "Expected an SSE value type!");
5423           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5424         }
5425         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5426       }
5427     }
5428
5429     // Is it a vector logical left shift?
5430     if (NumElems == 2 && Idx == 1 &&
5431         X86::isZeroNode(Op.getOperand(0)) &&
5432         !X86::isZeroNode(Op.getOperand(1))) {
5433       unsigned NumBits = VT.getSizeInBits();
5434       return getVShift(true, VT,
5435                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5436                                    VT, Op.getOperand(1)),
5437                        NumBits/2, DAG, *this, dl);
5438     }
5439
5440     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5441       return SDValue();
5442
5443     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5444     // is a non-constant being inserted into an element other than the low one,
5445     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5446     // movd/movss) to move this into the low element, then shuffle it into
5447     // place.
5448     if (EVTBits == 32) {
5449       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5450
5451       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5452       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5453       SmallVector<int, 8> MaskVec;
5454       for (unsigned i = 0; i != NumElems; ++i)
5455         MaskVec.push_back(i == Idx ? 0 : 1);
5456       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5457     }
5458   }
5459
5460   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5461   if (Values.size() == 1) {
5462     if (EVTBits == 32) {
5463       // Instead of a shuffle like this:
5464       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5465       // Check if it's possible to issue this instead.
5466       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5467       unsigned Idx = CountTrailingZeros_32(NonZeros);
5468       SDValue Item = Op.getOperand(Idx);
5469       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5470         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5471     }
5472     return SDValue();
5473   }
5474
5475   // A vector full of immediates; various special cases are already
5476   // handled, so this is best done with a single constant-pool load.
5477   if (IsAllConstants)
5478     return SDValue();
5479
5480   // For AVX-length vectors, build the individual 128-bit pieces and use
5481   // shuffles to put them in place.
5482   if (VT.is256BitVector()) {
5483     SmallVector<SDValue, 32> V;
5484     for (unsigned i = 0; i != NumElems; ++i)
5485       V.push_back(Op.getOperand(i));
5486
5487     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5488
5489     // Build both the lower and upper subvector.
5490     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5491     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5492                                 NumElems/2);
5493
5494     // Recreate the wider vector with the lower and upper part.
5495     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5496   }
5497
5498   // Let legalizer expand 2-wide build_vectors.
5499   if (EVTBits == 64) {
5500     if (NumNonZero == 1) {
5501       // One half is zero or undef.
5502       unsigned Idx = CountTrailingZeros_32(NonZeros);
5503       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5504                                  Op.getOperand(Idx));
5505       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5506     }
5507     return SDValue();
5508   }
5509
5510   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5511   if (EVTBits == 8 && NumElems == 16) {
5512     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5513                                         Subtarget, *this);
5514     if (V.getNode()) return V;
5515   }
5516
5517   if (EVTBits == 16 && NumElems == 8) {
5518     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5519                                       Subtarget, *this);
5520     if (V.getNode()) return V;
5521   }
5522
5523   // If element VT is == 32 bits, turn it into a number of shuffles.
5524   SmallVector<SDValue, 8> V(NumElems);
5525   if (NumElems == 4 && NumZero > 0) {
5526     for (unsigned i = 0; i < 4; ++i) {
5527       bool isZero = !(NonZeros & (1 << i));
5528       if (isZero)
5529         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5530       else
5531         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5532     }
5533
5534     for (unsigned i = 0; i < 2; ++i) {
5535       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5536         default: break;
5537         case 0:
5538           V[i] = V[i*2];  // Must be a zero vector.
5539           break;
5540         case 1:
5541           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5542           break;
5543         case 2:
5544           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5545           break;
5546         case 3:
5547           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5548           break;
5549       }
5550     }
5551
5552     bool Reverse1 = (NonZeros & 0x3) == 2;
5553     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5554     int MaskVec[] = {
5555       Reverse1 ? 1 : 0,
5556       Reverse1 ? 0 : 1,
5557       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5558       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5559     };
5560     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5561   }
5562
5563   if (Values.size() > 1 && VT.is128BitVector()) {
5564     // Check for a build vector of consecutive loads.
5565     for (unsigned i = 0; i < NumElems; ++i)
5566       V[i] = Op.getOperand(i);
5567
5568     // Check for elements which are consecutive loads.
5569     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5570     if (LD.getNode())
5571       return LD;
5572
5573     // Check for a build vector from mostly shuffle plus few inserting.
5574     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5575     if (Sh.getNode())
5576       return Sh;
5577
5578     // For SSE 4.1, use insertps to put the high elements into the low element.
5579     if (getSubtarget()->hasSSE41()) {
5580       SDValue Result;
5581       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5582         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5583       else
5584         Result = DAG.getUNDEF(VT);
5585
5586       for (unsigned i = 1; i < NumElems; ++i) {
5587         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5588         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5589                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5590       }
5591       return Result;
5592     }
5593
5594     // Otherwise, expand into a number of unpckl*, start by extending each of
5595     // our (non-undef) elements to the full vector width with the element in the
5596     // bottom slot of the vector (which generates no code for SSE).
5597     for (unsigned i = 0; i < NumElems; ++i) {
5598       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5599         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5600       else
5601         V[i] = DAG.getUNDEF(VT);
5602     }
5603
5604     // Next, we iteratively mix elements, e.g. for v4f32:
5605     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5606     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5607     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5608     unsigned EltStride = NumElems >> 1;
5609     while (EltStride != 0) {
5610       for (unsigned i = 0; i < EltStride; ++i) {
5611         // If V[i+EltStride] is undef and this is the first round of mixing,
5612         // then it is safe to just drop this shuffle: V[i] is already in the
5613         // right place, the one element (since it's the first round) being
5614         // inserted as undef can be dropped.  This isn't safe for successive
5615         // rounds because they will permute elements within both vectors.
5616         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5617             EltStride == NumElems/2)
5618           continue;
5619
5620         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5621       }
5622       EltStride >>= 1;
5623     }
5624     return V[0];
5625   }
5626   return SDValue();
5627 }
5628
5629 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5630 // to create 256-bit vectors from two other 128-bit ones.
5631 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5632   DebugLoc dl = Op.getDebugLoc();
5633   MVT ResVT = Op.getValueType().getSimpleVT();
5634
5635   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5636
5637   SDValue V1 = Op.getOperand(0);
5638   SDValue V2 = Op.getOperand(1);
5639   unsigned NumElems = ResVT.getVectorNumElements();
5640
5641   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5642 }
5643
5644 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5645   assert(Op.getNumOperands() == 2);
5646
5647   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5648   // from two other 128-bit ones.
5649   return LowerAVXCONCAT_VECTORS(Op, DAG);
5650 }
5651
5652 // Try to lower a shuffle node into a simple blend instruction.
5653 static SDValue
5654 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5655                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5656   SDValue V1 = SVOp->getOperand(0);
5657   SDValue V2 = SVOp->getOperand(1);
5658   DebugLoc dl = SVOp->getDebugLoc();
5659   MVT VT = SVOp->getValueType(0).getSimpleVT();
5660   MVT EltVT = VT.getVectorElementType();
5661   unsigned NumElems = VT.getVectorNumElements();
5662
5663   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5664     return SDValue();
5665   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5666     return SDValue();
5667
5668   // Check the mask for BLEND and build the value.
5669   unsigned MaskValue = 0;
5670   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5671   unsigned NumLanes = (NumElems-1)/8 + 1;
5672   unsigned NumElemsInLane = NumElems / NumLanes;
5673
5674   // Blend for v16i16 should be symetric for the both lanes.
5675   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5676
5677     int SndLaneEltIdx = (NumLanes == 2) ?
5678       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5679     int EltIdx = SVOp->getMaskElt(i);
5680
5681     if ((EltIdx < 0 || EltIdx == (int)i) &&
5682         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5683       continue;
5684
5685     if (((unsigned)EltIdx == (i + NumElems)) &&
5686         (SndLaneEltIdx < 0 ||
5687          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5688       MaskValue |= (1<<i);
5689     else
5690       return SDValue();
5691   }
5692
5693   // Convert i32 vectors to floating point if it is not AVX2.
5694   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5695   MVT BlendVT = VT;
5696   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5697     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5698                                NumElems);
5699     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5700     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5701   }
5702
5703   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5704                             DAG.getConstant(MaskValue, MVT::i32));
5705   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5706 }
5707
5708 // v8i16 shuffles - Prefer shuffles in the following order:
5709 // 1. [all]   pshuflw, pshufhw, optional move
5710 // 2. [ssse3] 1 x pshufb
5711 // 3. [ssse3] 2 x pshufb + 1 x por
5712 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5713 static SDValue
5714 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5715                          SelectionDAG &DAG) {
5716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5717   SDValue V1 = SVOp->getOperand(0);
5718   SDValue V2 = SVOp->getOperand(1);
5719   DebugLoc dl = SVOp->getDebugLoc();
5720   SmallVector<int, 8> MaskVals;
5721
5722   // Determine if more than 1 of the words in each of the low and high quadwords
5723   // of the result come from the same quadword of one of the two inputs.  Undef
5724   // mask values count as coming from any quadword, for better codegen.
5725   unsigned LoQuad[] = { 0, 0, 0, 0 };
5726   unsigned HiQuad[] = { 0, 0, 0, 0 };
5727   std::bitset<4> InputQuads;
5728   for (unsigned i = 0; i < 8; ++i) {
5729     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5730     int EltIdx = SVOp->getMaskElt(i);
5731     MaskVals.push_back(EltIdx);
5732     if (EltIdx < 0) {
5733       ++Quad[0];
5734       ++Quad[1];
5735       ++Quad[2];
5736       ++Quad[3];
5737       continue;
5738     }
5739     ++Quad[EltIdx / 4];
5740     InputQuads.set(EltIdx / 4);
5741   }
5742
5743   int BestLoQuad = -1;
5744   unsigned MaxQuad = 1;
5745   for (unsigned i = 0; i < 4; ++i) {
5746     if (LoQuad[i] > MaxQuad) {
5747       BestLoQuad = i;
5748       MaxQuad = LoQuad[i];
5749     }
5750   }
5751
5752   int BestHiQuad = -1;
5753   MaxQuad = 1;
5754   for (unsigned i = 0; i < 4; ++i) {
5755     if (HiQuad[i] > MaxQuad) {
5756       BestHiQuad = i;
5757       MaxQuad = HiQuad[i];
5758     }
5759   }
5760
5761   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5762   // of the two input vectors, shuffle them into one input vector so only a
5763   // single pshufb instruction is necessary. If There are more than 2 input
5764   // quads, disable the next transformation since it does not help SSSE3.
5765   bool V1Used = InputQuads[0] || InputQuads[1];
5766   bool V2Used = InputQuads[2] || InputQuads[3];
5767   if (Subtarget->hasSSSE3()) {
5768     if (InputQuads.count() == 2 && V1Used && V2Used) {
5769       BestLoQuad = InputQuads[0] ? 0 : 1;
5770       BestHiQuad = InputQuads[2] ? 2 : 3;
5771     }
5772     if (InputQuads.count() > 2) {
5773       BestLoQuad = -1;
5774       BestHiQuad = -1;
5775     }
5776   }
5777
5778   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5779   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5780   // words from all 4 input quadwords.
5781   SDValue NewV;
5782   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5783     int MaskV[] = {
5784       BestLoQuad < 0 ? 0 : BestLoQuad,
5785       BestHiQuad < 0 ? 1 : BestHiQuad
5786     };
5787     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5788                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5789                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5790     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5791
5792     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5793     // source words for the shuffle, to aid later transformations.
5794     bool AllWordsInNewV = true;
5795     bool InOrder[2] = { true, true };
5796     for (unsigned i = 0; i != 8; ++i) {
5797       int idx = MaskVals[i];
5798       if (idx != (int)i)
5799         InOrder[i/4] = false;
5800       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5801         continue;
5802       AllWordsInNewV = false;
5803       break;
5804     }
5805
5806     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5807     if (AllWordsInNewV) {
5808       for (int i = 0; i != 8; ++i) {
5809         int idx = MaskVals[i];
5810         if (idx < 0)
5811           continue;
5812         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5813         if ((idx != i) && idx < 4)
5814           pshufhw = false;
5815         if ((idx != i) && idx > 3)
5816           pshuflw = false;
5817       }
5818       V1 = NewV;
5819       V2Used = false;
5820       BestLoQuad = 0;
5821       BestHiQuad = 1;
5822     }
5823
5824     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5825     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5826     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5827       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5828       unsigned TargetMask = 0;
5829       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5830                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5831       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5832       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5833                              getShufflePSHUFLWImmediate(SVOp);
5834       V1 = NewV.getOperand(0);
5835       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5836     }
5837   }
5838
5839   // If we have SSSE3, and all words of the result are from 1 input vector,
5840   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5841   // is present, fall back to case 4.
5842   if (Subtarget->hasSSSE3()) {
5843     SmallVector<SDValue,16> pshufbMask;
5844
5845     // If we have elements from both input vectors, set the high bit of the
5846     // shuffle mask element to zero out elements that come from V2 in the V1
5847     // mask, and elements that come from V1 in the V2 mask, so that the two
5848     // results can be OR'd together.
5849     bool TwoInputs = V1Used && V2Used;
5850     for (unsigned i = 0; i != 8; ++i) {
5851       int EltIdx = MaskVals[i] * 2;
5852       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5853       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5854       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5855       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5856     }
5857     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5858     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5859                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5860                                  MVT::v16i8, &pshufbMask[0], 16));
5861     if (!TwoInputs)
5862       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5863
5864     // Calculate the shuffle mask for the second input, shuffle it, and
5865     // OR it with the first shuffled input.
5866     pshufbMask.clear();
5867     for (unsigned i = 0; i != 8; ++i) {
5868       int EltIdx = MaskVals[i] * 2;
5869       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5870       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5871       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5872       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5873     }
5874     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5875     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5876                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5877                                  MVT::v16i8, &pshufbMask[0], 16));
5878     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5879     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5880   }
5881
5882   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5883   // and update MaskVals with new element order.
5884   std::bitset<8> InOrder;
5885   if (BestLoQuad >= 0) {
5886     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5887     for (int i = 0; i != 4; ++i) {
5888       int idx = MaskVals[i];
5889       if (idx < 0) {
5890         InOrder.set(i);
5891       } else if ((idx / 4) == BestLoQuad) {
5892         MaskV[i] = idx & 3;
5893         InOrder.set(i);
5894       }
5895     }
5896     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5897                                 &MaskV[0]);
5898
5899     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5900       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5901       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5902                                   NewV.getOperand(0),
5903                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5904     }
5905   }
5906
5907   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5908   // and update MaskVals with the new element order.
5909   if (BestHiQuad >= 0) {
5910     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5911     for (unsigned i = 4; i != 8; ++i) {
5912       int idx = MaskVals[i];
5913       if (idx < 0) {
5914         InOrder.set(i);
5915       } else if ((idx / 4) == BestHiQuad) {
5916         MaskV[i] = (idx & 3) + 4;
5917         InOrder.set(i);
5918       }
5919     }
5920     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5921                                 &MaskV[0]);
5922
5923     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5924       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5925       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5926                                   NewV.getOperand(0),
5927                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5928     }
5929   }
5930
5931   // In case BestHi & BestLo were both -1, which means each quadword has a word
5932   // from each of the four input quadwords, calculate the InOrder bitvector now
5933   // before falling through to the insert/extract cleanup.
5934   if (BestLoQuad == -1 && BestHiQuad == -1) {
5935     NewV = V1;
5936     for (int i = 0; i != 8; ++i)
5937       if (MaskVals[i] < 0 || MaskVals[i] == i)
5938         InOrder.set(i);
5939   }
5940
5941   // The other elements are put in the right place using pextrw and pinsrw.
5942   for (unsigned i = 0; i != 8; ++i) {
5943     if (InOrder[i])
5944       continue;
5945     int EltIdx = MaskVals[i];
5946     if (EltIdx < 0)
5947       continue;
5948     SDValue ExtOp = (EltIdx < 8) ?
5949       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5950                   DAG.getIntPtrConstant(EltIdx)) :
5951       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5952                   DAG.getIntPtrConstant(EltIdx - 8));
5953     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5954                        DAG.getIntPtrConstant(i));
5955   }
5956   return NewV;
5957 }
5958
5959 // v16i8 shuffles - Prefer shuffles in the following order:
5960 // 1. [ssse3] 1 x pshufb
5961 // 2. [ssse3] 2 x pshufb + 1 x por
5962 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5963 static
5964 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5965                                  SelectionDAG &DAG,
5966                                  const X86TargetLowering &TLI) {
5967   SDValue V1 = SVOp->getOperand(0);
5968   SDValue V2 = SVOp->getOperand(1);
5969   DebugLoc dl = SVOp->getDebugLoc();
5970   ArrayRef<int> MaskVals = SVOp->getMask();
5971
5972   // If we have SSSE3, case 1 is generated when all result bytes come from
5973   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5974   // present, fall back to case 3.
5975
5976   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5977   if (TLI.getSubtarget()->hasSSSE3()) {
5978     SmallVector<SDValue,16> pshufbMask;
5979
5980     // If all result elements are from one input vector, then only translate
5981     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5982     //
5983     // Otherwise, we have elements from both input vectors, and must zero out
5984     // elements that come from V2 in the first mask, and V1 in the second mask
5985     // so that we can OR them together.
5986     for (unsigned i = 0; i != 16; ++i) {
5987       int EltIdx = MaskVals[i];
5988       if (EltIdx < 0 || EltIdx >= 16)
5989         EltIdx = 0x80;
5990       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5991     }
5992     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5993                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5994                                  MVT::v16i8, &pshufbMask[0], 16));
5995
5996     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5997     // the 2nd operand if it's undefined or zero.
5998     if (V2.getOpcode() == ISD::UNDEF ||
5999         ISD::isBuildVectorAllZeros(V2.getNode()))
6000       return V1;
6001
6002     // Calculate the shuffle mask for the second input, shuffle it, and
6003     // OR it with the first shuffled input.
6004     pshufbMask.clear();
6005     for (unsigned i = 0; i != 16; ++i) {
6006       int EltIdx = MaskVals[i];
6007       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6008       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6009     }
6010     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6011                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6012                                  MVT::v16i8, &pshufbMask[0], 16));
6013     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6014   }
6015
6016   // No SSSE3 - Calculate in place words and then fix all out of place words
6017   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6018   // the 16 different words that comprise the two doublequadword input vectors.
6019   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6020   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6021   SDValue NewV = V1;
6022   for (int i = 0; i != 8; ++i) {
6023     int Elt0 = MaskVals[i*2];
6024     int Elt1 = MaskVals[i*2+1];
6025
6026     // This word of the result is all undef, skip it.
6027     if (Elt0 < 0 && Elt1 < 0)
6028       continue;
6029
6030     // This word of the result is already in the correct place, skip it.
6031     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6032       continue;
6033
6034     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6035     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6036     SDValue InsElt;
6037
6038     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6039     // using a single extract together, load it and store it.
6040     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6041       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6042                            DAG.getIntPtrConstant(Elt1 / 2));
6043       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6044                         DAG.getIntPtrConstant(i));
6045       continue;
6046     }
6047
6048     // If Elt1 is defined, extract it from the appropriate source.  If the
6049     // source byte is not also odd, shift the extracted word left 8 bits
6050     // otherwise clear the bottom 8 bits if we need to do an or.
6051     if (Elt1 >= 0) {
6052       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6053                            DAG.getIntPtrConstant(Elt1 / 2));
6054       if ((Elt1 & 1) == 0)
6055         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6056                              DAG.getConstant(8,
6057                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6058       else if (Elt0 >= 0)
6059         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6060                              DAG.getConstant(0xFF00, MVT::i16));
6061     }
6062     // If Elt0 is defined, extract it from the appropriate source.  If the
6063     // source byte is not also even, shift the extracted word right 8 bits. If
6064     // Elt1 was also defined, OR the extracted values together before
6065     // inserting them in the result.
6066     if (Elt0 >= 0) {
6067       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6068                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6069       if ((Elt0 & 1) != 0)
6070         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6071                               DAG.getConstant(8,
6072                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6073       else if (Elt1 >= 0)
6074         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6075                              DAG.getConstant(0x00FF, MVT::i16));
6076       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6077                          : InsElt0;
6078     }
6079     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6080                        DAG.getIntPtrConstant(i));
6081   }
6082   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6083 }
6084
6085 // v32i8 shuffles - Translate to VPSHUFB if possible.
6086 static
6087 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6088                                  const X86Subtarget *Subtarget,
6089                                  SelectionDAG &DAG) {
6090   MVT VT = SVOp->getValueType(0).getSimpleVT();
6091   SDValue V1 = SVOp->getOperand(0);
6092   SDValue V2 = SVOp->getOperand(1);
6093   DebugLoc dl = SVOp->getDebugLoc();
6094   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6095
6096   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6097   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6098   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6099
6100   // VPSHUFB may be generated if
6101   // (1) one of input vector is undefined or zeroinitializer.
6102   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6103   // And (2) the mask indexes don't cross the 128-bit lane.
6104   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6105       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6106     return SDValue();
6107
6108   if (V1IsAllZero && !V2IsAllZero) {
6109     CommuteVectorShuffleMask(MaskVals, 32);
6110     V1 = V2;
6111   }
6112   SmallVector<SDValue, 32> pshufbMask;
6113   for (unsigned i = 0; i != 32; i++) {
6114     int EltIdx = MaskVals[i];
6115     if (EltIdx < 0 || EltIdx >= 32)
6116       EltIdx = 0x80;
6117     else {
6118       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6119         // Cross lane is not allowed.
6120         return SDValue();
6121       EltIdx &= 0xf;
6122     }
6123     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6124   }
6125   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6126                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6127                                   MVT::v32i8, &pshufbMask[0], 32));
6128 }
6129
6130 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6131 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6132 /// done when every pair / quad of shuffle mask elements point to elements in
6133 /// the right sequence. e.g.
6134 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6135 static
6136 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6137                                  SelectionDAG &DAG) {
6138   MVT VT = SVOp->getValueType(0).getSimpleVT();
6139   DebugLoc dl = SVOp->getDebugLoc();
6140   unsigned NumElems = VT.getVectorNumElements();
6141   MVT NewVT;
6142   unsigned Scale;
6143   switch (VT.SimpleTy) {
6144   default: llvm_unreachable("Unexpected!");
6145   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6146   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6147   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6148   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6149   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6150   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6151   }
6152
6153   SmallVector<int, 8> MaskVec;
6154   for (unsigned i = 0; i != NumElems; i += Scale) {
6155     int StartIdx = -1;
6156     for (unsigned j = 0; j != Scale; ++j) {
6157       int EltIdx = SVOp->getMaskElt(i+j);
6158       if (EltIdx < 0)
6159         continue;
6160       if (StartIdx < 0)
6161         StartIdx = (EltIdx / Scale);
6162       if (EltIdx != (int)(StartIdx*Scale + j))
6163         return SDValue();
6164     }
6165     MaskVec.push_back(StartIdx);
6166   }
6167
6168   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6169   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6170   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6171 }
6172
6173 /// getVZextMovL - Return a zero-extending vector move low node.
6174 ///
6175 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6176                             SDValue SrcOp, SelectionDAG &DAG,
6177                             const X86Subtarget *Subtarget, DebugLoc dl) {
6178   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6179     LoadSDNode *LD = NULL;
6180     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6181       LD = dyn_cast<LoadSDNode>(SrcOp);
6182     if (!LD) {
6183       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6184       // instead.
6185       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6186       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6187           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6188           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6189           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6190         // PR2108
6191         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6192         return DAG.getNode(ISD::BITCAST, dl, VT,
6193                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6194                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6195                                                    OpVT,
6196                                                    SrcOp.getOperand(0)
6197                                                           .getOperand(0))));
6198       }
6199     }
6200   }
6201
6202   return DAG.getNode(ISD::BITCAST, dl, VT,
6203                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6204                                  DAG.getNode(ISD::BITCAST, dl,
6205                                              OpVT, SrcOp)));
6206 }
6207
6208 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6209 /// which could not be matched by any known target speficic shuffle
6210 static SDValue
6211 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6212
6213   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6214   if (NewOp.getNode())
6215     return NewOp;
6216
6217   MVT VT = SVOp->getValueType(0).getSimpleVT();
6218
6219   unsigned NumElems = VT.getVectorNumElements();
6220   unsigned NumLaneElems = NumElems / 2;
6221
6222   DebugLoc dl = SVOp->getDebugLoc();
6223   MVT EltVT = VT.getVectorElementType();
6224   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6225   SDValue Output[2];
6226
6227   SmallVector<int, 16> Mask;
6228   for (unsigned l = 0; l < 2; ++l) {
6229     // Build a shuffle mask for the output, discovering on the fly which
6230     // input vectors to use as shuffle operands (recorded in InputUsed).
6231     // If building a suitable shuffle vector proves too hard, then bail
6232     // out with UseBuildVector set.
6233     bool UseBuildVector = false;
6234     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6235     unsigned LaneStart = l * NumLaneElems;
6236     for (unsigned i = 0; i != NumLaneElems; ++i) {
6237       // The mask element.  This indexes into the input.
6238       int Idx = SVOp->getMaskElt(i+LaneStart);
6239       if (Idx < 0) {
6240         // the mask element does not index into any input vector.
6241         Mask.push_back(-1);
6242         continue;
6243       }
6244
6245       // The input vector this mask element indexes into.
6246       int Input = Idx / NumLaneElems;
6247
6248       // Turn the index into an offset from the start of the input vector.
6249       Idx -= Input * NumLaneElems;
6250
6251       // Find or create a shuffle vector operand to hold this input.
6252       unsigned OpNo;
6253       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6254         if (InputUsed[OpNo] == Input)
6255           // This input vector is already an operand.
6256           break;
6257         if (InputUsed[OpNo] < 0) {
6258           // Create a new operand for this input vector.
6259           InputUsed[OpNo] = Input;
6260           break;
6261         }
6262       }
6263
6264       if (OpNo >= array_lengthof(InputUsed)) {
6265         // More than two input vectors used!  Give up on trying to create a
6266         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6267         UseBuildVector = true;
6268         break;
6269       }
6270
6271       // Add the mask index for the new shuffle vector.
6272       Mask.push_back(Idx + OpNo * NumLaneElems);
6273     }
6274
6275     if (UseBuildVector) {
6276       SmallVector<SDValue, 16> SVOps;
6277       for (unsigned i = 0; i != NumLaneElems; ++i) {
6278         // The mask element.  This indexes into the input.
6279         int Idx = SVOp->getMaskElt(i+LaneStart);
6280         if (Idx < 0) {
6281           SVOps.push_back(DAG.getUNDEF(EltVT));
6282           continue;
6283         }
6284
6285         // The input vector this mask element indexes into.
6286         int Input = Idx / NumElems;
6287
6288         // Turn the index into an offset from the start of the input vector.
6289         Idx -= Input * NumElems;
6290
6291         // Extract the vector element by hand.
6292         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6293                                     SVOp->getOperand(Input),
6294                                     DAG.getIntPtrConstant(Idx)));
6295       }
6296
6297       // Construct the output using a BUILD_VECTOR.
6298       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6299                               SVOps.size());
6300     } else if (InputUsed[0] < 0) {
6301       // No input vectors were used! The result is undefined.
6302       Output[l] = DAG.getUNDEF(NVT);
6303     } else {
6304       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6305                                         (InputUsed[0] % 2) * NumLaneElems,
6306                                         DAG, dl);
6307       // If only one input was used, use an undefined vector for the other.
6308       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6309         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6310                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6311       // At least one input vector was used. Create a new shuffle vector.
6312       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6313     }
6314
6315     Mask.clear();
6316   }
6317
6318   // Concatenate the result back
6319   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6320 }
6321
6322 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6323 /// 4 elements, and match them with several different shuffle types.
6324 static SDValue
6325 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6326   SDValue V1 = SVOp->getOperand(0);
6327   SDValue V2 = SVOp->getOperand(1);
6328   DebugLoc dl = SVOp->getDebugLoc();
6329   MVT VT = SVOp->getValueType(0).getSimpleVT();
6330
6331   assert(VT.is128BitVector() && "Unsupported vector size");
6332
6333   std::pair<int, int> Locs[4];
6334   int Mask1[] = { -1, -1, -1, -1 };
6335   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6336
6337   unsigned NumHi = 0;
6338   unsigned NumLo = 0;
6339   for (unsigned i = 0; i != 4; ++i) {
6340     int Idx = PermMask[i];
6341     if (Idx < 0) {
6342       Locs[i] = std::make_pair(-1, -1);
6343     } else {
6344       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6345       if (Idx < 4) {
6346         Locs[i] = std::make_pair(0, NumLo);
6347         Mask1[NumLo] = Idx;
6348         NumLo++;
6349       } else {
6350         Locs[i] = std::make_pair(1, NumHi);
6351         if (2+NumHi < 4)
6352           Mask1[2+NumHi] = Idx;
6353         NumHi++;
6354       }
6355     }
6356   }
6357
6358   if (NumLo <= 2 && NumHi <= 2) {
6359     // If no more than two elements come from either vector. This can be
6360     // implemented with two shuffles. First shuffle gather the elements.
6361     // The second shuffle, which takes the first shuffle as both of its
6362     // vector operands, put the elements into the right order.
6363     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6364
6365     int Mask2[] = { -1, -1, -1, -1 };
6366
6367     for (unsigned i = 0; i != 4; ++i)
6368       if (Locs[i].first != -1) {
6369         unsigned Idx = (i < 2) ? 0 : 4;
6370         Idx += Locs[i].first * 2 + Locs[i].second;
6371         Mask2[i] = Idx;
6372       }
6373
6374     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6375   }
6376
6377   if (NumLo == 3 || NumHi == 3) {
6378     // Otherwise, we must have three elements from one vector, call it X, and
6379     // one element from the other, call it Y.  First, use a shufps to build an
6380     // intermediate vector with the one element from Y and the element from X
6381     // that will be in the same half in the final destination (the indexes don't
6382     // matter). Then, use a shufps to build the final vector, taking the half
6383     // containing the element from Y from the intermediate, and the other half
6384     // from X.
6385     if (NumHi == 3) {
6386       // Normalize it so the 3 elements come from V1.
6387       CommuteVectorShuffleMask(PermMask, 4);
6388       std::swap(V1, V2);
6389     }
6390
6391     // Find the element from V2.
6392     unsigned HiIndex;
6393     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6394       int Val = PermMask[HiIndex];
6395       if (Val < 0)
6396         continue;
6397       if (Val >= 4)
6398         break;
6399     }
6400
6401     Mask1[0] = PermMask[HiIndex];
6402     Mask1[1] = -1;
6403     Mask1[2] = PermMask[HiIndex^1];
6404     Mask1[3] = -1;
6405     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6406
6407     if (HiIndex >= 2) {
6408       Mask1[0] = PermMask[0];
6409       Mask1[1] = PermMask[1];
6410       Mask1[2] = HiIndex & 1 ? 6 : 4;
6411       Mask1[3] = HiIndex & 1 ? 4 : 6;
6412       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6413     }
6414
6415     Mask1[0] = HiIndex & 1 ? 2 : 0;
6416     Mask1[1] = HiIndex & 1 ? 0 : 2;
6417     Mask1[2] = PermMask[2];
6418     Mask1[3] = PermMask[3];
6419     if (Mask1[2] >= 0)
6420       Mask1[2] += 4;
6421     if (Mask1[3] >= 0)
6422       Mask1[3] += 4;
6423     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6424   }
6425
6426   // Break it into (shuffle shuffle_hi, shuffle_lo).
6427   int LoMask[] = { -1, -1, -1, -1 };
6428   int HiMask[] = { -1, -1, -1, -1 };
6429
6430   int *MaskPtr = LoMask;
6431   unsigned MaskIdx = 0;
6432   unsigned LoIdx = 0;
6433   unsigned HiIdx = 2;
6434   for (unsigned i = 0; i != 4; ++i) {
6435     if (i == 2) {
6436       MaskPtr = HiMask;
6437       MaskIdx = 1;
6438       LoIdx = 0;
6439       HiIdx = 2;
6440     }
6441     int Idx = PermMask[i];
6442     if (Idx < 0) {
6443       Locs[i] = std::make_pair(-1, -1);
6444     } else if (Idx < 4) {
6445       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6446       MaskPtr[LoIdx] = Idx;
6447       LoIdx++;
6448     } else {
6449       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6450       MaskPtr[HiIdx] = Idx;
6451       HiIdx++;
6452     }
6453   }
6454
6455   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6456   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6457   int MaskOps[] = { -1, -1, -1, -1 };
6458   for (unsigned i = 0; i != 4; ++i)
6459     if (Locs[i].first != -1)
6460       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6461   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6462 }
6463
6464 static bool MayFoldVectorLoad(SDValue V) {
6465   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6466     V = V.getOperand(0);
6467
6468   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6469     V = V.getOperand(0);
6470   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6471       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6472     // BUILD_VECTOR (load), undef
6473     V = V.getOperand(0);
6474
6475   return MayFoldLoad(V);
6476 }
6477
6478 static
6479 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6480   EVT VT = Op.getValueType();
6481
6482   // Canonizalize to v2f64.
6483   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6484   return DAG.getNode(ISD::BITCAST, dl, VT,
6485                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6486                                           V1, DAG));
6487 }
6488
6489 static
6490 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6491                         bool HasSSE2) {
6492   SDValue V1 = Op.getOperand(0);
6493   SDValue V2 = Op.getOperand(1);
6494   EVT VT = Op.getValueType();
6495
6496   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6497
6498   if (HasSSE2 && VT == MVT::v2f64)
6499     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6500
6501   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6502   return DAG.getNode(ISD::BITCAST, dl, VT,
6503                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6504                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6505                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6506 }
6507
6508 static
6509 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6510   SDValue V1 = Op.getOperand(0);
6511   SDValue V2 = Op.getOperand(1);
6512   EVT VT = Op.getValueType();
6513
6514   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6515          "unsupported shuffle type");
6516
6517   if (V2.getOpcode() == ISD::UNDEF)
6518     V2 = V1;
6519
6520   // v4i32 or v4f32
6521   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6522 }
6523
6524 static
6525 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6526   SDValue V1 = Op.getOperand(0);
6527   SDValue V2 = Op.getOperand(1);
6528   EVT VT = Op.getValueType();
6529   unsigned NumElems = VT.getVectorNumElements();
6530
6531   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6532   // operand of these instructions is only memory, so check if there's a
6533   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6534   // same masks.
6535   bool CanFoldLoad = false;
6536
6537   // Trivial case, when V2 comes from a load.
6538   if (MayFoldVectorLoad(V2))
6539     CanFoldLoad = true;
6540
6541   // When V1 is a load, it can be folded later into a store in isel, example:
6542   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6543   //    turns into:
6544   //  (MOVLPSmr addr:$src1, VR128:$src2)
6545   // So, recognize this potential and also use MOVLPS or MOVLPD
6546   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6547     CanFoldLoad = true;
6548
6549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6550   if (CanFoldLoad) {
6551     if (HasSSE2 && NumElems == 2)
6552       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6553
6554     if (NumElems == 4)
6555       // If we don't care about the second element, proceed to use movss.
6556       if (SVOp->getMaskElt(1) != -1)
6557         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6558   }
6559
6560   // movl and movlp will both match v2i64, but v2i64 is never matched by
6561   // movl earlier because we make it strict to avoid messing with the movlp load
6562   // folding logic (see the code above getMOVLP call). Match it here then,
6563   // this is horrible, but will stay like this until we move all shuffle
6564   // matching to x86 specific nodes. Note that for the 1st condition all
6565   // types are matched with movsd.
6566   if (HasSSE2) {
6567     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6568     // as to remove this logic from here, as much as possible
6569     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6570       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6571     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6572   }
6573
6574   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6575
6576   // Invert the operand order and use SHUFPS to match it.
6577   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6578                               getShuffleSHUFImmediate(SVOp), DAG);
6579 }
6580
6581 // Reduce a vector shuffle to zext.
6582 SDValue
6583 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6584   // PMOVZX is only available from SSE41.
6585   if (!Subtarget->hasSSE41())
6586     return SDValue();
6587
6588   EVT VT = Op.getValueType();
6589
6590   // Only AVX2 support 256-bit vector integer extending.
6591   if (!Subtarget->hasInt256() && VT.is256BitVector())
6592     return SDValue();
6593
6594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6595   DebugLoc DL = Op.getDebugLoc();
6596   SDValue V1 = Op.getOperand(0);
6597   SDValue V2 = Op.getOperand(1);
6598   unsigned NumElems = VT.getVectorNumElements();
6599
6600   // Extending is an unary operation and the element type of the source vector
6601   // won't be equal to or larger than i64.
6602   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6603       VT.getVectorElementType() == MVT::i64)
6604     return SDValue();
6605
6606   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6607   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6608   while ((1U << Shift) < NumElems) {
6609     if (SVOp->getMaskElt(1U << Shift) == 1)
6610       break;
6611     Shift += 1;
6612     // The maximal ratio is 8, i.e. from i8 to i64.
6613     if (Shift > 3)
6614       return SDValue();
6615   }
6616
6617   // Check the shuffle mask.
6618   unsigned Mask = (1U << Shift) - 1;
6619   for (unsigned i = 0; i != NumElems; ++i) {
6620     int EltIdx = SVOp->getMaskElt(i);
6621     if ((i & Mask) != 0 && EltIdx != -1)
6622       return SDValue();
6623     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6624       return SDValue();
6625   }
6626
6627   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6628   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6629   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6630
6631   if (!isTypeLegal(NVT))
6632     return SDValue();
6633
6634   // Simplify the operand as it's prepared to be fed into shuffle.
6635   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6636   if (V1.getOpcode() == ISD::BITCAST &&
6637       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6638       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6639       V1.getOperand(0)
6640         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6641     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6642     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6643     ConstantSDNode *CIdx =
6644       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6645     // If it's foldable, i.e. normal load with single use, we will let code
6646     // selection to fold it. Otherwise, we will short the conversion sequence.
6647     if (CIdx && CIdx->getZExtValue() == 0 &&
6648         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6649       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6650   }
6651
6652   return DAG.getNode(ISD::BITCAST, DL, VT,
6653                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6654 }
6655
6656 SDValue
6657 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6658   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6659   MVT VT = Op.getValueType().getSimpleVT();
6660   DebugLoc dl = Op.getDebugLoc();
6661   SDValue V1 = Op.getOperand(0);
6662   SDValue V2 = Op.getOperand(1);
6663
6664   if (isZeroShuffle(SVOp))
6665     return getZeroVector(VT, Subtarget, DAG, dl);
6666
6667   // Handle splat operations
6668   if (SVOp->isSplat()) {
6669     unsigned NumElem = VT.getVectorNumElements();
6670
6671     // Use vbroadcast whenever the splat comes from a foldable load
6672     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6673     if (Broadcast.getNode())
6674       return Broadcast;
6675
6676     // Handle splats by matching through known shuffle masks
6677     if ((VT.is128BitVector() && NumElem <= 4) ||
6678         (VT.is256BitVector() && NumElem <= 8))
6679       return SDValue();
6680
6681     // All remaning splats are promoted to target supported vector shuffles.
6682     return PromoteSplat(SVOp, DAG);
6683   }
6684
6685   // Check integer expanding shuffles.
6686   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6687   if (NewOp.getNode())
6688     return NewOp;
6689
6690   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6691   // do it!
6692   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6693       VT == MVT::v16i16 || VT == MVT::v32i8) {
6694     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6695     if (NewOp.getNode())
6696       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6697   } else if ((VT == MVT::v4i32 ||
6698              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6699     // FIXME: Figure out a cleaner way to do this.
6700     // Try to make use of movq to zero out the top part.
6701     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6703       if (NewOp.getNode()) {
6704         MVT NewVT = NewOp.getValueType().getSimpleVT();
6705         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6706                                NewVT, true, false))
6707           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6708                               DAG, Subtarget, dl);
6709       }
6710     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6711       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6712       if (NewOp.getNode()) {
6713         MVT NewVT = NewOp.getValueType().getSimpleVT();
6714         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6715           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6716                               DAG, Subtarget, dl);
6717       }
6718     }
6719   }
6720   return SDValue();
6721 }
6722
6723 SDValue
6724 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6725   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6726   SDValue V1 = Op.getOperand(0);
6727   SDValue V2 = Op.getOperand(1);
6728   MVT VT = Op.getValueType().getSimpleVT();
6729   DebugLoc dl = Op.getDebugLoc();
6730   unsigned NumElems = VT.getVectorNumElements();
6731   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6732   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6733   bool V1IsSplat = false;
6734   bool V2IsSplat = false;
6735   bool HasSSE2 = Subtarget->hasSSE2();
6736   bool HasFp256    = Subtarget->hasFp256();
6737   bool HasInt256   = Subtarget->hasInt256();
6738   MachineFunction &MF = DAG.getMachineFunction();
6739   bool OptForSize = MF.getFunction()->getAttributes().
6740     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6741
6742   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6743
6744   if (V1IsUndef && V2IsUndef)
6745     return DAG.getUNDEF(VT);
6746
6747   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6748
6749   // Vector shuffle lowering takes 3 steps:
6750   //
6751   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6752   //    narrowing and commutation of operands should be handled.
6753   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6754   //    shuffle nodes.
6755   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6756   //    so the shuffle can be broken into other shuffles and the legalizer can
6757   //    try the lowering again.
6758   //
6759   // The general idea is that no vector_shuffle operation should be left to
6760   // be matched during isel, all of them must be converted to a target specific
6761   // node here.
6762
6763   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6764   // narrowing and commutation of operands should be handled. The actual code
6765   // doesn't include all of those, work in progress...
6766   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6767   if (NewOp.getNode())
6768     return NewOp;
6769
6770   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6771
6772   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6773   // unpckh_undef). Only use pshufd if speed is more important than size.
6774   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6775     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6776   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6777     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6778
6779   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6780       V2IsUndef && MayFoldVectorLoad(V1))
6781     return getMOVDDup(Op, dl, V1, DAG);
6782
6783   if (isMOVHLPS_v_undef_Mask(M, VT))
6784     return getMOVHighToLow(Op, dl, DAG);
6785
6786   // Use to match splats
6787   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6788       (VT == MVT::v2f64 || VT == MVT::v2i64))
6789     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6790
6791   if (isPSHUFDMask(M, VT)) {
6792     // The actual implementation will match the mask in the if above and then
6793     // during isel it can match several different instructions, not only pshufd
6794     // as its name says, sad but true, emulate the behavior for now...
6795     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6796       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6797
6798     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6799
6800     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6801       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6802
6803     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6804       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6805                                   DAG);
6806
6807     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6808                                 TargetMask, DAG);
6809   }
6810
6811   // Check if this can be converted into a logical shift.
6812   bool isLeft = false;
6813   unsigned ShAmt = 0;
6814   SDValue ShVal;
6815   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6816   if (isShift && ShVal.hasOneUse()) {
6817     // If the shifted value has multiple uses, it may be cheaper to use
6818     // v_set0 + movlhps or movhlps, etc.
6819     MVT EltVT = VT.getVectorElementType();
6820     ShAmt *= EltVT.getSizeInBits();
6821     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6822   }
6823
6824   if (isMOVLMask(M, VT)) {
6825     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6826       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6827     if (!isMOVLPMask(M, VT)) {
6828       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6829         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6830
6831       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6832         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6833     }
6834   }
6835
6836   // FIXME: fold these into legal mask.
6837   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6838     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6839
6840   if (isMOVHLPSMask(M, VT))
6841     return getMOVHighToLow(Op, dl, DAG);
6842
6843   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6844     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6845
6846   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6847     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6848
6849   if (isMOVLPMask(M, VT))
6850     return getMOVLP(Op, dl, DAG, HasSSE2);
6851
6852   if (ShouldXformToMOVHLPS(M, VT) ||
6853       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6854     return CommuteVectorShuffle(SVOp, DAG);
6855
6856   if (isShift) {
6857     // No better options. Use a vshldq / vsrldq.
6858     MVT EltVT = VT.getVectorElementType();
6859     ShAmt *= EltVT.getSizeInBits();
6860     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6861   }
6862
6863   bool Commuted = false;
6864   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6865   // 1,1,1,1 -> v8i16 though.
6866   V1IsSplat = isSplatVector(V1.getNode());
6867   V2IsSplat = isSplatVector(V2.getNode());
6868
6869   // Canonicalize the splat or undef, if present, to be on the RHS.
6870   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6871     CommuteVectorShuffleMask(M, NumElems);
6872     std::swap(V1, V2);
6873     std::swap(V1IsSplat, V2IsSplat);
6874     Commuted = true;
6875   }
6876
6877   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6878     // Shuffling low element of v1 into undef, just return v1.
6879     if (V2IsUndef)
6880       return V1;
6881     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6882     // the instruction selector will not match, so get a canonical MOVL with
6883     // swapped operands to undo the commute.
6884     return getMOVL(DAG, dl, VT, V2, V1);
6885   }
6886
6887   if (isUNPCKLMask(M, VT, HasInt256))
6888     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6889
6890   if (isUNPCKHMask(M, VT, HasInt256))
6891     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6892
6893   if (V2IsSplat) {
6894     // Normalize mask so all entries that point to V2 points to its first
6895     // element then try to match unpck{h|l} again. If match, return a
6896     // new vector_shuffle with the corrected mask.p
6897     SmallVector<int, 8> NewMask(M.begin(), M.end());
6898     NormalizeMask(NewMask, NumElems);
6899     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6900       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6901     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6902       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6903   }
6904
6905   if (Commuted) {
6906     // Commute is back and try unpck* again.
6907     // FIXME: this seems wrong.
6908     CommuteVectorShuffleMask(M, NumElems);
6909     std::swap(V1, V2);
6910     std::swap(V1IsSplat, V2IsSplat);
6911     Commuted = false;
6912
6913     if (isUNPCKLMask(M, VT, HasInt256))
6914       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6915
6916     if (isUNPCKHMask(M, VT, HasInt256))
6917       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6918   }
6919
6920   // Normalize the node to match x86 shuffle ops if needed
6921   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6922     return CommuteVectorShuffle(SVOp, DAG);
6923
6924   // The checks below are all present in isShuffleMaskLegal, but they are
6925   // inlined here right now to enable us to directly emit target specific
6926   // nodes, and remove one by one until they don't return Op anymore.
6927
6928   if (isPALIGNRMask(M, VT, Subtarget))
6929     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6930                                 getShufflePALIGNRImmediate(SVOp),
6931                                 DAG);
6932
6933   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6934       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6935     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6936       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6937   }
6938
6939   if (isPSHUFHWMask(M, VT, HasInt256))
6940     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6941                                 getShufflePSHUFHWImmediate(SVOp),
6942                                 DAG);
6943
6944   if (isPSHUFLWMask(M, VT, HasInt256))
6945     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6946                                 getShufflePSHUFLWImmediate(SVOp),
6947                                 DAG);
6948
6949   if (isSHUFPMask(M, VT, HasFp256))
6950     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6951                                 getShuffleSHUFImmediate(SVOp), DAG);
6952
6953   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6954     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6955   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6956     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6957
6958   //===--------------------------------------------------------------------===//
6959   // Generate target specific nodes for 128 or 256-bit shuffles only
6960   // supported in the AVX instruction set.
6961   //
6962
6963   // Handle VMOVDDUPY permutations
6964   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6965     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6966
6967   // Handle VPERMILPS/D* permutations
6968   if (isVPERMILPMask(M, VT, HasFp256)) {
6969     if (HasInt256 && VT == MVT::v8i32)
6970       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6971                                   getShuffleSHUFImmediate(SVOp), DAG);
6972     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6973                                 getShuffleSHUFImmediate(SVOp), DAG);
6974   }
6975
6976   // Handle VPERM2F128/VPERM2I128 permutations
6977   if (isVPERM2X128Mask(M, VT, HasFp256))
6978     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6979                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6980
6981   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6982   if (BlendOp.getNode())
6983     return BlendOp;
6984
6985   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6986     SmallVector<SDValue, 8> permclMask;
6987     for (unsigned i = 0; i != 8; ++i) {
6988       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6989     }
6990     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6991                                &permclMask[0], 8);
6992     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6993     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6994                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6995   }
6996
6997   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6998     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6999                                 getShuffleCLImmediate(SVOp), DAG);
7000
7001   //===--------------------------------------------------------------------===//
7002   // Since no target specific shuffle was selected for this generic one,
7003   // lower it into other known shuffles. FIXME: this isn't true yet, but
7004   // this is the plan.
7005   //
7006
7007   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7008   if (VT == MVT::v8i16) {
7009     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7010     if (NewOp.getNode())
7011       return NewOp;
7012   }
7013
7014   if (VT == MVT::v16i8) {
7015     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7016     if (NewOp.getNode())
7017       return NewOp;
7018   }
7019
7020   if (VT == MVT::v32i8) {
7021     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7022     if (NewOp.getNode())
7023       return NewOp;
7024   }
7025
7026   // Handle all 128-bit wide vectors with 4 elements, and match them with
7027   // several different shuffle types.
7028   if (NumElems == 4 && VT.is128BitVector())
7029     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7030
7031   // Handle general 256-bit shuffles
7032   if (VT.is256BitVector())
7033     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7034
7035   return SDValue();
7036 }
7037
7038 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7039   MVT VT = Op.getValueType().getSimpleVT();
7040   DebugLoc dl = Op.getDebugLoc();
7041
7042   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7043     return SDValue();
7044
7045   if (VT.getSizeInBits() == 8) {
7046     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7047                                   Op.getOperand(0), Op.getOperand(1));
7048     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7049                                   DAG.getValueType(VT));
7050     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7051   }
7052
7053   if (VT.getSizeInBits() == 16) {
7054     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7056     if (Idx == 0)
7057       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7058                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7059                                      DAG.getNode(ISD::BITCAST, dl,
7060                                                  MVT::v4i32,
7061                                                  Op.getOperand(0)),
7062                                      Op.getOperand(1)));
7063     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7064                                   Op.getOperand(0), Op.getOperand(1));
7065     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7066                                   DAG.getValueType(VT));
7067     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7068   }
7069
7070   if (VT == MVT::f32) {
7071     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7072     // the result back to FR32 register. It's only worth matching if the
7073     // result has a single use which is a store or a bitcast to i32.  And in
7074     // the case of a store, it's not worth it if the index is a constant 0,
7075     // because a MOVSSmr can be used instead, which is smaller and faster.
7076     if (!Op.hasOneUse())
7077       return SDValue();
7078     SDNode *User = *Op.getNode()->use_begin();
7079     if ((User->getOpcode() != ISD::STORE ||
7080          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7081           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7082         (User->getOpcode() != ISD::BITCAST ||
7083          User->getValueType(0) != MVT::i32))
7084       return SDValue();
7085     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7086                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7087                                               Op.getOperand(0)),
7088                                               Op.getOperand(1));
7089     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7090   }
7091
7092   if (VT == MVT::i32 || VT == MVT::i64) {
7093     // ExtractPS/pextrq works with constant index.
7094     if (isa<ConstantSDNode>(Op.getOperand(1)))
7095       return Op;
7096   }
7097   return SDValue();
7098 }
7099
7100 SDValue
7101 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7102                                            SelectionDAG &DAG) const {
7103   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7104     return SDValue();
7105
7106   SDValue Vec = Op.getOperand(0);
7107   MVT VecVT = Vec.getValueType().getSimpleVT();
7108
7109   // If this is a 256-bit vector result, first extract the 128-bit vector and
7110   // then extract the element from the 128-bit vector.
7111   if (VecVT.is256BitVector()) {
7112     DebugLoc dl = Op.getNode()->getDebugLoc();
7113     unsigned NumElems = VecVT.getVectorNumElements();
7114     SDValue Idx = Op.getOperand(1);
7115     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7116
7117     // Get the 128-bit vector.
7118     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7119
7120     if (IdxVal >= NumElems/2)
7121       IdxVal -= NumElems/2;
7122     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7123                        DAG.getConstant(IdxVal, MVT::i32));
7124   }
7125
7126   assert(VecVT.is128BitVector() && "Unexpected vector length");
7127
7128   if (Subtarget->hasSSE41()) {
7129     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7130     if (Res.getNode())
7131       return Res;
7132   }
7133
7134   MVT VT = Op.getValueType().getSimpleVT();
7135   DebugLoc dl = Op.getDebugLoc();
7136   // TODO: handle v16i8.
7137   if (VT.getSizeInBits() == 16) {
7138     SDValue Vec = Op.getOperand(0);
7139     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7140     if (Idx == 0)
7141       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7142                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7143                                      DAG.getNode(ISD::BITCAST, dl,
7144                                                  MVT::v4i32, Vec),
7145                                      Op.getOperand(1)));
7146     // Transform it so it match pextrw which produces a 32-bit result.
7147     MVT EltVT = MVT::i32;
7148     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7149                                   Op.getOperand(0), Op.getOperand(1));
7150     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7151                                   DAG.getValueType(VT));
7152     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7153   }
7154
7155   if (VT.getSizeInBits() == 32) {
7156     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7157     if (Idx == 0)
7158       return Op;
7159
7160     // SHUFPS the element to the lowest double word, then movss.
7161     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7162     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7163     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7164                                        DAG.getUNDEF(VVT), Mask);
7165     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7166                        DAG.getIntPtrConstant(0));
7167   }
7168
7169   if (VT.getSizeInBits() == 64) {
7170     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7171     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7172     //        to match extract_elt for f64.
7173     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7174     if (Idx == 0)
7175       return Op;
7176
7177     // UNPCKHPD the element to the lowest double word, then movsd.
7178     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7179     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7180     int Mask[2] = { 1, -1 };
7181     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7182     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7183                                        DAG.getUNDEF(VVT), Mask);
7184     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7185                        DAG.getIntPtrConstant(0));
7186   }
7187
7188   return SDValue();
7189 }
7190
7191 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7192   MVT VT = Op.getValueType().getSimpleVT();
7193   MVT EltVT = VT.getVectorElementType();
7194   DebugLoc dl = Op.getDebugLoc();
7195
7196   SDValue N0 = Op.getOperand(0);
7197   SDValue N1 = Op.getOperand(1);
7198   SDValue N2 = Op.getOperand(2);
7199
7200   if (!VT.is128BitVector())
7201     return SDValue();
7202
7203   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7204       isa<ConstantSDNode>(N2)) {
7205     unsigned Opc;
7206     if (VT == MVT::v8i16)
7207       Opc = X86ISD::PINSRW;
7208     else if (VT == MVT::v16i8)
7209       Opc = X86ISD::PINSRB;
7210     else
7211       Opc = X86ISD::PINSRB;
7212
7213     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7214     // argument.
7215     if (N1.getValueType() != MVT::i32)
7216       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7217     if (N2.getValueType() != MVT::i32)
7218       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7219     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7220   }
7221
7222   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7223     // Bits [7:6] of the constant are the source select.  This will always be
7224     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7225     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7226     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7227     // Bits [5:4] of the constant are the destination select.  This is the
7228     //  value of the incoming immediate.
7229     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7230     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7231     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7232     // Create this as a scalar to vector..
7233     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7234     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7235   }
7236
7237   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7238     // PINSR* works with constant index.
7239     return Op;
7240   }
7241   return SDValue();
7242 }
7243
7244 SDValue
7245 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7246   MVT VT = Op.getValueType().getSimpleVT();
7247   MVT EltVT = VT.getVectorElementType();
7248
7249   DebugLoc dl = Op.getDebugLoc();
7250   SDValue N0 = Op.getOperand(0);
7251   SDValue N1 = Op.getOperand(1);
7252   SDValue N2 = Op.getOperand(2);
7253
7254   // If this is a 256-bit vector result, first extract the 128-bit vector,
7255   // insert the element into the extracted half and then place it back.
7256   if (VT.is256BitVector()) {
7257     if (!isa<ConstantSDNode>(N2))
7258       return SDValue();
7259
7260     // Get the desired 128-bit vector half.
7261     unsigned NumElems = VT.getVectorNumElements();
7262     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7263     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7264
7265     // Insert the element into the desired half.
7266     bool Upper = IdxVal >= NumElems/2;
7267     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7268                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7269
7270     // Insert the changed part back to the 256-bit vector
7271     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7272   }
7273
7274   if (Subtarget->hasSSE41())
7275     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7276
7277   if (EltVT == MVT::i8)
7278     return SDValue();
7279
7280   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7281     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7282     // as its second argument.
7283     if (N1.getValueType() != MVT::i32)
7284       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7285     if (N2.getValueType() != MVT::i32)
7286       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7287     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7288   }
7289   return SDValue();
7290 }
7291
7292 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7293   LLVMContext *Context = DAG.getContext();
7294   DebugLoc dl = Op.getDebugLoc();
7295   MVT OpVT = Op.getValueType().getSimpleVT();
7296
7297   // If this is a 256-bit vector result, first insert into a 128-bit
7298   // vector and then insert into the 256-bit vector.
7299   if (!OpVT.is128BitVector()) {
7300     // Insert into a 128-bit vector.
7301     EVT VT128 = EVT::getVectorVT(*Context,
7302                                  OpVT.getVectorElementType(),
7303                                  OpVT.getVectorNumElements() / 2);
7304
7305     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7306
7307     // Insert the 128-bit vector.
7308     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7309   }
7310
7311   if (OpVT == MVT::v1i64 &&
7312       Op.getOperand(0).getValueType() == MVT::i64)
7313     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7314
7315   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7316   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7317   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7318                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7319 }
7320
7321 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7322 // a simple subregister reference or explicit instructions to grab
7323 // upper bits of a vector.
7324 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7325                                       SelectionDAG &DAG) {
7326   if (Subtarget->hasFp256()) {
7327     DebugLoc dl = Op.getNode()->getDebugLoc();
7328     SDValue Vec = Op.getNode()->getOperand(0);
7329     SDValue Idx = Op.getNode()->getOperand(1);
7330
7331     if (Op.getNode()->getValueType(0).is128BitVector() &&
7332         Vec.getNode()->getValueType(0).is256BitVector() &&
7333         isa<ConstantSDNode>(Idx)) {
7334       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7335       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7336     }
7337   }
7338   return SDValue();
7339 }
7340
7341 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7342 // simple superregister reference or explicit instructions to insert
7343 // the upper bits of a vector.
7344 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7345                                      SelectionDAG &DAG) {
7346   if (Subtarget->hasFp256()) {
7347     DebugLoc dl = Op.getNode()->getDebugLoc();
7348     SDValue Vec = Op.getNode()->getOperand(0);
7349     SDValue SubVec = Op.getNode()->getOperand(1);
7350     SDValue Idx = Op.getNode()->getOperand(2);
7351
7352     if (Op.getNode()->getValueType(0).is256BitVector() &&
7353         SubVec.getNode()->getValueType(0).is128BitVector() &&
7354         isa<ConstantSDNode>(Idx)) {
7355       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7356       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7357     }
7358   }
7359   return SDValue();
7360 }
7361
7362 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7363 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7364 // one of the above mentioned nodes. It has to be wrapped because otherwise
7365 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7366 // be used to form addressing mode. These wrapped nodes will be selected
7367 // into MOV32ri.
7368 SDValue
7369 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7370   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7371
7372   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7373   // global base reg.
7374   unsigned char OpFlag = 0;
7375   unsigned WrapperKind = X86ISD::Wrapper;
7376   CodeModel::Model M = getTargetMachine().getCodeModel();
7377
7378   if (Subtarget->isPICStyleRIPRel() &&
7379       (M == CodeModel::Small || M == CodeModel::Kernel))
7380     WrapperKind = X86ISD::WrapperRIP;
7381   else if (Subtarget->isPICStyleGOT())
7382     OpFlag = X86II::MO_GOTOFF;
7383   else if (Subtarget->isPICStyleStubPIC())
7384     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7385
7386   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7387                                              CP->getAlignment(),
7388                                              CP->getOffset(), OpFlag);
7389   DebugLoc DL = CP->getDebugLoc();
7390   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7391   // With PIC, the address is actually $g + Offset.
7392   if (OpFlag) {
7393     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7394                          DAG.getNode(X86ISD::GlobalBaseReg,
7395                                      DebugLoc(), getPointerTy()),
7396                          Result);
7397   }
7398
7399   return Result;
7400 }
7401
7402 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7403   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7404
7405   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7406   // global base reg.
7407   unsigned char OpFlag = 0;
7408   unsigned WrapperKind = X86ISD::Wrapper;
7409   CodeModel::Model M = getTargetMachine().getCodeModel();
7410
7411   if (Subtarget->isPICStyleRIPRel() &&
7412       (M == CodeModel::Small || M == CodeModel::Kernel))
7413     WrapperKind = X86ISD::WrapperRIP;
7414   else if (Subtarget->isPICStyleGOT())
7415     OpFlag = X86II::MO_GOTOFF;
7416   else if (Subtarget->isPICStyleStubPIC())
7417     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7418
7419   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7420                                           OpFlag);
7421   DebugLoc DL = JT->getDebugLoc();
7422   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7423
7424   // With PIC, the address is actually $g + Offset.
7425   if (OpFlag)
7426     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7427                          DAG.getNode(X86ISD::GlobalBaseReg,
7428                                      DebugLoc(), getPointerTy()),
7429                          Result);
7430
7431   return Result;
7432 }
7433
7434 SDValue
7435 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7436   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7437
7438   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7439   // global base reg.
7440   unsigned char OpFlag = 0;
7441   unsigned WrapperKind = X86ISD::Wrapper;
7442   CodeModel::Model M = getTargetMachine().getCodeModel();
7443
7444   if (Subtarget->isPICStyleRIPRel() &&
7445       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7446     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7447       OpFlag = X86II::MO_GOTPCREL;
7448     WrapperKind = X86ISD::WrapperRIP;
7449   } else if (Subtarget->isPICStyleGOT()) {
7450     OpFlag = X86II::MO_GOT;
7451   } else if (Subtarget->isPICStyleStubPIC()) {
7452     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7453   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7454     OpFlag = X86II::MO_DARWIN_NONLAZY;
7455   }
7456
7457   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7458
7459   DebugLoc DL = Op.getDebugLoc();
7460   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7461
7462   // With PIC, the address is actually $g + Offset.
7463   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7464       !Subtarget->is64Bit()) {
7465     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7466                          DAG.getNode(X86ISD::GlobalBaseReg,
7467                                      DebugLoc(), getPointerTy()),
7468                          Result);
7469   }
7470
7471   // For symbols that require a load from a stub to get the address, emit the
7472   // load.
7473   if (isGlobalStubReference(OpFlag))
7474     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7475                          MachinePointerInfo::getGOT(), false, false, false, 0);
7476
7477   return Result;
7478 }
7479
7480 SDValue
7481 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7482   // Create the TargetBlockAddressAddress node.
7483   unsigned char OpFlags =
7484     Subtarget->ClassifyBlockAddressReference();
7485   CodeModel::Model M = getTargetMachine().getCodeModel();
7486   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7487   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7488   DebugLoc dl = Op.getDebugLoc();
7489   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7490                                              OpFlags);
7491
7492   if (Subtarget->isPICStyleRIPRel() &&
7493       (M == CodeModel::Small || M == CodeModel::Kernel))
7494     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7495   else
7496     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7497
7498   // With PIC, the address is actually $g + Offset.
7499   if (isGlobalRelativeToPICBase(OpFlags)) {
7500     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7501                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7502                          Result);
7503   }
7504
7505   return Result;
7506 }
7507
7508 SDValue
7509 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7510                                       int64_t Offset, SelectionDAG &DAG) const {
7511   // Create the TargetGlobalAddress node, folding in the constant
7512   // offset if it is legal.
7513   unsigned char OpFlags =
7514     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7515   CodeModel::Model M = getTargetMachine().getCodeModel();
7516   SDValue Result;
7517   if (OpFlags == X86II::MO_NO_FLAG &&
7518       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7519     // A direct static reference to a global.
7520     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7521     Offset = 0;
7522   } else {
7523     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7524   }
7525
7526   if (Subtarget->isPICStyleRIPRel() &&
7527       (M == CodeModel::Small || M == CodeModel::Kernel))
7528     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7529   else
7530     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7531
7532   // With PIC, the address is actually $g + Offset.
7533   if (isGlobalRelativeToPICBase(OpFlags)) {
7534     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7535                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7536                          Result);
7537   }
7538
7539   // For globals that require a load from a stub to get the address, emit the
7540   // load.
7541   if (isGlobalStubReference(OpFlags))
7542     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7543                          MachinePointerInfo::getGOT(), false, false, false, 0);
7544
7545   // If there was a non-zero offset that we didn't fold, create an explicit
7546   // addition for it.
7547   if (Offset != 0)
7548     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7549                          DAG.getConstant(Offset, getPointerTy()));
7550
7551   return Result;
7552 }
7553
7554 SDValue
7555 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7556   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7557   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7558   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7559 }
7560
7561 static SDValue
7562 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7563            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7564            unsigned char OperandFlags, bool LocalDynamic = false) {
7565   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7566   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7567   DebugLoc dl = GA->getDebugLoc();
7568   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7569                                            GA->getValueType(0),
7570                                            GA->getOffset(),
7571                                            OperandFlags);
7572
7573   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7574                                            : X86ISD::TLSADDR;
7575
7576   if (InFlag) {
7577     SDValue Ops[] = { Chain,  TGA, *InFlag };
7578     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7579   } else {
7580     SDValue Ops[]  = { Chain, TGA };
7581     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7582   }
7583
7584   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7585   MFI->setAdjustsStack(true);
7586
7587   SDValue Flag = Chain.getValue(1);
7588   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7589 }
7590
7591 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7592 static SDValue
7593 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7594                                 const EVT PtrVT) {
7595   SDValue InFlag;
7596   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7597   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7598                                    DAG.getNode(X86ISD::GlobalBaseReg,
7599                                                DebugLoc(), PtrVT), InFlag);
7600   InFlag = Chain.getValue(1);
7601
7602   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7603 }
7604
7605 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7606 static SDValue
7607 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7608                                 const EVT PtrVT) {
7609   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7610                     X86::RAX, X86II::MO_TLSGD);
7611 }
7612
7613 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7614                                            SelectionDAG &DAG,
7615                                            const EVT PtrVT,
7616                                            bool is64Bit) {
7617   DebugLoc dl = GA->getDebugLoc();
7618
7619   // Get the start address of the TLS block for this module.
7620   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7621       .getInfo<X86MachineFunctionInfo>();
7622   MFI->incNumLocalDynamicTLSAccesses();
7623
7624   SDValue Base;
7625   if (is64Bit) {
7626     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7627                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7628   } else {
7629     SDValue InFlag;
7630     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7631         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7632     InFlag = Chain.getValue(1);
7633     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7634                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7635   }
7636
7637   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7638   // of Base.
7639
7640   // Build x@dtpoff.
7641   unsigned char OperandFlags = X86II::MO_DTPOFF;
7642   unsigned WrapperKind = X86ISD::Wrapper;
7643   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7644                                            GA->getValueType(0),
7645                                            GA->getOffset(), OperandFlags);
7646   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7647
7648   // Add x@dtpoff with the base.
7649   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7650 }
7651
7652 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7653 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7654                                    const EVT PtrVT, TLSModel::Model model,
7655                                    bool is64Bit, bool isPIC) {
7656   DebugLoc dl = GA->getDebugLoc();
7657
7658   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7659   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7660                                                          is64Bit ? 257 : 256));
7661
7662   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7663                                       DAG.getIntPtrConstant(0),
7664                                       MachinePointerInfo(Ptr),
7665                                       false, false, false, 0);
7666
7667   unsigned char OperandFlags = 0;
7668   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7669   // initialexec.
7670   unsigned WrapperKind = X86ISD::Wrapper;
7671   if (model == TLSModel::LocalExec) {
7672     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7673   } else if (model == TLSModel::InitialExec) {
7674     if (is64Bit) {
7675       OperandFlags = X86II::MO_GOTTPOFF;
7676       WrapperKind = X86ISD::WrapperRIP;
7677     } else {
7678       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7679     }
7680   } else {
7681     llvm_unreachable("Unexpected model");
7682   }
7683
7684   // emit "addl x@ntpoff,%eax" (local exec)
7685   // or "addl x@indntpoff,%eax" (initial exec)
7686   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7687   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7688                                            GA->getValueType(0),
7689                                            GA->getOffset(), OperandFlags);
7690   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7691
7692   if (model == TLSModel::InitialExec) {
7693     if (isPIC && !is64Bit) {
7694       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7695                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7696                            Offset);
7697     }
7698
7699     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7700                          MachinePointerInfo::getGOT(), false, false, false,
7701                          0);
7702   }
7703
7704   // The address of the thread local variable is the add of the thread
7705   // pointer with the offset of the variable.
7706   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7707 }
7708
7709 SDValue
7710 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7711
7712   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7713   const GlobalValue *GV = GA->getGlobal();
7714
7715   if (Subtarget->isTargetELF()) {
7716     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7717
7718     switch (model) {
7719       case TLSModel::GeneralDynamic:
7720         if (Subtarget->is64Bit())
7721           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7722         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7723       case TLSModel::LocalDynamic:
7724         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7725                                            Subtarget->is64Bit());
7726       case TLSModel::InitialExec:
7727       case TLSModel::LocalExec:
7728         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7729                                    Subtarget->is64Bit(),
7730                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7731     }
7732     llvm_unreachable("Unknown TLS model.");
7733   }
7734
7735   if (Subtarget->isTargetDarwin()) {
7736     // Darwin only has one model of TLS.  Lower to that.
7737     unsigned char OpFlag = 0;
7738     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7739                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7740
7741     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7742     // global base reg.
7743     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7744                   !Subtarget->is64Bit();
7745     if (PIC32)
7746       OpFlag = X86II::MO_TLVP_PIC_BASE;
7747     else
7748       OpFlag = X86II::MO_TLVP;
7749     DebugLoc DL = Op.getDebugLoc();
7750     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7751                                                 GA->getValueType(0),
7752                                                 GA->getOffset(), OpFlag);
7753     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7754
7755     // With PIC32, the address is actually $g + Offset.
7756     if (PIC32)
7757       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7758                            DAG.getNode(X86ISD::GlobalBaseReg,
7759                                        DebugLoc(), getPointerTy()),
7760                            Offset);
7761
7762     // Lowering the machine isd will make sure everything is in the right
7763     // location.
7764     SDValue Chain = DAG.getEntryNode();
7765     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7766     SDValue Args[] = { Chain, Offset };
7767     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7768
7769     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7770     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7771     MFI->setAdjustsStack(true);
7772
7773     // And our return value (tls address) is in the standard call return value
7774     // location.
7775     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7776     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7777                               Chain.getValue(1));
7778   }
7779
7780   if (Subtarget->isTargetWindows()) {
7781     // Just use the implicit TLS architecture
7782     // Need to generate someting similar to:
7783     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7784     //                                  ; from TEB
7785     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7786     //   mov     rcx, qword [rdx+rcx*8]
7787     //   mov     eax, .tls$:tlsvar
7788     //   [rax+rcx] contains the address
7789     // Windows 64bit: gs:0x58
7790     // Windows 32bit: fs:__tls_array
7791
7792     // If GV is an alias then use the aliasee for determining
7793     // thread-localness.
7794     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7795       GV = GA->resolveAliasedGlobal(false);
7796     DebugLoc dl = GA->getDebugLoc();
7797     SDValue Chain = DAG.getEntryNode();
7798
7799     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7800     // %gs:0x58 (64-bit).
7801     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7802                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7803                                                              256)
7804                                         : Type::getInt32PtrTy(*DAG.getContext(),
7805                                                               257));
7806
7807     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7808                                         Subtarget->is64Bit()
7809                                         ? DAG.getIntPtrConstant(0x58)
7810                                         : DAG.getExternalSymbol("_tls_array",
7811                                                                 getPointerTy()),
7812                                         MachinePointerInfo(Ptr),
7813                                         false, false, false, 0);
7814
7815     // Load the _tls_index variable
7816     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7817     if (Subtarget->is64Bit())
7818       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7819                            IDX, MachinePointerInfo(), MVT::i32,
7820                            false, false, 0);
7821     else
7822       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7823                         false, false, false, 0);
7824
7825     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7826                                     getPointerTy());
7827     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7828
7829     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7830     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7831                       false, false, false, 0);
7832
7833     // Get the offset of start of .tls section
7834     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7835                                              GA->getValueType(0),
7836                                              GA->getOffset(), X86II::MO_SECREL);
7837     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7838
7839     // The address of the thread local variable is the add of the thread
7840     // pointer with the offset of the variable.
7841     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7842   }
7843
7844   llvm_unreachable("TLS not implemented for this target.");
7845 }
7846
7847 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7848 /// and take a 2 x i32 value to shift plus a shift amount.
7849 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7850   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7851   EVT VT = Op.getValueType();
7852   unsigned VTBits = VT.getSizeInBits();
7853   DebugLoc dl = Op.getDebugLoc();
7854   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7855   SDValue ShOpLo = Op.getOperand(0);
7856   SDValue ShOpHi = Op.getOperand(1);
7857   SDValue ShAmt  = Op.getOperand(2);
7858   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7859                                      DAG.getConstant(VTBits - 1, MVT::i8))
7860                        : DAG.getConstant(0, VT);
7861
7862   SDValue Tmp2, Tmp3;
7863   if (Op.getOpcode() == ISD::SHL_PARTS) {
7864     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7865     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7866   } else {
7867     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7868     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7869   }
7870
7871   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7872                                 DAG.getConstant(VTBits, MVT::i8));
7873   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7874                              AndNode, DAG.getConstant(0, MVT::i8));
7875
7876   SDValue Hi, Lo;
7877   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7878   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7879   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7880
7881   if (Op.getOpcode() == ISD::SHL_PARTS) {
7882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7883     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7884   } else {
7885     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7886     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7887   }
7888
7889   SDValue Ops[2] = { Lo, Hi };
7890   return DAG.getMergeValues(Ops, 2, dl);
7891 }
7892
7893 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7894                                            SelectionDAG &DAG) const {
7895   EVT SrcVT = Op.getOperand(0).getValueType();
7896
7897   if (SrcVT.isVector())
7898     return SDValue();
7899
7900   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7901          "Unknown SINT_TO_FP to lower!");
7902
7903   // These are really Legal; return the operand so the caller accepts it as
7904   // Legal.
7905   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7906     return Op;
7907   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7908       Subtarget->is64Bit()) {
7909     return Op;
7910   }
7911
7912   DebugLoc dl = Op.getDebugLoc();
7913   unsigned Size = SrcVT.getSizeInBits()/8;
7914   MachineFunction &MF = DAG.getMachineFunction();
7915   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7916   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7917   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7918                                StackSlot,
7919                                MachinePointerInfo::getFixedStack(SSFI),
7920                                false, false, 0);
7921   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7922 }
7923
7924 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7925                                      SDValue StackSlot,
7926                                      SelectionDAG &DAG) const {
7927   // Build the FILD
7928   DebugLoc DL = Op.getDebugLoc();
7929   SDVTList Tys;
7930   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7931   if (useSSE)
7932     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7933   else
7934     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7935
7936   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7937
7938   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7939   MachineMemOperand *MMO;
7940   if (FI) {
7941     int SSFI = FI->getIndex();
7942     MMO =
7943       DAG.getMachineFunction()
7944       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7945                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7946   } else {
7947     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7948     StackSlot = StackSlot.getOperand(1);
7949   }
7950   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7951   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7952                                            X86ISD::FILD, DL,
7953                                            Tys, Ops, array_lengthof(Ops),
7954                                            SrcVT, MMO);
7955
7956   if (useSSE) {
7957     Chain = Result.getValue(1);
7958     SDValue InFlag = Result.getValue(2);
7959
7960     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7961     // shouldn't be necessary except that RFP cannot be live across
7962     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7963     MachineFunction &MF = DAG.getMachineFunction();
7964     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7965     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7966     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7967     Tys = DAG.getVTList(MVT::Other);
7968     SDValue Ops[] = {
7969       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7970     };
7971     MachineMemOperand *MMO =
7972       DAG.getMachineFunction()
7973       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7974                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7975
7976     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7977                                     Ops, array_lengthof(Ops),
7978                                     Op.getValueType(), MMO);
7979     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7980                          MachinePointerInfo::getFixedStack(SSFI),
7981                          false, false, false, 0);
7982   }
7983
7984   return Result;
7985 }
7986
7987 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7988 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7989                                                SelectionDAG &DAG) const {
7990   // This algorithm is not obvious. Here it is what we're trying to output:
7991   /*
7992      movq       %rax,  %xmm0
7993      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7994      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7995      #ifdef __SSE3__
7996        haddpd   %xmm0, %xmm0
7997      #else
7998        pshufd   $0x4e, %xmm0, %xmm1
7999        addpd    %xmm1, %xmm0
8000      #endif
8001   */
8002
8003   DebugLoc dl = Op.getDebugLoc();
8004   LLVMContext *Context = DAG.getContext();
8005
8006   // Build some magic constants.
8007   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8008   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8009   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8010
8011   SmallVector<Constant*,2> CV1;
8012   CV1.push_back(
8013     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8014                                       APInt(64, 0x4330000000000000ULL))));
8015   CV1.push_back(
8016     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8017                                       APInt(64, 0x4530000000000000ULL))));
8018   Constant *C1 = ConstantVector::get(CV1);
8019   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8020
8021   // Load the 64-bit value into an XMM register.
8022   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8023                             Op.getOperand(0));
8024   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8025                               MachinePointerInfo::getConstantPool(),
8026                               false, false, false, 16);
8027   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8028                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8029                               CLod0);
8030
8031   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8032                               MachinePointerInfo::getConstantPool(),
8033                               false, false, false, 16);
8034   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8035   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8036   SDValue Result;
8037
8038   if (Subtarget->hasSSE3()) {
8039     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8040     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8041   } else {
8042     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8043     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8044                                            S2F, 0x4E, DAG);
8045     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8046                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8047                          Sub);
8048   }
8049
8050   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8051                      DAG.getIntPtrConstant(0));
8052 }
8053
8054 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8055 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8056                                                SelectionDAG &DAG) const {
8057   DebugLoc dl = Op.getDebugLoc();
8058   // FP constant to bias correct the final result.
8059   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8060                                    MVT::f64);
8061
8062   // Load the 32-bit value into an XMM register.
8063   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8064                              Op.getOperand(0));
8065
8066   // Zero out the upper parts of the register.
8067   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8068
8069   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8070                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8071                      DAG.getIntPtrConstant(0));
8072
8073   // Or the load with the bias.
8074   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8075                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8076                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8077                                                    MVT::v2f64, Load)),
8078                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8079                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8080                                                    MVT::v2f64, Bias)));
8081   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8082                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8083                    DAG.getIntPtrConstant(0));
8084
8085   // Subtract the bias.
8086   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8087
8088   // Handle final rounding.
8089   EVT DestVT = Op.getValueType();
8090
8091   if (DestVT.bitsLT(MVT::f64))
8092     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8093                        DAG.getIntPtrConstant(0));
8094   if (DestVT.bitsGT(MVT::f64))
8095     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8096
8097   // Handle final rounding.
8098   return Sub;
8099 }
8100
8101 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8102                                                SelectionDAG &DAG) const {
8103   SDValue N0 = Op.getOperand(0);
8104   EVT SVT = N0.getValueType();
8105   DebugLoc dl = Op.getDebugLoc();
8106
8107   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8108           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8109          "Custom UINT_TO_FP is not supported!");
8110
8111   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8112                              SVT.getVectorNumElements());
8113   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8114                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8115 }
8116
8117 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8118                                            SelectionDAG &DAG) const {
8119   SDValue N0 = Op.getOperand(0);
8120   DebugLoc dl = Op.getDebugLoc();
8121
8122   if (Op.getValueType().isVector())
8123     return lowerUINT_TO_FP_vec(Op, DAG);
8124
8125   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8126   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8127   // the optimization here.
8128   if (DAG.SignBitIsZero(N0))
8129     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8130
8131   EVT SrcVT = N0.getValueType();
8132   EVT DstVT = Op.getValueType();
8133   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8134     return LowerUINT_TO_FP_i64(Op, DAG);
8135   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8136     return LowerUINT_TO_FP_i32(Op, DAG);
8137   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8138     return SDValue();
8139
8140   // Make a 64-bit buffer, and use it to build an FILD.
8141   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8142   if (SrcVT == MVT::i32) {
8143     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8144     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8145                                      getPointerTy(), StackSlot, WordOff);
8146     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8147                                   StackSlot, MachinePointerInfo(),
8148                                   false, false, 0);
8149     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8150                                   OffsetSlot, MachinePointerInfo(),
8151                                   false, false, 0);
8152     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8153     return Fild;
8154   }
8155
8156   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8157   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8158                                StackSlot, MachinePointerInfo(),
8159                                false, false, 0);
8160   // For i64 source, we need to add the appropriate power of 2 if the input
8161   // was negative.  This is the same as the optimization in
8162   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8163   // we must be careful to do the computation in x87 extended precision, not
8164   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8165   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8166   MachineMemOperand *MMO =
8167     DAG.getMachineFunction()
8168     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8169                           MachineMemOperand::MOLoad, 8, 8);
8170
8171   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8172   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8173   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8174                                          MVT::i64, MMO);
8175
8176   APInt FF(32, 0x5F800000ULL);
8177
8178   // Check whether the sign bit is set.
8179   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8180                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8181                                  ISD::SETLT);
8182
8183   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8184   SDValue FudgePtr = DAG.getConstantPool(
8185                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8186                                          getPointerTy());
8187
8188   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8189   SDValue Zero = DAG.getIntPtrConstant(0);
8190   SDValue Four = DAG.getIntPtrConstant(4);
8191   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8192                                Zero, Four);
8193   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8194
8195   // Load the value out, extending it from f32 to f80.
8196   // FIXME: Avoid the extend by constructing the right constant pool?
8197   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8198                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8199                                  MVT::f32, false, false, 4);
8200   // Extend everything to 80 bits to force it to be done on x87.
8201   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8202   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8203 }
8204
8205 std::pair<SDValue,SDValue>
8206 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8207                                     bool IsSigned, bool IsReplace) const {
8208   DebugLoc DL = Op.getDebugLoc();
8209
8210   EVT DstTy = Op.getValueType();
8211
8212   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8213     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8214     DstTy = MVT::i64;
8215   }
8216
8217   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8218          DstTy.getSimpleVT() >= MVT::i16 &&
8219          "Unknown FP_TO_INT to lower!");
8220
8221   // These are really Legal.
8222   if (DstTy == MVT::i32 &&
8223       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8224     return std::make_pair(SDValue(), SDValue());
8225   if (Subtarget->is64Bit() &&
8226       DstTy == MVT::i64 &&
8227       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8228     return std::make_pair(SDValue(), SDValue());
8229
8230   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8231   // stack slot, or into the FTOL runtime function.
8232   MachineFunction &MF = DAG.getMachineFunction();
8233   unsigned MemSize = DstTy.getSizeInBits()/8;
8234   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8235   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8236
8237   unsigned Opc;
8238   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8239     Opc = X86ISD::WIN_FTOL;
8240   else
8241     switch (DstTy.getSimpleVT().SimpleTy) {
8242     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8243     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8244     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8245     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8246     }
8247
8248   SDValue Chain = DAG.getEntryNode();
8249   SDValue Value = Op.getOperand(0);
8250   EVT TheVT = Op.getOperand(0).getValueType();
8251   // FIXME This causes a redundant load/store if the SSE-class value is already
8252   // in memory, such as if it is on the callstack.
8253   if (isScalarFPTypeInSSEReg(TheVT)) {
8254     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8255     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8256                          MachinePointerInfo::getFixedStack(SSFI),
8257                          false, false, 0);
8258     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8259     SDValue Ops[] = {
8260       Chain, StackSlot, DAG.getValueType(TheVT)
8261     };
8262
8263     MachineMemOperand *MMO =
8264       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8265                               MachineMemOperand::MOLoad, MemSize, MemSize);
8266     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8267                                     DstTy, MMO);
8268     Chain = Value.getValue(1);
8269     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8270     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8271   }
8272
8273   MachineMemOperand *MMO =
8274     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8275                             MachineMemOperand::MOStore, MemSize, MemSize);
8276
8277   if (Opc != X86ISD::WIN_FTOL) {
8278     // Build the FP_TO_INT*_IN_MEM
8279     SDValue Ops[] = { Chain, Value, StackSlot };
8280     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8281                                            Ops, 3, DstTy, MMO);
8282     return std::make_pair(FIST, StackSlot);
8283   } else {
8284     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8285       DAG.getVTList(MVT::Other, MVT::Glue),
8286       Chain, Value);
8287     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8288       MVT::i32, ftol.getValue(1));
8289     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8290       MVT::i32, eax.getValue(2));
8291     SDValue Ops[] = { eax, edx };
8292     SDValue pair = IsReplace
8293       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8294       : DAG.getMergeValues(Ops, 2, DL);
8295     return std::make_pair(pair, SDValue());
8296   }
8297 }
8298
8299 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8300                               const X86Subtarget *Subtarget) {
8301   MVT VT = Op->getValueType(0).getSimpleVT();
8302   SDValue In = Op->getOperand(0);
8303   MVT InVT = In.getValueType().getSimpleVT();
8304   DebugLoc dl = Op->getDebugLoc();
8305
8306   // Optimize vectors in AVX mode:
8307   //
8308   //   v8i16 -> v8i32
8309   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8310   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8311   //   Concat upper and lower parts.
8312   //
8313   //   v4i32 -> v4i64
8314   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8315   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8316   //   Concat upper and lower parts.
8317   //
8318
8319   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8320       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8321     return SDValue();
8322
8323   if (Subtarget->hasInt256())
8324     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8325
8326   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8327   SDValue Undef = DAG.getUNDEF(InVT);
8328   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8329   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8330   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8331
8332   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8333                              VT.getVectorNumElements()/2);
8334
8335   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8336   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8337
8338   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8339 }
8340
8341 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8342                                            SelectionDAG &DAG) const {
8343   if (Subtarget->hasFp256()) {
8344     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8345     if (Res.getNode())
8346       return Res;
8347   }
8348
8349   return SDValue();
8350 }
8351 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8352                                             SelectionDAG &DAG) const {
8353   DebugLoc DL = Op.getDebugLoc();
8354   MVT VT = Op.getValueType().getSimpleVT();
8355   SDValue In = Op.getOperand(0);
8356   MVT SVT = In.getValueType().getSimpleVT();
8357
8358   if (Subtarget->hasFp256()) {
8359     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8360     if (Res.getNode())
8361       return Res;
8362   }
8363
8364   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8365       VT.getVectorNumElements() != SVT.getVectorNumElements())
8366     return SDValue();
8367
8368   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8369
8370   // AVX2 has better support of integer extending.
8371   if (Subtarget->hasInt256())
8372     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8373
8374   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8375   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8376   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8377                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8378                                                 DAG.getUNDEF(MVT::v8i16),
8379                                                 &Mask[0]));
8380
8381   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8382 }
8383
8384 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8385   DebugLoc DL = Op.getDebugLoc();
8386   MVT VT = Op.getValueType().getSimpleVT();
8387   SDValue In = Op.getOperand(0);
8388   MVT SVT = In.getValueType().getSimpleVT();
8389
8390   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8391     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8392     if (Subtarget->hasInt256()) {
8393       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8394       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8395       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8396                                 ShufMask);
8397       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8398                          DAG.getIntPtrConstant(0));
8399     }
8400
8401     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8402     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8403                                DAG.getIntPtrConstant(0));
8404     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8405                                DAG.getIntPtrConstant(2));
8406
8407     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8408     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8409
8410     // The PSHUFD mask:
8411     static const int ShufMask1[] = {0, 2, 0, 0};
8412     SDValue Undef = DAG.getUNDEF(VT);
8413     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8414     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8415
8416     // The MOVLHPS mask:
8417     static const int ShufMask2[] = {0, 1, 4, 5};
8418     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8419   }
8420
8421   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8422     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8423     if (Subtarget->hasInt256()) {
8424       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8425
8426       SmallVector<SDValue,32> pshufbMask;
8427       for (unsigned i = 0; i < 2; ++i) {
8428         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8429         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8430         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8431         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8432         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8433         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8434         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8435         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8436         for (unsigned j = 0; j < 8; ++j)
8437           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8438       }
8439       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8440                                &pshufbMask[0], 32);
8441       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8442       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8443
8444       static const int ShufMask[] = {0,  2,  -1,  -1};
8445       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8446                                 &ShufMask[0]);
8447       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8448                        DAG.getIntPtrConstant(0));
8449       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8450     }
8451
8452     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8453                                DAG.getIntPtrConstant(0));
8454
8455     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8456                                DAG.getIntPtrConstant(4));
8457
8458     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8459     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8460
8461     // The PSHUFB mask:
8462     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8463                                    -1, -1, -1, -1, -1, -1, -1, -1};
8464
8465     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8466     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8467     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8468
8469     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8470     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8471
8472     // The MOVLHPS Mask:
8473     static const int ShufMask2[] = {0, 1, 4, 5};
8474     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8475     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8476   }
8477
8478   // Handle truncation of V256 to V128 using shuffles.
8479   if (!VT.is128BitVector() || !SVT.is256BitVector())
8480     return SDValue();
8481
8482   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8483          "Invalid op");
8484   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8485
8486   unsigned NumElems = VT.getVectorNumElements();
8487   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8488                              NumElems * 2);
8489
8490   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8491   // Prepare truncation shuffle mask
8492   for (unsigned i = 0; i != NumElems; ++i)
8493     MaskVec[i] = i * 2;
8494   SDValue V = DAG.getVectorShuffle(NVT, DL,
8495                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8496                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8497   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8498                      DAG.getIntPtrConstant(0));
8499 }
8500
8501 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8502                                            SelectionDAG &DAG) const {
8503   MVT VT = Op.getValueType().getSimpleVT();
8504   if (VT.isVector()) {
8505     if (VT == MVT::v8i16)
8506       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8507                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8508                                      MVT::v8i32, Op.getOperand(0)));
8509     return SDValue();
8510   }
8511
8512   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8513     /*IsSigned=*/ true, /*IsReplace=*/ false);
8514   SDValue FIST = Vals.first, StackSlot = Vals.second;
8515   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8516   if (FIST.getNode() == 0) return Op;
8517
8518   if (StackSlot.getNode())
8519     // Load the result.
8520     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8521                        FIST, StackSlot, MachinePointerInfo(),
8522                        false, false, false, 0);
8523
8524   // The node is the result.
8525   return FIST;
8526 }
8527
8528 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8529                                            SelectionDAG &DAG) const {
8530   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8531     /*IsSigned=*/ false, /*IsReplace=*/ false);
8532   SDValue FIST = Vals.first, StackSlot = Vals.second;
8533   assert(FIST.getNode() && "Unexpected failure");
8534
8535   if (StackSlot.getNode())
8536     // Load the result.
8537     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8538                        FIST, StackSlot, MachinePointerInfo(),
8539                        false, false, false, 0);
8540
8541   // The node is the result.
8542   return FIST;
8543 }
8544
8545 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8546   DebugLoc DL = Op.getDebugLoc();
8547   MVT VT = Op.getValueType().getSimpleVT();
8548   SDValue In = Op.getOperand(0);
8549   MVT SVT = In.getValueType().getSimpleVT();
8550
8551   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8552
8553   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8554                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8555                                  In, DAG.getUNDEF(SVT)));
8556 }
8557
8558 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8559   LLVMContext *Context = DAG.getContext();
8560   DebugLoc dl = Op.getDebugLoc();
8561   MVT VT = Op.getValueType().getSimpleVT();
8562   MVT EltVT = VT;
8563   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8564   if (VT.isVector()) {
8565     EltVT = VT.getVectorElementType();
8566     NumElts = VT.getVectorNumElements();
8567   }
8568   Constant *C;
8569   if (EltVT == MVT::f64)
8570     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8571                                           APInt(64, ~(1ULL << 63))));
8572   else
8573     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8574                                           APInt(32, ~(1U << 31))));
8575   C = ConstantVector::getSplat(NumElts, C);
8576   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8577   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8578   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8579                              MachinePointerInfo::getConstantPool(),
8580                              false, false, false, Alignment);
8581   if (VT.isVector()) {
8582     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8583     return DAG.getNode(ISD::BITCAST, dl, VT,
8584                        DAG.getNode(ISD::AND, dl, ANDVT,
8585                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8586                                                Op.getOperand(0)),
8587                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8588   }
8589   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8590 }
8591
8592 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8593   LLVMContext *Context = DAG.getContext();
8594   DebugLoc dl = Op.getDebugLoc();
8595   MVT VT = Op.getValueType().getSimpleVT();
8596   MVT EltVT = VT;
8597   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8598   if (VT.isVector()) {
8599     EltVT = VT.getVectorElementType();
8600     NumElts = VT.getVectorNumElements();
8601   }
8602   Constant *C;
8603   if (EltVT == MVT::f64)
8604     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8605                                           APInt(64, 1ULL << 63)));
8606   else
8607     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8608                                           APInt(32, 1U << 31)));
8609   C = ConstantVector::getSplat(NumElts, C);
8610   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8611   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8612   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8613                              MachinePointerInfo::getConstantPool(),
8614                              false, false, false, Alignment);
8615   if (VT.isVector()) {
8616     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8617     return DAG.getNode(ISD::BITCAST, dl, VT,
8618                        DAG.getNode(ISD::XOR, dl, XORVT,
8619                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8620                                                Op.getOperand(0)),
8621                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8622   }
8623
8624   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8625 }
8626
8627 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8628   LLVMContext *Context = DAG.getContext();
8629   SDValue Op0 = Op.getOperand(0);
8630   SDValue Op1 = Op.getOperand(1);
8631   DebugLoc dl = Op.getDebugLoc();
8632   MVT VT = Op.getValueType().getSimpleVT();
8633   MVT SrcVT = Op1.getValueType().getSimpleVT();
8634
8635   // If second operand is smaller, extend it first.
8636   if (SrcVT.bitsLT(VT)) {
8637     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8638     SrcVT = VT;
8639   }
8640   // And if it is bigger, shrink it first.
8641   if (SrcVT.bitsGT(VT)) {
8642     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8643     SrcVT = VT;
8644   }
8645
8646   // At this point the operands and the result should have the same
8647   // type, and that won't be f80 since that is not custom lowered.
8648
8649   // First get the sign bit of second operand.
8650   SmallVector<Constant*,4> CV;
8651   if (SrcVT == MVT::f64) {
8652     const fltSemantics &Sem = APFloat::IEEEdouble;
8653     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8654     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8655   } else {
8656     const fltSemantics &Sem = APFloat::IEEEsingle;
8657     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8658     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8659     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8660     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8661   }
8662   Constant *C = ConstantVector::get(CV);
8663   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8664   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8665                               MachinePointerInfo::getConstantPool(),
8666                               false, false, false, 16);
8667   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8668
8669   // Shift sign bit right or left if the two operands have different types.
8670   if (SrcVT.bitsGT(VT)) {
8671     // Op0 is MVT::f32, Op1 is MVT::f64.
8672     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8673     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8674                           DAG.getConstant(32, MVT::i32));
8675     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8676     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8677                           DAG.getIntPtrConstant(0));
8678   }
8679
8680   // Clear first operand sign bit.
8681   CV.clear();
8682   if (VT == MVT::f64) {
8683     const fltSemantics &Sem = APFloat::IEEEdouble;
8684     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8685                                                    APInt(64, ~(1ULL << 63)))));
8686     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8687   } else {
8688     const fltSemantics &Sem = APFloat::IEEEsingle;
8689     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8690                                                    APInt(32, ~(1U << 31)))));
8691     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8692     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8693     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8694   }
8695   C = ConstantVector::get(CV);
8696   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8697   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8698                               MachinePointerInfo::getConstantPool(),
8699                               false, false, false, 16);
8700   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8701
8702   // Or the value with the sign bit.
8703   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8704 }
8705
8706 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8707   SDValue N0 = Op.getOperand(0);
8708   DebugLoc dl = Op.getDebugLoc();
8709   MVT VT = Op.getValueType().getSimpleVT();
8710
8711   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8712   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8713                                   DAG.getConstant(1, VT));
8714   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8715 }
8716
8717 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8718 //
8719 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8720                                                   SelectionDAG &DAG) const {
8721   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8722
8723   if (!Subtarget->hasSSE41())
8724     return SDValue();
8725
8726   if (!Op->hasOneUse())
8727     return SDValue();
8728
8729   SDNode *N = Op.getNode();
8730   DebugLoc DL = N->getDebugLoc();
8731
8732   SmallVector<SDValue, 8> Opnds;
8733   DenseMap<SDValue, unsigned> VecInMap;
8734   EVT VT = MVT::Other;
8735
8736   // Recognize a special case where a vector is casted into wide integer to
8737   // test all 0s.
8738   Opnds.push_back(N->getOperand(0));
8739   Opnds.push_back(N->getOperand(1));
8740
8741   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8742     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8743     // BFS traverse all OR'd operands.
8744     if (I->getOpcode() == ISD::OR) {
8745       Opnds.push_back(I->getOperand(0));
8746       Opnds.push_back(I->getOperand(1));
8747       // Re-evaluate the number of nodes to be traversed.
8748       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8749       continue;
8750     }
8751
8752     // Quit if a non-EXTRACT_VECTOR_ELT
8753     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8754       return SDValue();
8755
8756     // Quit if without a constant index.
8757     SDValue Idx = I->getOperand(1);
8758     if (!isa<ConstantSDNode>(Idx))
8759       return SDValue();
8760
8761     SDValue ExtractedFromVec = I->getOperand(0);
8762     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8763     if (M == VecInMap.end()) {
8764       VT = ExtractedFromVec.getValueType();
8765       // Quit if not 128/256-bit vector.
8766       if (!VT.is128BitVector() && !VT.is256BitVector())
8767         return SDValue();
8768       // Quit if not the same type.
8769       if (VecInMap.begin() != VecInMap.end() &&
8770           VT != VecInMap.begin()->first.getValueType())
8771         return SDValue();
8772       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8773     }
8774     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8775   }
8776
8777   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8778          "Not extracted from 128-/256-bit vector.");
8779
8780   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8781   SmallVector<SDValue, 8> VecIns;
8782
8783   for (DenseMap<SDValue, unsigned>::const_iterator
8784         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8785     // Quit if not all elements are used.
8786     if (I->second != FullMask)
8787       return SDValue();
8788     VecIns.push_back(I->first);
8789   }
8790
8791   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8792
8793   // Cast all vectors into TestVT for PTEST.
8794   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8795     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8796
8797   // If more than one full vectors are evaluated, OR them first before PTEST.
8798   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8799     // Each iteration will OR 2 nodes and append the result until there is only
8800     // 1 node left, i.e. the final OR'd value of all vectors.
8801     SDValue LHS = VecIns[Slot];
8802     SDValue RHS = VecIns[Slot + 1];
8803     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8804   }
8805
8806   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8807                      VecIns.back(), VecIns.back());
8808 }
8809
8810 /// Emit nodes that will be selected as "test Op0,Op0", or something
8811 /// equivalent.
8812 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8813                                     SelectionDAG &DAG) const {
8814   DebugLoc dl = Op.getDebugLoc();
8815
8816   // CF and OF aren't always set the way we want. Determine which
8817   // of these we need.
8818   bool NeedCF = false;
8819   bool NeedOF = false;
8820   switch (X86CC) {
8821   default: break;
8822   case X86::COND_A: case X86::COND_AE:
8823   case X86::COND_B: case X86::COND_BE:
8824     NeedCF = true;
8825     break;
8826   case X86::COND_G: case X86::COND_GE:
8827   case X86::COND_L: case X86::COND_LE:
8828   case X86::COND_O: case X86::COND_NO:
8829     NeedOF = true;
8830     break;
8831   }
8832
8833   // See if we can use the EFLAGS value from the operand instead of
8834   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8835   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8836   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8837     // Emit a CMP with 0, which is the TEST pattern.
8838     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839                        DAG.getConstant(0, Op.getValueType()));
8840
8841   unsigned Opcode = 0;
8842   unsigned NumOperands = 0;
8843
8844   // Truncate operations may prevent the merge of the SETCC instruction
8845   // and the arithmetic intruction before it. Attempt to truncate the operands
8846   // of the arithmetic instruction and use a reduced bit-width instruction.
8847   bool NeedTruncation = false;
8848   SDValue ArithOp = Op;
8849   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8850     SDValue Arith = Op->getOperand(0);
8851     // Both the trunc and the arithmetic op need to have one user each.
8852     if (Arith->hasOneUse())
8853       switch (Arith.getOpcode()) {
8854         default: break;
8855         case ISD::ADD:
8856         case ISD::SUB:
8857         case ISD::AND:
8858         case ISD::OR:
8859         case ISD::XOR: {
8860           NeedTruncation = true;
8861           ArithOp = Arith;
8862         }
8863       }
8864   }
8865
8866   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8867   // which may be the result of a CAST.  We use the variable 'Op', which is the
8868   // non-casted variable when we check for possible users.
8869   switch (ArithOp.getOpcode()) {
8870   case ISD::ADD:
8871     // Due to an isel shortcoming, be conservative if this add is likely to be
8872     // selected as part of a load-modify-store instruction. When the root node
8873     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8874     // uses of other nodes in the match, such as the ADD in this case. This
8875     // leads to the ADD being left around and reselected, with the result being
8876     // two adds in the output.  Alas, even if none our users are stores, that
8877     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8878     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8879     // climbing the DAG back to the root, and it doesn't seem to be worth the
8880     // effort.
8881     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8882          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8883       if (UI->getOpcode() != ISD::CopyToReg &&
8884           UI->getOpcode() != ISD::SETCC &&
8885           UI->getOpcode() != ISD::STORE)
8886         goto default_case;
8887
8888     if (ConstantSDNode *C =
8889         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8890       // An add of one will be selected as an INC.
8891       if (C->getAPIntValue() == 1) {
8892         Opcode = X86ISD::INC;
8893         NumOperands = 1;
8894         break;
8895       }
8896
8897       // An add of negative one (subtract of one) will be selected as a DEC.
8898       if (C->getAPIntValue().isAllOnesValue()) {
8899         Opcode = X86ISD::DEC;
8900         NumOperands = 1;
8901         break;
8902       }
8903     }
8904
8905     // Otherwise use a regular EFLAGS-setting add.
8906     Opcode = X86ISD::ADD;
8907     NumOperands = 2;
8908     break;
8909   case ISD::AND: {
8910     // If the primary and result isn't used, don't bother using X86ISD::AND,
8911     // because a TEST instruction will be better.
8912     bool NonFlagUse = false;
8913     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8914            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8915       SDNode *User = *UI;
8916       unsigned UOpNo = UI.getOperandNo();
8917       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8918         // Look pass truncate.
8919         UOpNo = User->use_begin().getOperandNo();
8920         User = *User->use_begin();
8921       }
8922
8923       if (User->getOpcode() != ISD::BRCOND &&
8924           User->getOpcode() != ISD::SETCC &&
8925           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8926         NonFlagUse = true;
8927         break;
8928       }
8929     }
8930
8931     if (!NonFlagUse)
8932       break;
8933   }
8934     // FALL THROUGH
8935   case ISD::SUB:
8936   case ISD::OR:
8937   case ISD::XOR:
8938     // Due to the ISEL shortcoming noted above, be conservative if this op is
8939     // likely to be selected as part of a load-modify-store instruction.
8940     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8941            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8942       if (UI->getOpcode() == ISD::STORE)
8943         goto default_case;
8944
8945     // Otherwise use a regular EFLAGS-setting instruction.
8946     switch (ArithOp.getOpcode()) {
8947     default: llvm_unreachable("unexpected operator!");
8948     case ISD::SUB: Opcode = X86ISD::SUB; break;
8949     case ISD::XOR: Opcode = X86ISD::XOR; break;
8950     case ISD::AND: Opcode = X86ISD::AND; break;
8951     case ISD::OR: {
8952       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8953         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8954         if (EFLAGS.getNode())
8955           return EFLAGS;
8956       }
8957       Opcode = X86ISD::OR;
8958       break;
8959     }
8960     }
8961
8962     NumOperands = 2;
8963     break;
8964   case X86ISD::ADD:
8965   case X86ISD::SUB:
8966   case X86ISD::INC:
8967   case X86ISD::DEC:
8968   case X86ISD::OR:
8969   case X86ISD::XOR:
8970   case X86ISD::AND:
8971     return SDValue(Op.getNode(), 1);
8972   default:
8973   default_case:
8974     break;
8975   }
8976
8977   // If we found that truncation is beneficial, perform the truncation and
8978   // update 'Op'.
8979   if (NeedTruncation) {
8980     EVT VT = Op.getValueType();
8981     SDValue WideVal = Op->getOperand(0);
8982     EVT WideVT = WideVal.getValueType();
8983     unsigned ConvertedOp = 0;
8984     // Use a target machine opcode to prevent further DAGCombine
8985     // optimizations that may separate the arithmetic operations
8986     // from the setcc node.
8987     switch (WideVal.getOpcode()) {
8988       default: break;
8989       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8990       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8991       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8992       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8993       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8994     }
8995
8996     if (ConvertedOp) {
8997       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8998       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8999         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9000         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9001         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9002       }
9003     }
9004   }
9005
9006   if (Opcode == 0)
9007     // Emit a CMP with 0, which is the TEST pattern.
9008     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9009                        DAG.getConstant(0, Op.getValueType()));
9010
9011   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9012   SmallVector<SDValue, 4> Ops;
9013   for (unsigned i = 0; i != NumOperands; ++i)
9014     Ops.push_back(Op.getOperand(i));
9015
9016   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9017   DAG.ReplaceAllUsesWith(Op, New);
9018   return SDValue(New.getNode(), 1);
9019 }
9020
9021 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9022 /// equivalent.
9023 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9024                                    SelectionDAG &DAG) const {
9025   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9026     if (C->getAPIntValue() == 0)
9027       return EmitTest(Op0, X86CC, DAG);
9028
9029   DebugLoc dl = Op0.getDebugLoc();
9030   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9031        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9032     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9033     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9034     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9035                               Op0, Op1);
9036     return SDValue(Sub.getNode(), 1);
9037   }
9038   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9039 }
9040
9041 /// Convert a comparison if required by the subtarget.
9042 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9043                                                  SelectionDAG &DAG) const {
9044   // If the subtarget does not support the FUCOMI instruction, floating-point
9045   // comparisons have to be converted.
9046   if (Subtarget->hasCMov() ||
9047       Cmp.getOpcode() != X86ISD::CMP ||
9048       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9049       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9050     return Cmp;
9051
9052   // The instruction selector will select an FUCOM instruction instead of
9053   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9054   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9055   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9056   DebugLoc dl = Cmp.getDebugLoc();
9057   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9058   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9059   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9060                             DAG.getConstant(8, MVT::i8));
9061   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9062   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9063 }
9064
9065 static bool isAllOnes(SDValue V) {
9066   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9067   return C && C->isAllOnesValue();
9068 }
9069
9070 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9071 /// if it's possible.
9072 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9073                                      DebugLoc dl, SelectionDAG &DAG) const {
9074   SDValue Op0 = And.getOperand(0);
9075   SDValue Op1 = And.getOperand(1);
9076   if (Op0.getOpcode() == ISD::TRUNCATE)
9077     Op0 = Op0.getOperand(0);
9078   if (Op1.getOpcode() == ISD::TRUNCATE)
9079     Op1 = Op1.getOperand(0);
9080
9081   SDValue LHS, RHS;
9082   if (Op1.getOpcode() == ISD::SHL)
9083     std::swap(Op0, Op1);
9084   if (Op0.getOpcode() == ISD::SHL) {
9085     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9086       if (And00C->getZExtValue() == 1) {
9087         // If we looked past a truncate, check that it's only truncating away
9088         // known zeros.
9089         unsigned BitWidth = Op0.getValueSizeInBits();
9090         unsigned AndBitWidth = And.getValueSizeInBits();
9091         if (BitWidth > AndBitWidth) {
9092           APInt Zeros, Ones;
9093           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9094           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9095             return SDValue();
9096         }
9097         LHS = Op1;
9098         RHS = Op0.getOperand(1);
9099       }
9100   } else if (Op1.getOpcode() == ISD::Constant) {
9101     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9102     uint64_t AndRHSVal = AndRHS->getZExtValue();
9103     SDValue AndLHS = Op0;
9104
9105     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9106       LHS = AndLHS.getOperand(0);
9107       RHS = AndLHS.getOperand(1);
9108     }
9109
9110     // Use BT if the immediate can't be encoded in a TEST instruction.
9111     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9112       LHS = AndLHS;
9113       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9114     }
9115   }
9116
9117   if (LHS.getNode()) {
9118     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9119     // the condition code later.
9120     bool Invert = false;
9121     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9122       Invert = true;
9123       LHS = LHS.getOperand(0);
9124     }
9125
9126     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9127     // instruction.  Since the shift amount is in-range-or-undefined, we know
9128     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9129     // the encoding for the i16 version is larger than the i32 version.
9130     // Also promote i16 to i32 for performance / code size reason.
9131     if (LHS.getValueType() == MVT::i8 ||
9132         LHS.getValueType() == MVT::i16)
9133       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9134
9135     // If the operand types disagree, extend the shift amount to match.  Since
9136     // BT ignores high bits (like shifts) we can use anyextend.
9137     if (LHS.getValueType() != RHS.getValueType())
9138       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9139
9140     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9141     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9142     // Flip the condition if the LHS was a not instruction
9143     if (Invert)
9144       Cond = X86::GetOppositeBranchCondition(Cond);
9145     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9146                        DAG.getConstant(Cond, MVT::i8), BT);
9147   }
9148
9149   return SDValue();
9150 }
9151
9152 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9153 // ones, and then concatenate the result back.
9154 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9155   MVT VT = Op.getValueType().getSimpleVT();
9156
9157   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9158          "Unsupported value type for operation");
9159
9160   unsigned NumElems = VT.getVectorNumElements();
9161   DebugLoc dl = Op.getDebugLoc();
9162   SDValue CC = Op.getOperand(2);
9163
9164   // Extract the LHS vectors
9165   SDValue LHS = Op.getOperand(0);
9166   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9167   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9168
9169   // Extract the RHS vectors
9170   SDValue RHS = Op.getOperand(1);
9171   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9172   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9173
9174   // Issue the operation on the smaller types and concatenate the result back
9175   MVT EltVT = VT.getVectorElementType();
9176   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9177   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9178                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9179                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9180 }
9181
9182 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9183                            SelectionDAG &DAG) {
9184   SDValue Cond;
9185   SDValue Op0 = Op.getOperand(0);
9186   SDValue Op1 = Op.getOperand(1);
9187   SDValue CC = Op.getOperand(2);
9188   MVT VT = Op.getValueType().getSimpleVT();
9189   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9190   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9191   DebugLoc dl = Op.getDebugLoc();
9192
9193   if (isFP) {
9194 #ifndef NDEBUG
9195     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9196     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9197 #endif
9198
9199     unsigned SSECC;
9200     bool Swap = false;
9201
9202     // SSE Condition code mapping:
9203     //  0 - EQ
9204     //  1 - LT
9205     //  2 - LE
9206     //  3 - UNORD
9207     //  4 - NEQ
9208     //  5 - NLT
9209     //  6 - NLE
9210     //  7 - ORD
9211     switch (SetCCOpcode) {
9212     default: llvm_unreachable("Unexpected SETCC condition");
9213     case ISD::SETOEQ:
9214     case ISD::SETEQ:  SSECC = 0; break;
9215     case ISD::SETOGT:
9216     case ISD::SETGT: Swap = true; // Fallthrough
9217     case ISD::SETLT:
9218     case ISD::SETOLT: SSECC = 1; break;
9219     case ISD::SETOGE:
9220     case ISD::SETGE: Swap = true; // Fallthrough
9221     case ISD::SETLE:
9222     case ISD::SETOLE: SSECC = 2; break;
9223     case ISD::SETUO:  SSECC = 3; break;
9224     case ISD::SETUNE:
9225     case ISD::SETNE:  SSECC = 4; break;
9226     case ISD::SETULE: Swap = true; // Fallthrough
9227     case ISD::SETUGE: SSECC = 5; break;
9228     case ISD::SETULT: Swap = true; // Fallthrough
9229     case ISD::SETUGT: SSECC = 6; break;
9230     case ISD::SETO:   SSECC = 7; break;
9231     case ISD::SETUEQ:
9232     case ISD::SETONE: SSECC = 8; break;
9233     }
9234     if (Swap)
9235       std::swap(Op0, Op1);
9236
9237     // In the two special cases we can't handle, emit two comparisons.
9238     if (SSECC == 8) {
9239       unsigned CC0, CC1;
9240       unsigned CombineOpc;
9241       if (SetCCOpcode == ISD::SETUEQ) {
9242         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9243       } else {
9244         assert(SetCCOpcode == ISD::SETONE);
9245         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9246       }
9247
9248       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9249                                  DAG.getConstant(CC0, MVT::i8));
9250       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9251                                  DAG.getConstant(CC1, MVT::i8));
9252       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9253     }
9254     // Handle all other FP comparisons here.
9255     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9256                        DAG.getConstant(SSECC, MVT::i8));
9257   }
9258
9259   // Break 256-bit integer vector compare into smaller ones.
9260   if (VT.is256BitVector() && !Subtarget->hasInt256())
9261     return Lower256IntVSETCC(Op, DAG);
9262
9263   // We are handling one of the integer comparisons here.  Since SSE only has
9264   // GT and EQ comparisons for integer, swapping operands and multiple
9265   // operations may be required for some comparisons.
9266   unsigned Opc;
9267   bool Swap = false, Invert = false, FlipSigns = false;
9268
9269   switch (SetCCOpcode) {
9270   default: llvm_unreachable("Unexpected SETCC condition");
9271   case ISD::SETNE:  Invert = true;
9272   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9273   case ISD::SETLT:  Swap = true;
9274   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9275   case ISD::SETGE:  Swap = true;
9276   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9277   case ISD::SETULT: Swap = true;
9278   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9279   case ISD::SETUGE: Swap = true;
9280   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9281   }
9282   if (Swap)
9283     std::swap(Op0, Op1);
9284
9285   // Check that the operation in question is available (most are plain SSE2,
9286   // but PCMPGTQ and PCMPEQQ have different requirements).
9287   if (VT == MVT::v2i64) {
9288     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9289       return SDValue();
9290     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9291       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9292       // pcmpeqd + pshufd + pand.
9293       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9294
9295       // First cast everything to the right type,
9296       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9297       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9298
9299       // Do the compare.
9300       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9301
9302       // Make sure the lower and upper halves are both all-ones.
9303       const int Mask[] = { 1, 0, 3, 2 };
9304       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9305       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9306
9307       if (Invert)
9308         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9309
9310       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9311     }
9312   }
9313
9314   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9315   // bits of the inputs before performing those operations.
9316   if (FlipSigns) {
9317     EVT EltVT = VT.getVectorElementType();
9318     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9319                                       EltVT);
9320     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9321     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9322                                     SignBits.size());
9323     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9324     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9325   }
9326
9327   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9328
9329   // If the logical-not of the result is required, perform that now.
9330   if (Invert)
9331     Result = DAG.getNOT(dl, Result, VT);
9332
9333   return Result;
9334 }
9335
9336 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9337
9338   MVT VT = Op.getValueType().getSimpleVT();
9339
9340   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9341
9342   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9343   SDValue Op0 = Op.getOperand(0);
9344   SDValue Op1 = Op.getOperand(1);
9345   DebugLoc dl = Op.getDebugLoc();
9346   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9347
9348   // Optimize to BT if possible.
9349   // Lower (X & (1 << N)) == 0 to BT(X, N).
9350   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9351   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9352   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9353       Op1.getOpcode() == ISD::Constant &&
9354       cast<ConstantSDNode>(Op1)->isNullValue() &&
9355       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9356     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9357     if (NewSetCC.getNode())
9358       return NewSetCC;
9359   }
9360
9361   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9362   // these.
9363   if (Op1.getOpcode() == ISD::Constant &&
9364       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9365        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9366       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9367
9368     // If the input is a setcc, then reuse the input setcc or use a new one with
9369     // the inverted condition.
9370     if (Op0.getOpcode() == X86ISD::SETCC) {
9371       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9372       bool Invert = (CC == ISD::SETNE) ^
9373         cast<ConstantSDNode>(Op1)->isNullValue();
9374       if (!Invert) return Op0;
9375
9376       CCode = X86::GetOppositeBranchCondition(CCode);
9377       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9378                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9379     }
9380   }
9381
9382   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9383   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9384   if (X86CC == X86::COND_INVALID)
9385     return SDValue();
9386
9387   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9388   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9389   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9390                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9391 }
9392
9393 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9394 static bool isX86LogicalCmp(SDValue Op) {
9395   unsigned Opc = Op.getNode()->getOpcode();
9396   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9397       Opc == X86ISD::SAHF)
9398     return true;
9399   if (Op.getResNo() == 1 &&
9400       (Opc == X86ISD::ADD ||
9401        Opc == X86ISD::SUB ||
9402        Opc == X86ISD::ADC ||
9403        Opc == X86ISD::SBB ||
9404        Opc == X86ISD::SMUL ||
9405        Opc == X86ISD::UMUL ||
9406        Opc == X86ISD::INC ||
9407        Opc == X86ISD::DEC ||
9408        Opc == X86ISD::OR ||
9409        Opc == X86ISD::XOR ||
9410        Opc == X86ISD::AND))
9411     return true;
9412
9413   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9414     return true;
9415
9416   return false;
9417 }
9418
9419 static bool isZero(SDValue V) {
9420   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9421   return C && C->isNullValue();
9422 }
9423
9424 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9425   if (V.getOpcode() != ISD::TRUNCATE)
9426     return false;
9427
9428   SDValue VOp0 = V.getOperand(0);
9429   unsigned InBits = VOp0.getValueSizeInBits();
9430   unsigned Bits = V.getValueSizeInBits();
9431   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9432 }
9433
9434 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9435   bool addTest = true;
9436   SDValue Cond  = Op.getOperand(0);
9437   SDValue Op1 = Op.getOperand(1);
9438   SDValue Op2 = Op.getOperand(2);
9439   DebugLoc DL = Op.getDebugLoc();
9440   SDValue CC;
9441
9442   if (Cond.getOpcode() == ISD::SETCC) {
9443     SDValue NewCond = LowerSETCC(Cond, DAG);
9444     if (NewCond.getNode())
9445       Cond = NewCond;
9446   }
9447
9448   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9449   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9450   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9451   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9452   if (Cond.getOpcode() == X86ISD::SETCC &&
9453       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9454       isZero(Cond.getOperand(1).getOperand(1))) {
9455     SDValue Cmp = Cond.getOperand(1);
9456
9457     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9458
9459     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9460         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9461       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9462
9463       SDValue CmpOp0 = Cmp.getOperand(0);
9464       // Apply further optimizations for special cases
9465       // (select (x != 0), -1, 0) -> neg & sbb
9466       // (select (x == 0), 0, -1) -> neg & sbb
9467       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9468         if (YC->isNullValue() &&
9469             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9470           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9471           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9472                                     DAG.getConstant(0, CmpOp0.getValueType()),
9473                                     CmpOp0);
9474           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9475                                     DAG.getConstant(X86::COND_B, MVT::i8),
9476                                     SDValue(Neg.getNode(), 1));
9477           return Res;
9478         }
9479
9480       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9481                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9482       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9483
9484       SDValue Res =   // Res = 0 or -1.
9485         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9486                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9487
9488       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9489         Res = DAG.getNOT(DL, Res, Res.getValueType());
9490
9491       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9492       if (N2C == 0 || !N2C->isNullValue())
9493         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9494       return Res;
9495     }
9496   }
9497
9498   // Look past (and (setcc_carry (cmp ...)), 1).
9499   if (Cond.getOpcode() == ISD::AND &&
9500       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9501     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9502     if (C && C->getAPIntValue() == 1)
9503       Cond = Cond.getOperand(0);
9504   }
9505
9506   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9507   // setting operand in place of the X86ISD::SETCC.
9508   unsigned CondOpcode = Cond.getOpcode();
9509   if (CondOpcode == X86ISD::SETCC ||
9510       CondOpcode == X86ISD::SETCC_CARRY) {
9511     CC = Cond.getOperand(0);
9512
9513     SDValue Cmp = Cond.getOperand(1);
9514     unsigned Opc = Cmp.getOpcode();
9515     MVT VT = Op.getValueType().getSimpleVT();
9516
9517     bool IllegalFPCMov = false;
9518     if (VT.isFloatingPoint() && !VT.isVector() &&
9519         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9520       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9521
9522     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9523         Opc == X86ISD::BT) { // FIXME
9524       Cond = Cmp;
9525       addTest = false;
9526     }
9527   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9528              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9529              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9530               Cond.getOperand(0).getValueType() != MVT::i8)) {
9531     SDValue LHS = Cond.getOperand(0);
9532     SDValue RHS = Cond.getOperand(1);
9533     unsigned X86Opcode;
9534     unsigned X86Cond;
9535     SDVTList VTs;
9536     switch (CondOpcode) {
9537     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9538     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9539     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9540     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9541     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9542     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9543     default: llvm_unreachable("unexpected overflowing operator");
9544     }
9545     if (CondOpcode == ISD::UMULO)
9546       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9547                           MVT::i32);
9548     else
9549       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9550
9551     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9552
9553     if (CondOpcode == ISD::UMULO)
9554       Cond = X86Op.getValue(2);
9555     else
9556       Cond = X86Op.getValue(1);
9557
9558     CC = DAG.getConstant(X86Cond, MVT::i8);
9559     addTest = false;
9560   }
9561
9562   if (addTest) {
9563     // Look pass the truncate if the high bits are known zero.
9564     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9565         Cond = Cond.getOperand(0);
9566
9567     // We know the result of AND is compared against zero. Try to match
9568     // it to BT.
9569     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9570       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9571       if (NewSetCC.getNode()) {
9572         CC = NewSetCC.getOperand(0);
9573         Cond = NewSetCC.getOperand(1);
9574         addTest = false;
9575       }
9576     }
9577   }
9578
9579   if (addTest) {
9580     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9581     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9582   }
9583
9584   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9585   // a <  b ?  0 : -1 -> RES = setcc_carry
9586   // a >= b ? -1 :  0 -> RES = setcc_carry
9587   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9588   if (Cond.getOpcode() == X86ISD::SUB) {
9589     Cond = ConvertCmpIfNecessary(Cond, DAG);
9590     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9591
9592     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9593         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9594       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9595                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9596       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9597         return DAG.getNOT(DL, Res, Res.getValueType());
9598       return Res;
9599     }
9600   }
9601
9602   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9603   // widen the cmov and push the truncate through. This avoids introducing a new
9604   // branch during isel and doesn't add any extensions.
9605   if (Op.getValueType() == MVT::i8 &&
9606       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9607     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9608     if (T1.getValueType() == T2.getValueType() &&
9609         // Blacklist CopyFromReg to avoid partial register stalls.
9610         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9611       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9612       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9613       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9614     }
9615   }
9616
9617   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9618   // condition is true.
9619   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9620   SDValue Ops[] = { Op2, Op1, CC, Cond };
9621   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9622 }
9623
9624 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9625                                             SelectionDAG &DAG) const {
9626   MVT VT = Op->getValueType(0).getSimpleVT();
9627   SDValue In = Op->getOperand(0);
9628   MVT InVT = In.getValueType().getSimpleVT();
9629   DebugLoc dl = Op->getDebugLoc();
9630
9631   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9632       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9633     return SDValue();
9634
9635   if (Subtarget->hasInt256())
9636     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9637
9638   // Optimize vectors in AVX mode
9639   // Sign extend  v8i16 to v8i32 and
9640   //              v4i32 to v4i64
9641   //
9642   // Divide input vector into two parts
9643   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9644   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9645   // concat the vectors to original VT
9646
9647   unsigned NumElems = InVT.getVectorNumElements();
9648   SDValue Undef = DAG.getUNDEF(InVT);
9649
9650   SmallVector<int,8> ShufMask1(NumElems, -1);
9651   for (unsigned i = 0; i != NumElems/2; ++i)
9652     ShufMask1[i] = i;
9653
9654   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9655
9656   SmallVector<int,8> ShufMask2(NumElems, -1);
9657   for (unsigned i = 0; i != NumElems/2; ++i)
9658     ShufMask2[i] = i + NumElems/2;
9659
9660   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9661
9662   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9663                                 VT.getVectorNumElements()/2);
9664
9665   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9666   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9667
9668   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9669 }
9670
9671 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9672 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9673 // from the AND / OR.
9674 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9675   Opc = Op.getOpcode();
9676   if (Opc != ISD::OR && Opc != ISD::AND)
9677     return false;
9678   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9679           Op.getOperand(0).hasOneUse() &&
9680           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9681           Op.getOperand(1).hasOneUse());
9682 }
9683
9684 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9685 // 1 and that the SETCC node has a single use.
9686 static bool isXor1OfSetCC(SDValue Op) {
9687   if (Op.getOpcode() != ISD::XOR)
9688     return false;
9689   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9690   if (N1C && N1C->getAPIntValue() == 1) {
9691     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9692       Op.getOperand(0).hasOneUse();
9693   }
9694   return false;
9695 }
9696
9697 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9698   bool addTest = true;
9699   SDValue Chain = Op.getOperand(0);
9700   SDValue Cond  = Op.getOperand(1);
9701   SDValue Dest  = Op.getOperand(2);
9702   DebugLoc dl = Op.getDebugLoc();
9703   SDValue CC;
9704   bool Inverted = false;
9705
9706   if (Cond.getOpcode() == ISD::SETCC) {
9707     // Check for setcc([su]{add,sub,mul}o == 0).
9708     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9709         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9710         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9711         Cond.getOperand(0).getResNo() == 1 &&
9712         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9713          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9714          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9715          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9716          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9717          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9718       Inverted = true;
9719       Cond = Cond.getOperand(0);
9720     } else {
9721       SDValue NewCond = LowerSETCC(Cond, DAG);
9722       if (NewCond.getNode())
9723         Cond = NewCond;
9724     }
9725   }
9726 #if 0
9727   // FIXME: LowerXALUO doesn't handle these!!
9728   else if (Cond.getOpcode() == X86ISD::ADD  ||
9729            Cond.getOpcode() == X86ISD::SUB  ||
9730            Cond.getOpcode() == X86ISD::SMUL ||
9731            Cond.getOpcode() == X86ISD::UMUL)
9732     Cond = LowerXALUO(Cond, DAG);
9733 #endif
9734
9735   // Look pass (and (setcc_carry (cmp ...)), 1).
9736   if (Cond.getOpcode() == ISD::AND &&
9737       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9738     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9739     if (C && C->getAPIntValue() == 1)
9740       Cond = Cond.getOperand(0);
9741   }
9742
9743   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9744   // setting operand in place of the X86ISD::SETCC.
9745   unsigned CondOpcode = Cond.getOpcode();
9746   if (CondOpcode == X86ISD::SETCC ||
9747       CondOpcode == X86ISD::SETCC_CARRY) {
9748     CC = Cond.getOperand(0);
9749
9750     SDValue Cmp = Cond.getOperand(1);
9751     unsigned Opc = Cmp.getOpcode();
9752     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9753     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9754       Cond = Cmp;
9755       addTest = false;
9756     } else {
9757       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9758       default: break;
9759       case X86::COND_O:
9760       case X86::COND_B:
9761         // These can only come from an arithmetic instruction with overflow,
9762         // e.g. SADDO, UADDO.
9763         Cond = Cond.getNode()->getOperand(1);
9764         addTest = false;
9765         break;
9766       }
9767     }
9768   }
9769   CondOpcode = Cond.getOpcode();
9770   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9771       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9772       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9773        Cond.getOperand(0).getValueType() != MVT::i8)) {
9774     SDValue LHS = Cond.getOperand(0);
9775     SDValue RHS = Cond.getOperand(1);
9776     unsigned X86Opcode;
9777     unsigned X86Cond;
9778     SDVTList VTs;
9779     switch (CondOpcode) {
9780     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9781     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9782     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9783     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9784     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9785     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9786     default: llvm_unreachable("unexpected overflowing operator");
9787     }
9788     if (Inverted)
9789       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9790     if (CondOpcode == ISD::UMULO)
9791       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9792                           MVT::i32);
9793     else
9794       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9795
9796     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9797
9798     if (CondOpcode == ISD::UMULO)
9799       Cond = X86Op.getValue(2);
9800     else
9801       Cond = X86Op.getValue(1);
9802
9803     CC = DAG.getConstant(X86Cond, MVT::i8);
9804     addTest = false;
9805   } else {
9806     unsigned CondOpc;
9807     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9808       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9809       if (CondOpc == ISD::OR) {
9810         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9811         // two branches instead of an explicit OR instruction with a
9812         // separate test.
9813         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9814             isX86LogicalCmp(Cmp)) {
9815           CC = Cond.getOperand(0).getOperand(0);
9816           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9817                               Chain, Dest, CC, Cmp);
9818           CC = Cond.getOperand(1).getOperand(0);
9819           Cond = Cmp;
9820           addTest = false;
9821         }
9822       } else { // ISD::AND
9823         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9824         // two branches instead of an explicit AND instruction with a
9825         // separate test. However, we only do this if this block doesn't
9826         // have a fall-through edge, because this requires an explicit
9827         // jmp when the condition is false.
9828         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9829             isX86LogicalCmp(Cmp) &&
9830             Op.getNode()->hasOneUse()) {
9831           X86::CondCode CCode =
9832             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9833           CCode = X86::GetOppositeBranchCondition(CCode);
9834           CC = DAG.getConstant(CCode, MVT::i8);
9835           SDNode *User = *Op.getNode()->use_begin();
9836           // Look for an unconditional branch following this conditional branch.
9837           // We need this because we need to reverse the successors in order
9838           // to implement FCMP_OEQ.
9839           if (User->getOpcode() == ISD::BR) {
9840             SDValue FalseBB = User->getOperand(1);
9841             SDNode *NewBR =
9842               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9843             assert(NewBR == User);
9844             (void)NewBR;
9845             Dest = FalseBB;
9846
9847             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9848                                 Chain, Dest, CC, Cmp);
9849             X86::CondCode CCode =
9850               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9851             CCode = X86::GetOppositeBranchCondition(CCode);
9852             CC = DAG.getConstant(CCode, MVT::i8);
9853             Cond = Cmp;
9854             addTest = false;
9855           }
9856         }
9857       }
9858     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9859       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9860       // It should be transformed during dag combiner except when the condition
9861       // is set by a arithmetics with overflow node.
9862       X86::CondCode CCode =
9863         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9864       CCode = X86::GetOppositeBranchCondition(CCode);
9865       CC = DAG.getConstant(CCode, MVT::i8);
9866       Cond = Cond.getOperand(0).getOperand(1);
9867       addTest = false;
9868     } else if (Cond.getOpcode() == ISD::SETCC &&
9869                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9870       // For FCMP_OEQ, we can emit
9871       // two branches instead of an explicit AND instruction with a
9872       // separate test. However, we only do this if this block doesn't
9873       // have a fall-through edge, because this requires an explicit
9874       // jmp when the condition is false.
9875       if (Op.getNode()->hasOneUse()) {
9876         SDNode *User = *Op.getNode()->use_begin();
9877         // Look for an unconditional branch following this conditional branch.
9878         // We need this because we need to reverse the successors in order
9879         // to implement FCMP_OEQ.
9880         if (User->getOpcode() == ISD::BR) {
9881           SDValue FalseBB = User->getOperand(1);
9882           SDNode *NewBR =
9883             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9884           assert(NewBR == User);
9885           (void)NewBR;
9886           Dest = FalseBB;
9887
9888           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9889                                     Cond.getOperand(0), Cond.getOperand(1));
9890           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9891           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9892           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9893                               Chain, Dest, CC, Cmp);
9894           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9895           Cond = Cmp;
9896           addTest = false;
9897         }
9898       }
9899     } else if (Cond.getOpcode() == ISD::SETCC &&
9900                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9901       // For FCMP_UNE, we can emit
9902       // two branches instead of an explicit AND instruction with a
9903       // separate test. However, we only do this if this block doesn't
9904       // have a fall-through edge, because this requires an explicit
9905       // jmp when the condition is false.
9906       if (Op.getNode()->hasOneUse()) {
9907         SDNode *User = *Op.getNode()->use_begin();
9908         // Look for an unconditional branch following this conditional branch.
9909         // We need this because we need to reverse the successors in order
9910         // to implement FCMP_UNE.
9911         if (User->getOpcode() == ISD::BR) {
9912           SDValue FalseBB = User->getOperand(1);
9913           SDNode *NewBR =
9914             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9915           assert(NewBR == User);
9916           (void)NewBR;
9917
9918           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9919                                     Cond.getOperand(0), Cond.getOperand(1));
9920           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9921           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9922           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9923                               Chain, Dest, CC, Cmp);
9924           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9925           Cond = Cmp;
9926           addTest = false;
9927           Dest = FalseBB;
9928         }
9929       }
9930     }
9931   }
9932
9933   if (addTest) {
9934     // Look pass the truncate if the high bits are known zero.
9935     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9936         Cond = Cond.getOperand(0);
9937
9938     // We know the result of AND is compared against zero. Try to match
9939     // it to BT.
9940     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9941       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9942       if (NewSetCC.getNode()) {
9943         CC = NewSetCC.getOperand(0);
9944         Cond = NewSetCC.getOperand(1);
9945         addTest = false;
9946       }
9947     }
9948   }
9949
9950   if (addTest) {
9951     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9952     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9953   }
9954   Cond = ConvertCmpIfNecessary(Cond, DAG);
9955   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9956                      Chain, Dest, CC, Cond);
9957 }
9958
9959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9960 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9962 // that the guard pages used by the OS virtual memory manager are allocated in
9963 // correct sequence.
9964 SDValue
9965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9966                                            SelectionDAG &DAG) const {
9967   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9968           getTargetMachine().Options.EnableSegmentedStacks) &&
9969          "This should be used only on Windows targets or when segmented stacks "
9970          "are being used");
9971   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9972   DebugLoc dl = Op.getDebugLoc();
9973
9974   // Get the inputs.
9975   SDValue Chain = Op.getOperand(0);
9976   SDValue Size  = Op.getOperand(1);
9977   // FIXME: Ensure alignment here
9978
9979   bool Is64Bit = Subtarget->is64Bit();
9980   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9981
9982   if (getTargetMachine().Options.EnableSegmentedStacks) {
9983     MachineFunction &MF = DAG.getMachineFunction();
9984     MachineRegisterInfo &MRI = MF.getRegInfo();
9985
9986     if (Is64Bit) {
9987       // The 64 bit implementation of segmented stacks needs to clobber both r10
9988       // r11. This makes it impossible to use it along with nested parameters.
9989       const Function *F = MF.getFunction();
9990
9991       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9992            I != E; ++I)
9993         if (I->hasNestAttr())
9994           report_fatal_error("Cannot use segmented stacks with functions that "
9995                              "have nested arguments.");
9996     }
9997
9998     const TargetRegisterClass *AddrRegClass =
9999       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10000     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10001     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10002     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10003                                 DAG.getRegister(Vreg, SPTy));
10004     SDValue Ops1[2] = { Value, Chain };
10005     return DAG.getMergeValues(Ops1, 2, dl);
10006   } else {
10007     SDValue Flag;
10008     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10009
10010     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10011     Flag = Chain.getValue(1);
10012     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10013
10014     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10015     Flag = Chain.getValue(1);
10016
10017     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10018                                SPTy).getValue(1);
10019
10020     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10021     return DAG.getMergeValues(Ops1, 2, dl);
10022   }
10023 }
10024
10025 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10026   MachineFunction &MF = DAG.getMachineFunction();
10027   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10028
10029   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10030   DebugLoc DL = Op.getDebugLoc();
10031
10032   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10033     // vastart just stores the address of the VarArgsFrameIndex slot into the
10034     // memory location argument.
10035     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10036                                    getPointerTy());
10037     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10038                         MachinePointerInfo(SV), false, false, 0);
10039   }
10040
10041   // __va_list_tag:
10042   //   gp_offset         (0 - 6 * 8)
10043   //   fp_offset         (48 - 48 + 8 * 16)
10044   //   overflow_arg_area (point to parameters coming in memory).
10045   //   reg_save_area
10046   SmallVector<SDValue, 8> MemOps;
10047   SDValue FIN = Op.getOperand(1);
10048   // Store gp_offset
10049   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10050                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10051                                                MVT::i32),
10052                                FIN, MachinePointerInfo(SV), false, false, 0);
10053   MemOps.push_back(Store);
10054
10055   // Store fp_offset
10056   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10057                     FIN, DAG.getIntPtrConstant(4));
10058   Store = DAG.getStore(Op.getOperand(0), DL,
10059                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10060                                        MVT::i32),
10061                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10062   MemOps.push_back(Store);
10063
10064   // Store ptr to overflow_arg_area
10065   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10066                     FIN, DAG.getIntPtrConstant(4));
10067   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10068                                     getPointerTy());
10069   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10070                        MachinePointerInfo(SV, 8),
10071                        false, false, 0);
10072   MemOps.push_back(Store);
10073
10074   // Store ptr to reg_save_area.
10075   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10076                     FIN, DAG.getIntPtrConstant(8));
10077   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10078                                     getPointerTy());
10079   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10080                        MachinePointerInfo(SV, 16), false, false, 0);
10081   MemOps.push_back(Store);
10082   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10083                      &MemOps[0], MemOps.size());
10084 }
10085
10086 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10087   assert(Subtarget->is64Bit() &&
10088          "LowerVAARG only handles 64-bit va_arg!");
10089   assert((Subtarget->isTargetLinux() ||
10090           Subtarget->isTargetDarwin()) &&
10091           "Unhandled target in LowerVAARG");
10092   assert(Op.getNode()->getNumOperands() == 4);
10093   SDValue Chain = Op.getOperand(0);
10094   SDValue SrcPtr = Op.getOperand(1);
10095   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10096   unsigned Align = Op.getConstantOperandVal(3);
10097   DebugLoc dl = Op.getDebugLoc();
10098
10099   EVT ArgVT = Op.getNode()->getValueType(0);
10100   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10101   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10102   uint8_t ArgMode;
10103
10104   // Decide which area this value should be read from.
10105   // TODO: Implement the AMD64 ABI in its entirety. This simple
10106   // selection mechanism works only for the basic types.
10107   if (ArgVT == MVT::f80) {
10108     llvm_unreachable("va_arg for f80 not yet implemented");
10109   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10110     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10111   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10112     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10113   } else {
10114     llvm_unreachable("Unhandled argument type in LowerVAARG");
10115   }
10116
10117   if (ArgMode == 2) {
10118     // Sanity Check: Make sure using fp_offset makes sense.
10119     assert(!getTargetMachine().Options.UseSoftFloat &&
10120            !(DAG.getMachineFunction()
10121                 .getFunction()->getAttributes()
10122                 .hasAttribute(AttributeSet::FunctionIndex,
10123                               Attribute::NoImplicitFloat)) &&
10124            Subtarget->hasSSE1());
10125   }
10126
10127   // Insert VAARG_64 node into the DAG
10128   // VAARG_64 returns two values: Variable Argument Address, Chain
10129   SmallVector<SDValue, 11> InstOps;
10130   InstOps.push_back(Chain);
10131   InstOps.push_back(SrcPtr);
10132   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10133   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10134   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10135   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10136   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10137                                           VTs, &InstOps[0], InstOps.size(),
10138                                           MVT::i64,
10139                                           MachinePointerInfo(SV),
10140                                           /*Align=*/0,
10141                                           /*Volatile=*/false,
10142                                           /*ReadMem=*/true,
10143                                           /*WriteMem=*/true);
10144   Chain = VAARG.getValue(1);
10145
10146   // Load the next argument and return it
10147   return DAG.getLoad(ArgVT, dl,
10148                      Chain,
10149                      VAARG,
10150                      MachinePointerInfo(),
10151                      false, false, false, 0);
10152 }
10153
10154 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10155                            SelectionDAG &DAG) {
10156   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10157   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10158   SDValue Chain = Op.getOperand(0);
10159   SDValue DstPtr = Op.getOperand(1);
10160   SDValue SrcPtr = Op.getOperand(2);
10161   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10162   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10163   DebugLoc DL = Op.getDebugLoc();
10164
10165   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10166                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10167                        false,
10168                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10169 }
10170
10171 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10172 // may or may not be a constant. Takes immediate version of shift as input.
10173 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10174                                    SDValue SrcOp, SDValue ShAmt,
10175                                    SelectionDAG &DAG) {
10176   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10177
10178   if (isa<ConstantSDNode>(ShAmt)) {
10179     // Constant may be a TargetConstant. Use a regular constant.
10180     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10181     switch (Opc) {
10182       default: llvm_unreachable("Unknown target vector shift node");
10183       case X86ISD::VSHLI:
10184       case X86ISD::VSRLI:
10185       case X86ISD::VSRAI:
10186         return DAG.getNode(Opc, dl, VT, SrcOp,
10187                            DAG.getConstant(ShiftAmt, MVT::i32));
10188     }
10189   }
10190
10191   // Change opcode to non-immediate version
10192   switch (Opc) {
10193     default: llvm_unreachable("Unknown target vector shift node");
10194     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10195     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10196     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10197   }
10198
10199   // Need to build a vector containing shift amount
10200   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10201   SDValue ShOps[4];
10202   ShOps[0] = ShAmt;
10203   ShOps[1] = DAG.getConstant(0, MVT::i32);
10204   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10205   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10206
10207   // The return type has to be a 128-bit type with the same element
10208   // type as the input type.
10209   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10210   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10211
10212   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10213   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10214 }
10215
10216 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10217   DebugLoc dl = Op.getDebugLoc();
10218   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10219   switch (IntNo) {
10220   default: return SDValue();    // Don't custom lower most intrinsics.
10221   // Comparison intrinsics.
10222   case Intrinsic::x86_sse_comieq_ss:
10223   case Intrinsic::x86_sse_comilt_ss:
10224   case Intrinsic::x86_sse_comile_ss:
10225   case Intrinsic::x86_sse_comigt_ss:
10226   case Intrinsic::x86_sse_comige_ss:
10227   case Intrinsic::x86_sse_comineq_ss:
10228   case Intrinsic::x86_sse_ucomieq_ss:
10229   case Intrinsic::x86_sse_ucomilt_ss:
10230   case Intrinsic::x86_sse_ucomile_ss:
10231   case Intrinsic::x86_sse_ucomigt_ss:
10232   case Intrinsic::x86_sse_ucomige_ss:
10233   case Intrinsic::x86_sse_ucomineq_ss:
10234   case Intrinsic::x86_sse2_comieq_sd:
10235   case Intrinsic::x86_sse2_comilt_sd:
10236   case Intrinsic::x86_sse2_comile_sd:
10237   case Intrinsic::x86_sse2_comigt_sd:
10238   case Intrinsic::x86_sse2_comige_sd:
10239   case Intrinsic::x86_sse2_comineq_sd:
10240   case Intrinsic::x86_sse2_ucomieq_sd:
10241   case Intrinsic::x86_sse2_ucomilt_sd:
10242   case Intrinsic::x86_sse2_ucomile_sd:
10243   case Intrinsic::x86_sse2_ucomigt_sd:
10244   case Intrinsic::x86_sse2_ucomige_sd:
10245   case Intrinsic::x86_sse2_ucomineq_sd: {
10246     unsigned Opc;
10247     ISD::CondCode CC;
10248     switch (IntNo) {
10249     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10250     case Intrinsic::x86_sse_comieq_ss:
10251     case Intrinsic::x86_sse2_comieq_sd:
10252       Opc = X86ISD::COMI;
10253       CC = ISD::SETEQ;
10254       break;
10255     case Intrinsic::x86_sse_comilt_ss:
10256     case Intrinsic::x86_sse2_comilt_sd:
10257       Opc = X86ISD::COMI;
10258       CC = ISD::SETLT;
10259       break;
10260     case Intrinsic::x86_sse_comile_ss:
10261     case Intrinsic::x86_sse2_comile_sd:
10262       Opc = X86ISD::COMI;
10263       CC = ISD::SETLE;
10264       break;
10265     case Intrinsic::x86_sse_comigt_ss:
10266     case Intrinsic::x86_sse2_comigt_sd:
10267       Opc = X86ISD::COMI;
10268       CC = ISD::SETGT;
10269       break;
10270     case Intrinsic::x86_sse_comige_ss:
10271     case Intrinsic::x86_sse2_comige_sd:
10272       Opc = X86ISD::COMI;
10273       CC = ISD::SETGE;
10274       break;
10275     case Intrinsic::x86_sse_comineq_ss:
10276     case Intrinsic::x86_sse2_comineq_sd:
10277       Opc = X86ISD::COMI;
10278       CC = ISD::SETNE;
10279       break;
10280     case Intrinsic::x86_sse_ucomieq_ss:
10281     case Intrinsic::x86_sse2_ucomieq_sd:
10282       Opc = X86ISD::UCOMI;
10283       CC = ISD::SETEQ;
10284       break;
10285     case Intrinsic::x86_sse_ucomilt_ss:
10286     case Intrinsic::x86_sse2_ucomilt_sd:
10287       Opc = X86ISD::UCOMI;
10288       CC = ISD::SETLT;
10289       break;
10290     case Intrinsic::x86_sse_ucomile_ss:
10291     case Intrinsic::x86_sse2_ucomile_sd:
10292       Opc = X86ISD::UCOMI;
10293       CC = ISD::SETLE;
10294       break;
10295     case Intrinsic::x86_sse_ucomigt_ss:
10296     case Intrinsic::x86_sse2_ucomigt_sd:
10297       Opc = X86ISD::UCOMI;
10298       CC = ISD::SETGT;
10299       break;
10300     case Intrinsic::x86_sse_ucomige_ss:
10301     case Intrinsic::x86_sse2_ucomige_sd:
10302       Opc = X86ISD::UCOMI;
10303       CC = ISD::SETGE;
10304       break;
10305     case Intrinsic::x86_sse_ucomineq_ss:
10306     case Intrinsic::x86_sse2_ucomineq_sd:
10307       Opc = X86ISD::UCOMI;
10308       CC = ISD::SETNE;
10309       break;
10310     }
10311
10312     SDValue LHS = Op.getOperand(1);
10313     SDValue RHS = Op.getOperand(2);
10314     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10315     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10316     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10317     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10318                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10319     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10320   }
10321
10322   // Arithmetic intrinsics.
10323   case Intrinsic::x86_sse2_pmulu_dq:
10324   case Intrinsic::x86_avx2_pmulu_dq:
10325     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10326                        Op.getOperand(1), Op.getOperand(2));
10327
10328   // SSE2/AVX2 sub with unsigned saturation intrinsics
10329   case Intrinsic::x86_sse2_psubus_b:
10330   case Intrinsic::x86_sse2_psubus_w:
10331   case Intrinsic::x86_avx2_psubus_b:
10332   case Intrinsic::x86_avx2_psubus_w:
10333     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10334                        Op.getOperand(1), Op.getOperand(2));
10335
10336   // SSE3/AVX horizontal add/sub intrinsics
10337   case Intrinsic::x86_sse3_hadd_ps:
10338   case Intrinsic::x86_sse3_hadd_pd:
10339   case Intrinsic::x86_avx_hadd_ps_256:
10340   case Intrinsic::x86_avx_hadd_pd_256:
10341   case Intrinsic::x86_sse3_hsub_ps:
10342   case Intrinsic::x86_sse3_hsub_pd:
10343   case Intrinsic::x86_avx_hsub_ps_256:
10344   case Intrinsic::x86_avx_hsub_pd_256:
10345   case Intrinsic::x86_ssse3_phadd_w_128:
10346   case Intrinsic::x86_ssse3_phadd_d_128:
10347   case Intrinsic::x86_avx2_phadd_w:
10348   case Intrinsic::x86_avx2_phadd_d:
10349   case Intrinsic::x86_ssse3_phsub_w_128:
10350   case Intrinsic::x86_ssse3_phsub_d_128:
10351   case Intrinsic::x86_avx2_phsub_w:
10352   case Intrinsic::x86_avx2_phsub_d: {
10353     unsigned Opcode;
10354     switch (IntNo) {
10355     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10356     case Intrinsic::x86_sse3_hadd_ps:
10357     case Intrinsic::x86_sse3_hadd_pd:
10358     case Intrinsic::x86_avx_hadd_ps_256:
10359     case Intrinsic::x86_avx_hadd_pd_256:
10360       Opcode = X86ISD::FHADD;
10361       break;
10362     case Intrinsic::x86_sse3_hsub_ps:
10363     case Intrinsic::x86_sse3_hsub_pd:
10364     case Intrinsic::x86_avx_hsub_ps_256:
10365     case Intrinsic::x86_avx_hsub_pd_256:
10366       Opcode = X86ISD::FHSUB;
10367       break;
10368     case Intrinsic::x86_ssse3_phadd_w_128:
10369     case Intrinsic::x86_ssse3_phadd_d_128:
10370     case Intrinsic::x86_avx2_phadd_w:
10371     case Intrinsic::x86_avx2_phadd_d:
10372       Opcode = X86ISD::HADD;
10373       break;
10374     case Intrinsic::x86_ssse3_phsub_w_128:
10375     case Intrinsic::x86_ssse3_phsub_d_128:
10376     case Intrinsic::x86_avx2_phsub_w:
10377     case Intrinsic::x86_avx2_phsub_d:
10378       Opcode = X86ISD::HSUB;
10379       break;
10380     }
10381     return DAG.getNode(Opcode, dl, Op.getValueType(),
10382                        Op.getOperand(1), Op.getOperand(2));
10383   }
10384
10385   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10386   case Intrinsic::x86_sse2_pmaxu_b:
10387   case Intrinsic::x86_sse41_pmaxuw:
10388   case Intrinsic::x86_sse41_pmaxud:
10389   case Intrinsic::x86_avx2_pmaxu_b:
10390   case Intrinsic::x86_avx2_pmaxu_w:
10391   case Intrinsic::x86_avx2_pmaxu_d:
10392   case Intrinsic::x86_sse2_pminu_b:
10393   case Intrinsic::x86_sse41_pminuw:
10394   case Intrinsic::x86_sse41_pminud:
10395   case Intrinsic::x86_avx2_pminu_b:
10396   case Intrinsic::x86_avx2_pminu_w:
10397   case Intrinsic::x86_avx2_pminu_d:
10398   case Intrinsic::x86_sse41_pmaxsb:
10399   case Intrinsic::x86_sse2_pmaxs_w:
10400   case Intrinsic::x86_sse41_pmaxsd:
10401   case Intrinsic::x86_avx2_pmaxs_b:
10402   case Intrinsic::x86_avx2_pmaxs_w:
10403   case Intrinsic::x86_avx2_pmaxs_d:
10404   case Intrinsic::x86_sse41_pminsb:
10405   case Intrinsic::x86_sse2_pmins_w:
10406   case Intrinsic::x86_sse41_pminsd:
10407   case Intrinsic::x86_avx2_pmins_b:
10408   case Intrinsic::x86_avx2_pmins_w:
10409   case Intrinsic::x86_avx2_pmins_d: {
10410     unsigned Opcode;
10411     switch (IntNo) {
10412     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10413     case Intrinsic::x86_sse2_pmaxu_b:
10414     case Intrinsic::x86_sse41_pmaxuw:
10415     case Intrinsic::x86_sse41_pmaxud:
10416     case Intrinsic::x86_avx2_pmaxu_b:
10417     case Intrinsic::x86_avx2_pmaxu_w:
10418     case Intrinsic::x86_avx2_pmaxu_d:
10419       Opcode = X86ISD::UMAX;
10420       break;
10421     case Intrinsic::x86_sse2_pminu_b:
10422     case Intrinsic::x86_sse41_pminuw:
10423     case Intrinsic::x86_sse41_pminud:
10424     case Intrinsic::x86_avx2_pminu_b:
10425     case Intrinsic::x86_avx2_pminu_w:
10426     case Intrinsic::x86_avx2_pminu_d:
10427       Opcode = X86ISD::UMIN;
10428       break;
10429     case Intrinsic::x86_sse41_pmaxsb:
10430     case Intrinsic::x86_sse2_pmaxs_w:
10431     case Intrinsic::x86_sse41_pmaxsd:
10432     case Intrinsic::x86_avx2_pmaxs_b:
10433     case Intrinsic::x86_avx2_pmaxs_w:
10434     case Intrinsic::x86_avx2_pmaxs_d:
10435       Opcode = X86ISD::SMAX;
10436       break;
10437     case Intrinsic::x86_sse41_pminsb:
10438     case Intrinsic::x86_sse2_pmins_w:
10439     case Intrinsic::x86_sse41_pminsd:
10440     case Intrinsic::x86_avx2_pmins_b:
10441     case Intrinsic::x86_avx2_pmins_w:
10442     case Intrinsic::x86_avx2_pmins_d:
10443       Opcode = X86ISD::SMIN;
10444       break;
10445     }
10446     return DAG.getNode(Opcode, dl, Op.getValueType(),
10447                        Op.getOperand(1), Op.getOperand(2));
10448   }
10449
10450   // SSE/SSE2/AVX floating point max/min intrinsics.
10451   case Intrinsic::x86_sse_max_ps:
10452   case Intrinsic::x86_sse2_max_pd:
10453   case Intrinsic::x86_avx_max_ps_256:
10454   case Intrinsic::x86_avx_max_pd_256:
10455   case Intrinsic::x86_sse_min_ps:
10456   case Intrinsic::x86_sse2_min_pd:
10457   case Intrinsic::x86_avx_min_ps_256:
10458   case Intrinsic::x86_avx_min_pd_256: {
10459     unsigned Opcode;
10460     switch (IntNo) {
10461     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10462     case Intrinsic::x86_sse_max_ps:
10463     case Intrinsic::x86_sse2_max_pd:
10464     case Intrinsic::x86_avx_max_ps_256:
10465     case Intrinsic::x86_avx_max_pd_256:
10466       Opcode = X86ISD::FMAX;
10467       break;
10468     case Intrinsic::x86_sse_min_ps:
10469     case Intrinsic::x86_sse2_min_pd:
10470     case Intrinsic::x86_avx_min_ps_256:
10471     case Intrinsic::x86_avx_min_pd_256:
10472       Opcode = X86ISD::FMIN;
10473       break;
10474     }
10475     return DAG.getNode(Opcode, dl, Op.getValueType(),
10476                        Op.getOperand(1), Op.getOperand(2));
10477   }
10478
10479   // AVX2 variable shift intrinsics
10480   case Intrinsic::x86_avx2_psllv_d:
10481   case Intrinsic::x86_avx2_psllv_q:
10482   case Intrinsic::x86_avx2_psllv_d_256:
10483   case Intrinsic::x86_avx2_psllv_q_256:
10484   case Intrinsic::x86_avx2_psrlv_d:
10485   case Intrinsic::x86_avx2_psrlv_q:
10486   case Intrinsic::x86_avx2_psrlv_d_256:
10487   case Intrinsic::x86_avx2_psrlv_q_256:
10488   case Intrinsic::x86_avx2_psrav_d:
10489   case Intrinsic::x86_avx2_psrav_d_256: {
10490     unsigned Opcode;
10491     switch (IntNo) {
10492     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10493     case Intrinsic::x86_avx2_psllv_d:
10494     case Intrinsic::x86_avx2_psllv_q:
10495     case Intrinsic::x86_avx2_psllv_d_256:
10496     case Intrinsic::x86_avx2_psllv_q_256:
10497       Opcode = ISD::SHL;
10498       break;
10499     case Intrinsic::x86_avx2_psrlv_d:
10500     case Intrinsic::x86_avx2_psrlv_q:
10501     case Intrinsic::x86_avx2_psrlv_d_256:
10502     case Intrinsic::x86_avx2_psrlv_q_256:
10503       Opcode = ISD::SRL;
10504       break;
10505     case Intrinsic::x86_avx2_psrav_d:
10506     case Intrinsic::x86_avx2_psrav_d_256:
10507       Opcode = ISD::SRA;
10508       break;
10509     }
10510     return DAG.getNode(Opcode, dl, Op.getValueType(),
10511                        Op.getOperand(1), Op.getOperand(2));
10512   }
10513
10514   case Intrinsic::x86_ssse3_pshuf_b_128:
10515   case Intrinsic::x86_avx2_pshuf_b:
10516     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10517                        Op.getOperand(1), Op.getOperand(2));
10518
10519   case Intrinsic::x86_ssse3_psign_b_128:
10520   case Intrinsic::x86_ssse3_psign_w_128:
10521   case Intrinsic::x86_ssse3_psign_d_128:
10522   case Intrinsic::x86_avx2_psign_b:
10523   case Intrinsic::x86_avx2_psign_w:
10524   case Intrinsic::x86_avx2_psign_d:
10525     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10526                        Op.getOperand(1), Op.getOperand(2));
10527
10528   case Intrinsic::x86_sse41_insertps:
10529     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10530                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10531
10532   case Intrinsic::x86_avx_vperm2f128_ps_256:
10533   case Intrinsic::x86_avx_vperm2f128_pd_256:
10534   case Intrinsic::x86_avx_vperm2f128_si_256:
10535   case Intrinsic::x86_avx2_vperm2i128:
10536     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10537                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10538
10539   case Intrinsic::x86_avx2_permd:
10540   case Intrinsic::x86_avx2_permps:
10541     // Operands intentionally swapped. Mask is last operand to intrinsic,
10542     // but second operand for node/intruction.
10543     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10544                        Op.getOperand(2), Op.getOperand(1));
10545
10546   case Intrinsic::x86_sse_sqrt_ps:
10547   case Intrinsic::x86_sse2_sqrt_pd:
10548   case Intrinsic::x86_avx_sqrt_ps_256:
10549   case Intrinsic::x86_avx_sqrt_pd_256:
10550     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10551
10552   // ptest and testp intrinsics. The intrinsic these come from are designed to
10553   // return an integer value, not just an instruction so lower it to the ptest
10554   // or testp pattern and a setcc for the result.
10555   case Intrinsic::x86_sse41_ptestz:
10556   case Intrinsic::x86_sse41_ptestc:
10557   case Intrinsic::x86_sse41_ptestnzc:
10558   case Intrinsic::x86_avx_ptestz_256:
10559   case Intrinsic::x86_avx_ptestc_256:
10560   case Intrinsic::x86_avx_ptestnzc_256:
10561   case Intrinsic::x86_avx_vtestz_ps:
10562   case Intrinsic::x86_avx_vtestc_ps:
10563   case Intrinsic::x86_avx_vtestnzc_ps:
10564   case Intrinsic::x86_avx_vtestz_pd:
10565   case Intrinsic::x86_avx_vtestc_pd:
10566   case Intrinsic::x86_avx_vtestnzc_pd:
10567   case Intrinsic::x86_avx_vtestz_ps_256:
10568   case Intrinsic::x86_avx_vtestc_ps_256:
10569   case Intrinsic::x86_avx_vtestnzc_ps_256:
10570   case Intrinsic::x86_avx_vtestz_pd_256:
10571   case Intrinsic::x86_avx_vtestc_pd_256:
10572   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10573     bool IsTestPacked = false;
10574     unsigned X86CC;
10575     switch (IntNo) {
10576     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10577     case Intrinsic::x86_avx_vtestz_ps:
10578     case Intrinsic::x86_avx_vtestz_pd:
10579     case Intrinsic::x86_avx_vtestz_ps_256:
10580     case Intrinsic::x86_avx_vtestz_pd_256:
10581       IsTestPacked = true; // Fallthrough
10582     case Intrinsic::x86_sse41_ptestz:
10583     case Intrinsic::x86_avx_ptestz_256:
10584       // ZF = 1
10585       X86CC = X86::COND_E;
10586       break;
10587     case Intrinsic::x86_avx_vtestc_ps:
10588     case Intrinsic::x86_avx_vtestc_pd:
10589     case Intrinsic::x86_avx_vtestc_ps_256:
10590     case Intrinsic::x86_avx_vtestc_pd_256:
10591       IsTestPacked = true; // Fallthrough
10592     case Intrinsic::x86_sse41_ptestc:
10593     case Intrinsic::x86_avx_ptestc_256:
10594       // CF = 1
10595       X86CC = X86::COND_B;
10596       break;
10597     case Intrinsic::x86_avx_vtestnzc_ps:
10598     case Intrinsic::x86_avx_vtestnzc_pd:
10599     case Intrinsic::x86_avx_vtestnzc_ps_256:
10600     case Intrinsic::x86_avx_vtestnzc_pd_256:
10601       IsTestPacked = true; // Fallthrough
10602     case Intrinsic::x86_sse41_ptestnzc:
10603     case Intrinsic::x86_avx_ptestnzc_256:
10604       // ZF and CF = 0
10605       X86CC = X86::COND_A;
10606       break;
10607     }
10608
10609     SDValue LHS = Op.getOperand(1);
10610     SDValue RHS = Op.getOperand(2);
10611     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10612     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10613     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10614     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10615     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10616   }
10617
10618   // SSE/AVX shift intrinsics
10619   case Intrinsic::x86_sse2_psll_w:
10620   case Intrinsic::x86_sse2_psll_d:
10621   case Intrinsic::x86_sse2_psll_q:
10622   case Intrinsic::x86_avx2_psll_w:
10623   case Intrinsic::x86_avx2_psll_d:
10624   case Intrinsic::x86_avx2_psll_q:
10625   case Intrinsic::x86_sse2_psrl_w:
10626   case Intrinsic::x86_sse2_psrl_d:
10627   case Intrinsic::x86_sse2_psrl_q:
10628   case Intrinsic::x86_avx2_psrl_w:
10629   case Intrinsic::x86_avx2_psrl_d:
10630   case Intrinsic::x86_avx2_psrl_q:
10631   case Intrinsic::x86_sse2_psra_w:
10632   case Intrinsic::x86_sse2_psra_d:
10633   case Intrinsic::x86_avx2_psra_w:
10634   case Intrinsic::x86_avx2_psra_d: {
10635     unsigned Opcode;
10636     switch (IntNo) {
10637     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10638     case Intrinsic::x86_sse2_psll_w:
10639     case Intrinsic::x86_sse2_psll_d:
10640     case Intrinsic::x86_sse2_psll_q:
10641     case Intrinsic::x86_avx2_psll_w:
10642     case Intrinsic::x86_avx2_psll_d:
10643     case Intrinsic::x86_avx2_psll_q:
10644       Opcode = X86ISD::VSHL;
10645       break;
10646     case Intrinsic::x86_sse2_psrl_w:
10647     case Intrinsic::x86_sse2_psrl_d:
10648     case Intrinsic::x86_sse2_psrl_q:
10649     case Intrinsic::x86_avx2_psrl_w:
10650     case Intrinsic::x86_avx2_psrl_d:
10651     case Intrinsic::x86_avx2_psrl_q:
10652       Opcode = X86ISD::VSRL;
10653       break;
10654     case Intrinsic::x86_sse2_psra_w:
10655     case Intrinsic::x86_sse2_psra_d:
10656     case Intrinsic::x86_avx2_psra_w:
10657     case Intrinsic::x86_avx2_psra_d:
10658       Opcode = X86ISD::VSRA;
10659       break;
10660     }
10661     return DAG.getNode(Opcode, dl, Op.getValueType(),
10662                        Op.getOperand(1), Op.getOperand(2));
10663   }
10664
10665   // SSE/AVX immediate shift intrinsics
10666   case Intrinsic::x86_sse2_pslli_w:
10667   case Intrinsic::x86_sse2_pslli_d:
10668   case Intrinsic::x86_sse2_pslli_q:
10669   case Intrinsic::x86_avx2_pslli_w:
10670   case Intrinsic::x86_avx2_pslli_d:
10671   case Intrinsic::x86_avx2_pslli_q:
10672   case Intrinsic::x86_sse2_psrli_w:
10673   case Intrinsic::x86_sse2_psrli_d:
10674   case Intrinsic::x86_sse2_psrli_q:
10675   case Intrinsic::x86_avx2_psrli_w:
10676   case Intrinsic::x86_avx2_psrli_d:
10677   case Intrinsic::x86_avx2_psrli_q:
10678   case Intrinsic::x86_sse2_psrai_w:
10679   case Intrinsic::x86_sse2_psrai_d:
10680   case Intrinsic::x86_avx2_psrai_w:
10681   case Intrinsic::x86_avx2_psrai_d: {
10682     unsigned Opcode;
10683     switch (IntNo) {
10684     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10685     case Intrinsic::x86_sse2_pslli_w:
10686     case Intrinsic::x86_sse2_pslli_d:
10687     case Intrinsic::x86_sse2_pslli_q:
10688     case Intrinsic::x86_avx2_pslli_w:
10689     case Intrinsic::x86_avx2_pslli_d:
10690     case Intrinsic::x86_avx2_pslli_q:
10691       Opcode = X86ISD::VSHLI;
10692       break;
10693     case Intrinsic::x86_sse2_psrli_w:
10694     case Intrinsic::x86_sse2_psrli_d:
10695     case Intrinsic::x86_sse2_psrli_q:
10696     case Intrinsic::x86_avx2_psrli_w:
10697     case Intrinsic::x86_avx2_psrli_d:
10698     case Intrinsic::x86_avx2_psrli_q:
10699       Opcode = X86ISD::VSRLI;
10700       break;
10701     case Intrinsic::x86_sse2_psrai_w:
10702     case Intrinsic::x86_sse2_psrai_d:
10703     case Intrinsic::x86_avx2_psrai_w:
10704     case Intrinsic::x86_avx2_psrai_d:
10705       Opcode = X86ISD::VSRAI;
10706       break;
10707     }
10708     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10709                                Op.getOperand(1), Op.getOperand(2), DAG);
10710   }
10711
10712   case Intrinsic::x86_sse42_pcmpistria128:
10713   case Intrinsic::x86_sse42_pcmpestria128:
10714   case Intrinsic::x86_sse42_pcmpistric128:
10715   case Intrinsic::x86_sse42_pcmpestric128:
10716   case Intrinsic::x86_sse42_pcmpistrio128:
10717   case Intrinsic::x86_sse42_pcmpestrio128:
10718   case Intrinsic::x86_sse42_pcmpistris128:
10719   case Intrinsic::x86_sse42_pcmpestris128:
10720   case Intrinsic::x86_sse42_pcmpistriz128:
10721   case Intrinsic::x86_sse42_pcmpestriz128: {
10722     unsigned Opcode;
10723     unsigned X86CC;
10724     switch (IntNo) {
10725     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10726     case Intrinsic::x86_sse42_pcmpistria128:
10727       Opcode = X86ISD::PCMPISTRI;
10728       X86CC = X86::COND_A;
10729       break;
10730     case Intrinsic::x86_sse42_pcmpestria128:
10731       Opcode = X86ISD::PCMPESTRI;
10732       X86CC = X86::COND_A;
10733       break;
10734     case Intrinsic::x86_sse42_pcmpistric128:
10735       Opcode = X86ISD::PCMPISTRI;
10736       X86CC = X86::COND_B;
10737       break;
10738     case Intrinsic::x86_sse42_pcmpestric128:
10739       Opcode = X86ISD::PCMPESTRI;
10740       X86CC = X86::COND_B;
10741       break;
10742     case Intrinsic::x86_sse42_pcmpistrio128:
10743       Opcode = X86ISD::PCMPISTRI;
10744       X86CC = X86::COND_O;
10745       break;
10746     case Intrinsic::x86_sse42_pcmpestrio128:
10747       Opcode = X86ISD::PCMPESTRI;
10748       X86CC = X86::COND_O;
10749       break;
10750     case Intrinsic::x86_sse42_pcmpistris128:
10751       Opcode = X86ISD::PCMPISTRI;
10752       X86CC = X86::COND_S;
10753       break;
10754     case Intrinsic::x86_sse42_pcmpestris128:
10755       Opcode = X86ISD::PCMPESTRI;
10756       X86CC = X86::COND_S;
10757       break;
10758     case Intrinsic::x86_sse42_pcmpistriz128:
10759       Opcode = X86ISD::PCMPISTRI;
10760       X86CC = X86::COND_E;
10761       break;
10762     case Intrinsic::x86_sse42_pcmpestriz128:
10763       Opcode = X86ISD::PCMPESTRI;
10764       X86CC = X86::COND_E;
10765       break;
10766     }
10767     SmallVector<SDValue, 5> NewOps;
10768     NewOps.append(Op->op_begin()+1, Op->op_end());
10769     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10770     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10771     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10772                                 DAG.getConstant(X86CC, MVT::i8),
10773                                 SDValue(PCMP.getNode(), 1));
10774     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10775   }
10776
10777   case Intrinsic::x86_sse42_pcmpistri128:
10778   case Intrinsic::x86_sse42_pcmpestri128: {
10779     unsigned Opcode;
10780     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10781       Opcode = X86ISD::PCMPISTRI;
10782     else
10783       Opcode = X86ISD::PCMPESTRI;
10784
10785     SmallVector<SDValue, 5> NewOps;
10786     NewOps.append(Op->op_begin()+1, Op->op_end());
10787     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10788     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10789   }
10790   case Intrinsic::x86_fma_vfmadd_ps:
10791   case Intrinsic::x86_fma_vfmadd_pd:
10792   case Intrinsic::x86_fma_vfmsub_ps:
10793   case Intrinsic::x86_fma_vfmsub_pd:
10794   case Intrinsic::x86_fma_vfnmadd_ps:
10795   case Intrinsic::x86_fma_vfnmadd_pd:
10796   case Intrinsic::x86_fma_vfnmsub_ps:
10797   case Intrinsic::x86_fma_vfnmsub_pd:
10798   case Intrinsic::x86_fma_vfmaddsub_ps:
10799   case Intrinsic::x86_fma_vfmaddsub_pd:
10800   case Intrinsic::x86_fma_vfmsubadd_ps:
10801   case Intrinsic::x86_fma_vfmsubadd_pd:
10802   case Intrinsic::x86_fma_vfmadd_ps_256:
10803   case Intrinsic::x86_fma_vfmadd_pd_256:
10804   case Intrinsic::x86_fma_vfmsub_ps_256:
10805   case Intrinsic::x86_fma_vfmsub_pd_256:
10806   case Intrinsic::x86_fma_vfnmadd_ps_256:
10807   case Intrinsic::x86_fma_vfnmadd_pd_256:
10808   case Intrinsic::x86_fma_vfnmsub_ps_256:
10809   case Intrinsic::x86_fma_vfnmsub_pd_256:
10810   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10811   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10812   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10813   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10814     unsigned Opc;
10815     switch (IntNo) {
10816     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10817     case Intrinsic::x86_fma_vfmadd_ps:
10818     case Intrinsic::x86_fma_vfmadd_pd:
10819     case Intrinsic::x86_fma_vfmadd_ps_256:
10820     case Intrinsic::x86_fma_vfmadd_pd_256:
10821       Opc = X86ISD::FMADD;
10822       break;
10823     case Intrinsic::x86_fma_vfmsub_ps:
10824     case Intrinsic::x86_fma_vfmsub_pd:
10825     case Intrinsic::x86_fma_vfmsub_ps_256:
10826     case Intrinsic::x86_fma_vfmsub_pd_256:
10827       Opc = X86ISD::FMSUB;
10828       break;
10829     case Intrinsic::x86_fma_vfnmadd_ps:
10830     case Intrinsic::x86_fma_vfnmadd_pd:
10831     case Intrinsic::x86_fma_vfnmadd_ps_256:
10832     case Intrinsic::x86_fma_vfnmadd_pd_256:
10833       Opc = X86ISD::FNMADD;
10834       break;
10835     case Intrinsic::x86_fma_vfnmsub_ps:
10836     case Intrinsic::x86_fma_vfnmsub_pd:
10837     case Intrinsic::x86_fma_vfnmsub_ps_256:
10838     case Intrinsic::x86_fma_vfnmsub_pd_256:
10839       Opc = X86ISD::FNMSUB;
10840       break;
10841     case Intrinsic::x86_fma_vfmaddsub_ps:
10842     case Intrinsic::x86_fma_vfmaddsub_pd:
10843     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10844     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10845       Opc = X86ISD::FMADDSUB;
10846       break;
10847     case Intrinsic::x86_fma_vfmsubadd_ps:
10848     case Intrinsic::x86_fma_vfmsubadd_pd:
10849     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10850     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10851       Opc = X86ISD::FMSUBADD;
10852       break;
10853     }
10854
10855     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10856                        Op.getOperand(2), Op.getOperand(3));
10857   }
10858   }
10859 }
10860
10861 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10862   DebugLoc dl = Op.getDebugLoc();
10863   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10864   switch (IntNo) {
10865   default: return SDValue();    // Don't custom lower most intrinsics.
10866
10867   // RDRAND intrinsics.
10868   case Intrinsic::x86_rdrand_16:
10869   case Intrinsic::x86_rdrand_32:
10870   case Intrinsic::x86_rdrand_64: {
10871     // Emit the node with the right value type.
10872     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10873     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10874
10875     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10876     // return the value from Rand, which is always 0, casted to i32.
10877     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10878                       DAG.getConstant(1, Op->getValueType(1)),
10879                       DAG.getConstant(X86::COND_B, MVT::i32),
10880                       SDValue(Result.getNode(), 1) };
10881     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10882                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10883                                   Ops, 4);
10884
10885     // Return { result, isValid, chain }.
10886     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10887                        SDValue(Result.getNode(), 2));
10888   }
10889   }
10890 }
10891
10892 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10893                                            SelectionDAG &DAG) const {
10894   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10895   MFI->setReturnAddressIsTaken(true);
10896
10897   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10898   DebugLoc dl = Op.getDebugLoc();
10899   EVT PtrVT = getPointerTy();
10900
10901   if (Depth > 0) {
10902     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10903     SDValue Offset =
10904       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10905     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10906                        DAG.getNode(ISD::ADD, dl, PtrVT,
10907                                    FrameAddr, Offset),
10908                        MachinePointerInfo(), false, false, false, 0);
10909   }
10910
10911   // Just load the return address.
10912   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10913   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10914                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10915 }
10916
10917 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10918   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10919   MFI->setFrameAddressIsTaken(true);
10920
10921   EVT VT = Op.getValueType();
10922   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10923   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10924   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10925   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10926   while (Depth--)
10927     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10928                             MachinePointerInfo(),
10929                             false, false, false, 0);
10930   return FrameAddr;
10931 }
10932
10933 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10934                                                      SelectionDAG &DAG) const {
10935   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10936 }
10937
10938 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10939   SDValue Chain     = Op.getOperand(0);
10940   SDValue Offset    = Op.getOperand(1);
10941   SDValue Handler   = Op.getOperand(2);
10942   DebugLoc dl       = Op.getDebugLoc();
10943
10944   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10945                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10946                                      getPointerTy());
10947   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10948
10949   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10950                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10951   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10952   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10953                        false, false, 0);
10954   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10955
10956   return DAG.getNode(X86ISD::EH_RETURN, dl,
10957                      MVT::Other,
10958                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10959 }
10960
10961 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10962                                                SelectionDAG &DAG) const {
10963   DebugLoc DL = Op.getDebugLoc();
10964   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10965                      DAG.getVTList(MVT::i32, MVT::Other),
10966                      Op.getOperand(0), Op.getOperand(1));
10967 }
10968
10969 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10970                                                 SelectionDAG &DAG) const {
10971   DebugLoc DL = Op.getDebugLoc();
10972   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10973                      Op.getOperand(0), Op.getOperand(1));
10974 }
10975
10976 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10977   return Op.getOperand(0);
10978 }
10979
10980 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10981                                                 SelectionDAG &DAG) const {
10982   SDValue Root = Op.getOperand(0);
10983   SDValue Trmp = Op.getOperand(1); // trampoline
10984   SDValue FPtr = Op.getOperand(2); // nested function
10985   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10986   DebugLoc dl  = Op.getDebugLoc();
10987
10988   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10989   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10990
10991   if (Subtarget->is64Bit()) {
10992     SDValue OutChains[6];
10993
10994     // Large code-model.
10995     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10996     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10997
10998     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10999     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11000
11001     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11002
11003     // Load the pointer to the nested function into R11.
11004     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11005     SDValue Addr = Trmp;
11006     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11007                                 Addr, MachinePointerInfo(TrmpAddr),
11008                                 false, false, 0);
11009
11010     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11011                        DAG.getConstant(2, MVT::i64));
11012     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11013                                 MachinePointerInfo(TrmpAddr, 2),
11014                                 false, false, 2);
11015
11016     // Load the 'nest' parameter value into R10.
11017     // R10 is specified in X86CallingConv.td
11018     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11019     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11020                        DAG.getConstant(10, MVT::i64));
11021     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11022                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11023                                 false, false, 0);
11024
11025     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11026                        DAG.getConstant(12, MVT::i64));
11027     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11028                                 MachinePointerInfo(TrmpAddr, 12),
11029                                 false, false, 2);
11030
11031     // Jump to the nested function.
11032     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11033     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11034                        DAG.getConstant(20, MVT::i64));
11035     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11036                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11037                                 false, false, 0);
11038
11039     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11040     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11041                        DAG.getConstant(22, MVT::i64));
11042     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11043                                 MachinePointerInfo(TrmpAddr, 22),
11044                                 false, false, 0);
11045
11046     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11047   } else {
11048     const Function *Func =
11049       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11050     CallingConv::ID CC = Func->getCallingConv();
11051     unsigned NestReg;
11052
11053     switch (CC) {
11054     default:
11055       llvm_unreachable("Unsupported calling convention");
11056     case CallingConv::C:
11057     case CallingConv::X86_StdCall: {
11058       // Pass 'nest' parameter in ECX.
11059       // Must be kept in sync with X86CallingConv.td
11060       NestReg = X86::ECX;
11061
11062       // Check that ECX wasn't needed by an 'inreg' parameter.
11063       FunctionType *FTy = Func->getFunctionType();
11064       const AttributeSet &Attrs = Func->getAttributes();
11065
11066       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11067         unsigned InRegCount = 0;
11068         unsigned Idx = 1;
11069
11070         for (FunctionType::param_iterator I = FTy->param_begin(),
11071              E = FTy->param_end(); I != E; ++I, ++Idx)
11072           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11073             // FIXME: should only count parameters that are lowered to integers.
11074             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11075
11076         if (InRegCount > 2) {
11077           report_fatal_error("Nest register in use - reduce number of inreg"
11078                              " parameters!");
11079         }
11080       }
11081       break;
11082     }
11083     case CallingConv::X86_FastCall:
11084     case CallingConv::X86_ThisCall:
11085     case CallingConv::Fast:
11086       // Pass 'nest' parameter in EAX.
11087       // Must be kept in sync with X86CallingConv.td
11088       NestReg = X86::EAX;
11089       break;
11090     }
11091
11092     SDValue OutChains[4];
11093     SDValue Addr, Disp;
11094
11095     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11096                        DAG.getConstant(10, MVT::i32));
11097     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11098
11099     // This is storing the opcode for MOV32ri.
11100     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11101     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11102     OutChains[0] = DAG.getStore(Root, dl,
11103                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11104                                 Trmp, MachinePointerInfo(TrmpAddr),
11105                                 false, false, 0);
11106
11107     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11108                        DAG.getConstant(1, MVT::i32));
11109     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11110                                 MachinePointerInfo(TrmpAddr, 1),
11111                                 false, false, 1);
11112
11113     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11114     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11115                        DAG.getConstant(5, MVT::i32));
11116     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11117                                 MachinePointerInfo(TrmpAddr, 5),
11118                                 false, false, 1);
11119
11120     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11121                        DAG.getConstant(6, MVT::i32));
11122     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11123                                 MachinePointerInfo(TrmpAddr, 6),
11124                                 false, false, 1);
11125
11126     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11127   }
11128 }
11129
11130 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11131                                             SelectionDAG &DAG) const {
11132   /*
11133    The rounding mode is in bits 11:10 of FPSR, and has the following
11134    settings:
11135      00 Round to nearest
11136      01 Round to -inf
11137      10 Round to +inf
11138      11 Round to 0
11139
11140   FLT_ROUNDS, on the other hand, expects the following:
11141     -1 Undefined
11142      0 Round to 0
11143      1 Round to nearest
11144      2 Round to +inf
11145      3 Round to -inf
11146
11147   To perform the conversion, we do:
11148     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11149   */
11150
11151   MachineFunction &MF = DAG.getMachineFunction();
11152   const TargetMachine &TM = MF.getTarget();
11153   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11154   unsigned StackAlignment = TFI.getStackAlignment();
11155   EVT VT = Op.getValueType();
11156   DebugLoc DL = Op.getDebugLoc();
11157
11158   // Save FP Control Word to stack slot
11159   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11160   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11161
11162   MachineMemOperand *MMO =
11163    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11164                            MachineMemOperand::MOStore, 2, 2);
11165
11166   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11167   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11168                                           DAG.getVTList(MVT::Other),
11169                                           Ops, 2, MVT::i16, MMO);
11170
11171   // Load FP Control Word from stack slot
11172   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11173                             MachinePointerInfo(), false, false, false, 0);
11174
11175   // Transform as necessary
11176   SDValue CWD1 =
11177     DAG.getNode(ISD::SRL, DL, MVT::i16,
11178                 DAG.getNode(ISD::AND, DL, MVT::i16,
11179                             CWD, DAG.getConstant(0x800, MVT::i16)),
11180                 DAG.getConstant(11, MVT::i8));
11181   SDValue CWD2 =
11182     DAG.getNode(ISD::SRL, DL, MVT::i16,
11183                 DAG.getNode(ISD::AND, DL, MVT::i16,
11184                             CWD, DAG.getConstant(0x400, MVT::i16)),
11185                 DAG.getConstant(9, MVT::i8));
11186
11187   SDValue RetVal =
11188     DAG.getNode(ISD::AND, DL, MVT::i16,
11189                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11190                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11191                             DAG.getConstant(1, MVT::i16)),
11192                 DAG.getConstant(3, MVT::i16));
11193
11194   return DAG.getNode((VT.getSizeInBits() < 16 ?
11195                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11196 }
11197
11198 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11199   EVT VT = Op.getValueType();
11200   EVT OpVT = VT;
11201   unsigned NumBits = VT.getSizeInBits();
11202   DebugLoc dl = Op.getDebugLoc();
11203
11204   Op = Op.getOperand(0);
11205   if (VT == MVT::i8) {
11206     // Zero extend to i32 since there is not an i8 bsr.
11207     OpVT = MVT::i32;
11208     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11209   }
11210
11211   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11212   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11213   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11214
11215   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11216   SDValue Ops[] = {
11217     Op,
11218     DAG.getConstant(NumBits+NumBits-1, OpVT),
11219     DAG.getConstant(X86::COND_E, MVT::i8),
11220     Op.getValue(1)
11221   };
11222   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11223
11224   // Finally xor with NumBits-1.
11225   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11226
11227   if (VT == MVT::i8)
11228     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11229   return Op;
11230 }
11231
11232 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11233   EVT VT = Op.getValueType();
11234   EVT OpVT = VT;
11235   unsigned NumBits = VT.getSizeInBits();
11236   DebugLoc dl = Op.getDebugLoc();
11237
11238   Op = Op.getOperand(0);
11239   if (VT == MVT::i8) {
11240     // Zero extend to i32 since there is not an i8 bsr.
11241     OpVT = MVT::i32;
11242     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11243   }
11244
11245   // Issue a bsr (scan bits in reverse).
11246   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11247   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11248
11249   // And xor with NumBits-1.
11250   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11251
11252   if (VT == MVT::i8)
11253     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11254   return Op;
11255 }
11256
11257 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11258   EVT VT = Op.getValueType();
11259   unsigned NumBits = VT.getSizeInBits();
11260   DebugLoc dl = Op.getDebugLoc();
11261   Op = Op.getOperand(0);
11262
11263   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11264   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11265   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11266
11267   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11268   SDValue Ops[] = {
11269     Op,
11270     DAG.getConstant(NumBits, VT),
11271     DAG.getConstant(X86::COND_E, MVT::i8),
11272     Op.getValue(1)
11273   };
11274   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11275 }
11276
11277 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11278 // ones, and then concatenate the result back.
11279 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11280   EVT VT = Op.getValueType();
11281
11282   assert(VT.is256BitVector() && VT.isInteger() &&
11283          "Unsupported value type for operation");
11284
11285   unsigned NumElems = VT.getVectorNumElements();
11286   DebugLoc dl = Op.getDebugLoc();
11287
11288   // Extract the LHS vectors
11289   SDValue LHS = Op.getOperand(0);
11290   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11291   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11292
11293   // Extract the RHS vectors
11294   SDValue RHS = Op.getOperand(1);
11295   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11296   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11297
11298   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11299   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11300
11301   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11302                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11303                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11304 }
11305
11306 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11307   assert(Op.getValueType().is256BitVector() &&
11308          Op.getValueType().isInteger() &&
11309          "Only handle AVX 256-bit vector integer operation");
11310   return Lower256IntArith(Op, DAG);
11311 }
11312
11313 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11314   assert(Op.getValueType().is256BitVector() &&
11315          Op.getValueType().isInteger() &&
11316          "Only handle AVX 256-bit vector integer operation");
11317   return Lower256IntArith(Op, DAG);
11318 }
11319
11320 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11321                         SelectionDAG &DAG) {
11322   DebugLoc dl = Op.getDebugLoc();
11323   EVT VT = Op.getValueType();
11324
11325   // Decompose 256-bit ops into smaller 128-bit ops.
11326   if (VT.is256BitVector() && !Subtarget->hasInt256())
11327     return Lower256IntArith(Op, DAG);
11328
11329   SDValue A = Op.getOperand(0);
11330   SDValue B = Op.getOperand(1);
11331
11332   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11333   if (VT == MVT::v4i32) {
11334     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11335            "Should not custom lower when pmuldq is available!");
11336
11337     // Extract the odd parts.
11338     const int UnpackMask[] = { 1, -1, 3, -1 };
11339     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11340     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11341
11342     // Multiply the even parts.
11343     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11344     // Now multiply odd parts.
11345     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11346
11347     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11348     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11349
11350     // Merge the two vectors back together with a shuffle. This expands into 2
11351     // shuffles.
11352     const int ShufMask[] = { 0, 4, 2, 6 };
11353     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11354   }
11355
11356   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11357          "Only know how to lower V2I64/V4I64 multiply");
11358
11359   //  Ahi = psrlqi(a, 32);
11360   //  Bhi = psrlqi(b, 32);
11361   //
11362   //  AloBlo = pmuludq(a, b);
11363   //  AloBhi = pmuludq(a, Bhi);
11364   //  AhiBlo = pmuludq(Ahi, b);
11365
11366   //  AloBhi = psllqi(AloBhi, 32);
11367   //  AhiBlo = psllqi(AhiBlo, 32);
11368   //  return AloBlo + AloBhi + AhiBlo;
11369
11370   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11371
11372   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11373   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11374
11375   // Bit cast to 32-bit vectors for MULUDQ
11376   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11377   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11378   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11379   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11380   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11381
11382   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11383   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11384   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11385
11386   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11387   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11388
11389   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11390   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11391 }
11392
11393 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11394   EVT VT = Op.getValueType();
11395   EVT EltTy = VT.getVectorElementType();
11396   unsigned NumElts = VT.getVectorNumElements();
11397   SDValue N0 = Op.getOperand(0);
11398   DebugLoc dl = Op.getDebugLoc();
11399
11400   // Lower sdiv X, pow2-const.
11401   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11402   if (!C)
11403     return SDValue();
11404
11405   APInt SplatValue, SplatUndef;
11406   unsigned MinSplatBits;
11407   bool HasAnyUndefs;
11408   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11409     return SDValue();
11410
11411   if ((SplatValue != 0) &&
11412       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11413     unsigned lg2 = SplatValue.countTrailingZeros();
11414     // Splat the sign bit.
11415     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11416     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11417     // Add (N0 < 0) ? abs2 - 1 : 0;
11418     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11419     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11420     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11421     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11422     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11423
11424     // If we're dividing by a positive value, we're done.  Otherwise, we must
11425     // negate the result.
11426     if (SplatValue.isNonNegative())
11427       return SRA;
11428
11429     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11430     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11431     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11432   }
11433   return SDValue();
11434 }
11435
11436 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11437
11438   EVT VT = Op.getValueType();
11439   DebugLoc dl = Op.getDebugLoc();
11440   SDValue R = Op.getOperand(0);
11441   SDValue Amt = Op.getOperand(1);
11442   LLVMContext *Context = DAG.getContext();
11443
11444   if (!Subtarget->hasSSE2())
11445     return SDValue();
11446
11447   // Optimize shl/srl/sra with constant shift amount.
11448   if (isSplatVector(Amt.getNode())) {
11449     SDValue SclrAmt = Amt->getOperand(0);
11450     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11451       uint64_t ShiftAmt = C->getZExtValue();
11452
11453       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11454           (Subtarget->hasInt256() &&
11455            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11456         if (Op.getOpcode() == ISD::SHL)
11457           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11458                              DAG.getConstant(ShiftAmt, MVT::i32));
11459         if (Op.getOpcode() == ISD::SRL)
11460           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11461                              DAG.getConstant(ShiftAmt, MVT::i32));
11462         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11463           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11464                              DAG.getConstant(ShiftAmt, MVT::i32));
11465       }
11466
11467       if (VT == MVT::v16i8) {
11468         if (Op.getOpcode() == ISD::SHL) {
11469           // Make a large shift.
11470           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11471                                     DAG.getConstant(ShiftAmt, MVT::i32));
11472           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11473           // Zero out the rightmost bits.
11474           SmallVector<SDValue, 16> V(16,
11475                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11476                                                      MVT::i8));
11477           return DAG.getNode(ISD::AND, dl, VT, SHL,
11478                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11479         }
11480         if (Op.getOpcode() == ISD::SRL) {
11481           // Make a large shift.
11482           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11483                                     DAG.getConstant(ShiftAmt, MVT::i32));
11484           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11485           // Zero out the leftmost bits.
11486           SmallVector<SDValue, 16> V(16,
11487                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11488                                                      MVT::i8));
11489           return DAG.getNode(ISD::AND, dl, VT, SRL,
11490                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11491         }
11492         if (Op.getOpcode() == ISD::SRA) {
11493           if (ShiftAmt == 7) {
11494             // R s>> 7  ===  R s< 0
11495             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11496             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11497           }
11498
11499           // R s>> a === ((R u>> a) ^ m) - m
11500           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11501           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11502                                                          MVT::i8));
11503           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11504           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11505           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11506           return Res;
11507         }
11508         llvm_unreachable("Unknown shift opcode.");
11509       }
11510
11511       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11512         if (Op.getOpcode() == ISD::SHL) {
11513           // Make a large shift.
11514           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11515                                     DAG.getConstant(ShiftAmt, MVT::i32));
11516           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11517           // Zero out the rightmost bits.
11518           SmallVector<SDValue, 32> V(32,
11519                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11520                                                      MVT::i8));
11521           return DAG.getNode(ISD::AND, dl, VT, SHL,
11522                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11523         }
11524         if (Op.getOpcode() == ISD::SRL) {
11525           // Make a large shift.
11526           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11527                                     DAG.getConstant(ShiftAmt, MVT::i32));
11528           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11529           // Zero out the leftmost bits.
11530           SmallVector<SDValue, 32> V(32,
11531                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11532                                                      MVT::i8));
11533           return DAG.getNode(ISD::AND, dl, VT, SRL,
11534                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11535         }
11536         if (Op.getOpcode() == ISD::SRA) {
11537           if (ShiftAmt == 7) {
11538             // R s>> 7  ===  R s< 0
11539             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11540             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11541           }
11542
11543           // R s>> a === ((R u>> a) ^ m) - m
11544           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11545           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11546                                                          MVT::i8));
11547           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11548           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11549           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11550           return Res;
11551         }
11552         llvm_unreachable("Unknown shift opcode.");
11553       }
11554     }
11555   }
11556
11557   // Lower SHL with variable shift amount.
11558   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11559     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11560                      DAG.getConstant(23, MVT::i32));
11561
11562     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11563     Constant *C = ConstantDataVector::get(*Context, CV);
11564     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11565     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11566                                  MachinePointerInfo::getConstantPool(),
11567                                  false, false, false, 16);
11568
11569     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11570     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11571     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11572     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11573   }
11574   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11575     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11576
11577     // a = a << 5;
11578     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11579                      DAG.getConstant(5, MVT::i32));
11580     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11581
11582     // Turn 'a' into a mask suitable for VSELECT
11583     SDValue VSelM = DAG.getConstant(0x80, VT);
11584     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11585     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11586
11587     SDValue CM1 = DAG.getConstant(0x0f, VT);
11588     SDValue CM2 = DAG.getConstant(0x3f, VT);
11589
11590     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11591     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11592     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11593                             DAG.getConstant(4, MVT::i32), DAG);
11594     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11595     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11596
11597     // a += a
11598     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11599     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11600     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11601
11602     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11603     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11604     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11605                             DAG.getConstant(2, MVT::i32), DAG);
11606     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11607     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11608
11609     // a += a
11610     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11611     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11612     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11613
11614     // return VSELECT(r, r+r, a);
11615     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11616                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11617     return R;
11618   }
11619
11620   // Decompose 256-bit shifts into smaller 128-bit shifts.
11621   if (VT.is256BitVector()) {
11622     unsigned NumElems = VT.getVectorNumElements();
11623     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11624     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11625
11626     // Extract the two vectors
11627     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11628     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11629
11630     // Recreate the shift amount vectors
11631     SDValue Amt1, Amt2;
11632     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11633       // Constant shift amount
11634       SmallVector<SDValue, 4> Amt1Csts;
11635       SmallVector<SDValue, 4> Amt2Csts;
11636       for (unsigned i = 0; i != NumElems/2; ++i)
11637         Amt1Csts.push_back(Amt->getOperand(i));
11638       for (unsigned i = NumElems/2; i != NumElems; ++i)
11639         Amt2Csts.push_back(Amt->getOperand(i));
11640
11641       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11642                                  &Amt1Csts[0], NumElems/2);
11643       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11644                                  &Amt2Csts[0], NumElems/2);
11645     } else {
11646       // Variable shift amount
11647       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11648       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11649     }
11650
11651     // Issue new vector shifts for the smaller types
11652     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11653     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11654
11655     // Concatenate the result back
11656     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11657   }
11658
11659   return SDValue();
11660 }
11661
11662 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11663   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11664   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11665   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11666   // has only one use.
11667   SDNode *N = Op.getNode();
11668   SDValue LHS = N->getOperand(0);
11669   SDValue RHS = N->getOperand(1);
11670   unsigned BaseOp = 0;
11671   unsigned Cond = 0;
11672   DebugLoc DL = Op.getDebugLoc();
11673   switch (Op.getOpcode()) {
11674   default: llvm_unreachable("Unknown ovf instruction!");
11675   case ISD::SADDO:
11676     // A subtract of one will be selected as a INC. Note that INC doesn't
11677     // set CF, so we can't do this for UADDO.
11678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11679       if (C->isOne()) {
11680         BaseOp = X86ISD::INC;
11681         Cond = X86::COND_O;
11682         break;
11683       }
11684     BaseOp = X86ISD::ADD;
11685     Cond = X86::COND_O;
11686     break;
11687   case ISD::UADDO:
11688     BaseOp = X86ISD::ADD;
11689     Cond = X86::COND_B;
11690     break;
11691   case ISD::SSUBO:
11692     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11693     // set CF, so we can't do this for USUBO.
11694     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11695       if (C->isOne()) {
11696         BaseOp = X86ISD::DEC;
11697         Cond = X86::COND_O;
11698         break;
11699       }
11700     BaseOp = X86ISD::SUB;
11701     Cond = X86::COND_O;
11702     break;
11703   case ISD::USUBO:
11704     BaseOp = X86ISD::SUB;
11705     Cond = X86::COND_B;
11706     break;
11707   case ISD::SMULO:
11708     BaseOp = X86ISD::SMUL;
11709     Cond = X86::COND_O;
11710     break;
11711   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11712     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11713                                  MVT::i32);
11714     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11715
11716     SDValue SetCC =
11717       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11718                   DAG.getConstant(X86::COND_O, MVT::i32),
11719                   SDValue(Sum.getNode(), 2));
11720
11721     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11722   }
11723   }
11724
11725   // Also sets EFLAGS.
11726   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11727   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11728
11729   SDValue SetCC =
11730     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11731                 DAG.getConstant(Cond, MVT::i32),
11732                 SDValue(Sum.getNode(), 1));
11733
11734   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11735 }
11736
11737 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11738                                                   SelectionDAG &DAG) const {
11739   DebugLoc dl = Op.getDebugLoc();
11740   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11741   EVT VT = Op.getValueType();
11742
11743   if (!Subtarget->hasSSE2() || !VT.isVector())
11744     return SDValue();
11745
11746   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11747                       ExtraVT.getScalarType().getSizeInBits();
11748   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11749
11750   switch (VT.getSimpleVT().SimpleTy) {
11751     default: return SDValue();
11752     case MVT::v8i32:
11753     case MVT::v16i16:
11754       if (!Subtarget->hasFp256())
11755         return SDValue();
11756       if (!Subtarget->hasInt256()) {
11757         // needs to be split
11758         unsigned NumElems = VT.getVectorNumElements();
11759
11760         // Extract the LHS vectors
11761         SDValue LHS = Op.getOperand(0);
11762         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11763         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11764
11765         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11766         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11767
11768         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11769         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11770         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11771                                    ExtraNumElems/2);
11772         SDValue Extra = DAG.getValueType(ExtraVT);
11773
11774         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11775         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11776
11777         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11778       }
11779       // fall through
11780     case MVT::v4i32:
11781     case MVT::v8i16: {
11782       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11783                                          Op.getOperand(0), ShAmt, DAG);
11784       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11785     }
11786   }
11787 }
11788
11789 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11790                               SelectionDAG &DAG) {
11791   DebugLoc dl = Op.getDebugLoc();
11792
11793   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11794   // There isn't any reason to disable it if the target processor supports it.
11795   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11796     SDValue Chain = Op.getOperand(0);
11797     SDValue Zero = DAG.getConstant(0, MVT::i32);
11798     SDValue Ops[] = {
11799       DAG.getRegister(X86::ESP, MVT::i32), // Base
11800       DAG.getTargetConstant(1, MVT::i8),   // Scale
11801       DAG.getRegister(0, MVT::i32),        // Index
11802       DAG.getTargetConstant(0, MVT::i32),  // Disp
11803       DAG.getRegister(0, MVT::i32),        // Segment.
11804       Zero,
11805       Chain
11806     };
11807     SDNode *Res =
11808       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11809                           array_lengthof(Ops));
11810     return SDValue(Res, 0);
11811   }
11812
11813   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11814   if (!isDev)
11815     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11816
11817   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11818   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11819   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11820   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11821
11822   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11823   if (!Op1 && !Op2 && !Op3 && Op4)
11824     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11825
11826   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11827   if (Op1 && !Op2 && !Op3 && !Op4)
11828     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11829
11830   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11831   //           (MFENCE)>;
11832   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11833 }
11834
11835 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11836                                  SelectionDAG &DAG) {
11837   DebugLoc dl = Op.getDebugLoc();
11838   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11839     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11840   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11841     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11842
11843   // The only fence that needs an instruction is a sequentially-consistent
11844   // cross-thread fence.
11845   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11846     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11847     // no-sse2). There isn't any reason to disable it if the target processor
11848     // supports it.
11849     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11850       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11851
11852     SDValue Chain = Op.getOperand(0);
11853     SDValue Zero = DAG.getConstant(0, MVT::i32);
11854     SDValue Ops[] = {
11855       DAG.getRegister(X86::ESP, MVT::i32), // Base
11856       DAG.getTargetConstant(1, MVT::i8),   // Scale
11857       DAG.getRegister(0, MVT::i32),        // Index
11858       DAG.getTargetConstant(0, MVT::i32),  // Disp
11859       DAG.getRegister(0, MVT::i32),        // Segment.
11860       Zero,
11861       Chain
11862     };
11863     SDNode *Res =
11864       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11865                          array_lengthof(Ops));
11866     return SDValue(Res, 0);
11867   }
11868
11869   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11870   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11871 }
11872
11873 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11874                              SelectionDAG &DAG) {
11875   EVT T = Op.getValueType();
11876   DebugLoc DL = Op.getDebugLoc();
11877   unsigned Reg = 0;
11878   unsigned size = 0;
11879   switch(T.getSimpleVT().SimpleTy) {
11880   default: llvm_unreachable("Invalid value type!");
11881   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11882   case MVT::i16: Reg = X86::AX;  size = 2; break;
11883   case MVT::i32: Reg = X86::EAX; size = 4; break;
11884   case MVT::i64:
11885     assert(Subtarget->is64Bit() && "Node not type legal!");
11886     Reg = X86::RAX; size = 8;
11887     break;
11888   }
11889   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11890                                     Op.getOperand(2), SDValue());
11891   SDValue Ops[] = { cpIn.getValue(0),
11892                     Op.getOperand(1),
11893                     Op.getOperand(3),
11894                     DAG.getTargetConstant(size, MVT::i8),
11895                     cpIn.getValue(1) };
11896   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11897   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11898   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11899                                            Ops, 5, T, MMO);
11900   SDValue cpOut =
11901     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11902   return cpOut;
11903 }
11904
11905 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11906                                      SelectionDAG &DAG) {
11907   assert(Subtarget->is64Bit() && "Result not type legalized?");
11908   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11909   SDValue TheChain = Op.getOperand(0);
11910   DebugLoc dl = Op.getDebugLoc();
11911   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11912   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11913   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11914                                    rax.getValue(2));
11915   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11916                             DAG.getConstant(32, MVT::i8));
11917   SDValue Ops[] = {
11918     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11919     rdx.getValue(1)
11920   };
11921   return DAG.getMergeValues(Ops, 2, dl);
11922 }
11923
11924 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11925   EVT SrcVT = Op.getOperand(0).getValueType();
11926   EVT DstVT = Op.getValueType();
11927   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11928          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11929   assert((DstVT == MVT::i64 ||
11930           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11931          "Unexpected custom BITCAST");
11932   // i64 <=> MMX conversions are Legal.
11933   if (SrcVT==MVT::i64 && DstVT.isVector())
11934     return Op;
11935   if (DstVT==MVT::i64 && SrcVT.isVector())
11936     return Op;
11937   // MMX <=> MMX conversions are Legal.
11938   if (SrcVT.isVector() && DstVT.isVector())
11939     return Op;
11940   // All other conversions need to be expanded.
11941   return SDValue();
11942 }
11943
11944 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11945   SDNode *Node = Op.getNode();
11946   DebugLoc dl = Node->getDebugLoc();
11947   EVT T = Node->getValueType(0);
11948   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11949                               DAG.getConstant(0, T), Node->getOperand(2));
11950   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11951                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11952                        Node->getOperand(0),
11953                        Node->getOperand(1), negOp,
11954                        cast<AtomicSDNode>(Node)->getSrcValue(),
11955                        cast<AtomicSDNode>(Node)->getAlignment(),
11956                        cast<AtomicSDNode>(Node)->getOrdering(),
11957                        cast<AtomicSDNode>(Node)->getSynchScope());
11958 }
11959
11960 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11961   SDNode *Node = Op.getNode();
11962   DebugLoc dl = Node->getDebugLoc();
11963   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11964
11965   // Convert seq_cst store -> xchg
11966   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11967   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11968   //        (The only way to get a 16-byte store is cmpxchg16b)
11969   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11970   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11971       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11972     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11973                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11974                                  Node->getOperand(0),
11975                                  Node->getOperand(1), Node->getOperand(2),
11976                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11977                                  cast<AtomicSDNode>(Node)->getOrdering(),
11978                                  cast<AtomicSDNode>(Node)->getSynchScope());
11979     return Swap.getValue(1);
11980   }
11981   // Other atomic stores have a simple pattern.
11982   return Op;
11983 }
11984
11985 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11986   EVT VT = Op.getNode()->getValueType(0);
11987
11988   // Let legalize expand this if it isn't a legal type yet.
11989   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11990     return SDValue();
11991
11992   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11993
11994   unsigned Opc;
11995   bool ExtraOp = false;
11996   switch (Op.getOpcode()) {
11997   default: llvm_unreachable("Invalid code");
11998   case ISD::ADDC: Opc = X86ISD::ADD; break;
11999   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12000   case ISD::SUBC: Opc = X86ISD::SUB; break;
12001   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12002   }
12003
12004   if (!ExtraOp)
12005     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12006                        Op.getOperand(1));
12007   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12008                      Op.getOperand(1), Op.getOperand(2));
12009 }
12010
12011 /// LowerOperation - Provide custom lowering hooks for some operations.
12012 ///
12013 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12014   switch (Op.getOpcode()) {
12015   default: llvm_unreachable("Should not custom lower this!");
12016   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12017   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12018   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12019   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12020   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12021   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12022   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12023   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12024   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12025   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12026   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12027   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12028   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12029   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12030   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12031   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12032   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12033   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12034   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12035   case ISD::SHL_PARTS:
12036   case ISD::SRA_PARTS:
12037   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12038   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12039   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12040   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12041   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12042   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12043   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12044   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12045   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12046   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12047   case ISD::FABS:               return LowerFABS(Op, DAG);
12048   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12049   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12050   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12051   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12052   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12053   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12054   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12055   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12056   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12057   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12058   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12059   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12060   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12061   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12062   case ISD::FRAME_TO_ARGS_OFFSET:
12063                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12064   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12065   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12066   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12067   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12068   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12069   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12070   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12071   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12072   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12073   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12074   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12075   case ISD::SRA:
12076   case ISD::SRL:
12077   case ISD::SHL:                return LowerShift(Op, DAG);
12078   case ISD::SADDO:
12079   case ISD::UADDO:
12080   case ISD::SSUBO:
12081   case ISD::USUBO:
12082   case ISD::SMULO:
12083   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12084   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12085   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12086   case ISD::ADDC:
12087   case ISD::ADDE:
12088   case ISD::SUBC:
12089   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12090   case ISD::ADD:                return LowerADD(Op, DAG);
12091   case ISD::SUB:                return LowerSUB(Op, DAG);
12092   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12093   }
12094 }
12095
12096 static void ReplaceATOMIC_LOAD(SDNode *Node,
12097                                   SmallVectorImpl<SDValue> &Results,
12098                                   SelectionDAG &DAG) {
12099   DebugLoc dl = Node->getDebugLoc();
12100   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12101
12102   // Convert wide load -> cmpxchg8b/cmpxchg16b
12103   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12104   //        (The only way to get a 16-byte load is cmpxchg16b)
12105   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12106   SDValue Zero = DAG.getConstant(0, VT);
12107   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12108                                Node->getOperand(0),
12109                                Node->getOperand(1), Zero, Zero,
12110                                cast<AtomicSDNode>(Node)->getMemOperand(),
12111                                cast<AtomicSDNode>(Node)->getOrdering(),
12112                                cast<AtomicSDNode>(Node)->getSynchScope());
12113   Results.push_back(Swap.getValue(0));
12114   Results.push_back(Swap.getValue(1));
12115 }
12116
12117 static void
12118 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12119                         SelectionDAG &DAG, unsigned NewOp) {
12120   DebugLoc dl = Node->getDebugLoc();
12121   assert (Node->getValueType(0) == MVT::i64 &&
12122           "Only know how to expand i64 atomics");
12123
12124   SDValue Chain = Node->getOperand(0);
12125   SDValue In1 = Node->getOperand(1);
12126   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12127                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12128   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12129                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12130   SDValue Ops[] = { Chain, In1, In2L, In2H };
12131   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12132   SDValue Result =
12133     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12134                             cast<MemSDNode>(Node)->getMemOperand());
12135   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12136   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12137   Results.push_back(Result.getValue(2));
12138 }
12139
12140 /// ReplaceNodeResults - Replace a node with an illegal result type
12141 /// with a new node built out of custom code.
12142 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12143                                            SmallVectorImpl<SDValue>&Results,
12144                                            SelectionDAG &DAG) const {
12145   DebugLoc dl = N->getDebugLoc();
12146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12147   switch (N->getOpcode()) {
12148   default:
12149     llvm_unreachable("Do not know how to custom type legalize this operation!");
12150   case ISD::SIGN_EXTEND_INREG:
12151   case ISD::ADDC:
12152   case ISD::ADDE:
12153   case ISD::SUBC:
12154   case ISD::SUBE:
12155     // We don't want to expand or promote these.
12156     return;
12157   case ISD::FP_TO_SINT:
12158   case ISD::FP_TO_UINT: {
12159     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12160
12161     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12162       return;
12163
12164     std::pair<SDValue,SDValue> Vals =
12165         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12166     SDValue FIST = Vals.first, StackSlot = Vals.second;
12167     if (FIST.getNode() != 0) {
12168       EVT VT = N->getValueType(0);
12169       // Return a load from the stack slot.
12170       if (StackSlot.getNode() != 0)
12171         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12172                                       MachinePointerInfo(),
12173                                       false, false, false, 0));
12174       else
12175         Results.push_back(FIST);
12176     }
12177     return;
12178   }
12179   case ISD::UINT_TO_FP: {
12180     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12181         N->getValueType(0) != MVT::v2f32)
12182       return;
12183     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12184                                  N->getOperand(0));
12185     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12186                                      MVT::f64);
12187     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12188     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12189                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12190     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12191     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12192     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12193     return;
12194   }
12195   case ISD::FP_ROUND: {
12196     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12197         return;
12198     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12199     Results.push_back(V);
12200     return;
12201   }
12202   case ISD::READCYCLECOUNTER: {
12203     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12204     SDValue TheChain = N->getOperand(0);
12205     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12206     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12207                                      rd.getValue(1));
12208     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12209                                      eax.getValue(2));
12210     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12211     SDValue Ops[] = { eax, edx };
12212     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12213     Results.push_back(edx.getValue(1));
12214     return;
12215   }
12216   case ISD::ATOMIC_CMP_SWAP: {
12217     EVT T = N->getValueType(0);
12218     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12219     bool Regs64bit = T == MVT::i128;
12220     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12221     SDValue cpInL, cpInH;
12222     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12223                         DAG.getConstant(0, HalfT));
12224     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12225                         DAG.getConstant(1, HalfT));
12226     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12227                              Regs64bit ? X86::RAX : X86::EAX,
12228                              cpInL, SDValue());
12229     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12230                              Regs64bit ? X86::RDX : X86::EDX,
12231                              cpInH, cpInL.getValue(1));
12232     SDValue swapInL, swapInH;
12233     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12234                           DAG.getConstant(0, HalfT));
12235     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12236                           DAG.getConstant(1, HalfT));
12237     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12238                                Regs64bit ? X86::RBX : X86::EBX,
12239                                swapInL, cpInH.getValue(1));
12240     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12241                                Regs64bit ? X86::RCX : X86::ECX,
12242                                swapInH, swapInL.getValue(1));
12243     SDValue Ops[] = { swapInH.getValue(0),
12244                       N->getOperand(1),
12245                       swapInH.getValue(1) };
12246     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12247     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12248     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12249                                   X86ISD::LCMPXCHG8_DAG;
12250     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12251                                              Ops, 3, T, MMO);
12252     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12253                                         Regs64bit ? X86::RAX : X86::EAX,
12254                                         HalfT, Result.getValue(1));
12255     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12256                                         Regs64bit ? X86::RDX : X86::EDX,
12257                                         HalfT, cpOutL.getValue(2));
12258     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12259     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12260     Results.push_back(cpOutH.getValue(1));
12261     return;
12262   }
12263   case ISD::ATOMIC_LOAD_ADD:
12264   case ISD::ATOMIC_LOAD_AND:
12265   case ISD::ATOMIC_LOAD_NAND:
12266   case ISD::ATOMIC_LOAD_OR:
12267   case ISD::ATOMIC_LOAD_SUB:
12268   case ISD::ATOMIC_LOAD_XOR:
12269   case ISD::ATOMIC_LOAD_MAX:
12270   case ISD::ATOMIC_LOAD_MIN:
12271   case ISD::ATOMIC_LOAD_UMAX:
12272   case ISD::ATOMIC_LOAD_UMIN:
12273   case ISD::ATOMIC_SWAP: {
12274     unsigned Opc;
12275     switch (N->getOpcode()) {
12276     default: llvm_unreachable("Unexpected opcode");
12277     case ISD::ATOMIC_LOAD_ADD:
12278       Opc = X86ISD::ATOMADD64_DAG;
12279       break;
12280     case ISD::ATOMIC_LOAD_AND:
12281       Opc = X86ISD::ATOMAND64_DAG;
12282       break;
12283     case ISD::ATOMIC_LOAD_NAND:
12284       Opc = X86ISD::ATOMNAND64_DAG;
12285       break;
12286     case ISD::ATOMIC_LOAD_OR:
12287       Opc = X86ISD::ATOMOR64_DAG;
12288       break;
12289     case ISD::ATOMIC_LOAD_SUB:
12290       Opc = X86ISD::ATOMSUB64_DAG;
12291       break;
12292     case ISD::ATOMIC_LOAD_XOR:
12293       Opc = X86ISD::ATOMXOR64_DAG;
12294       break;
12295     case ISD::ATOMIC_LOAD_MAX:
12296       Opc = X86ISD::ATOMMAX64_DAG;
12297       break;
12298     case ISD::ATOMIC_LOAD_MIN:
12299       Opc = X86ISD::ATOMMIN64_DAG;
12300       break;
12301     case ISD::ATOMIC_LOAD_UMAX:
12302       Opc = X86ISD::ATOMUMAX64_DAG;
12303       break;
12304     case ISD::ATOMIC_LOAD_UMIN:
12305       Opc = X86ISD::ATOMUMIN64_DAG;
12306       break;
12307     case ISD::ATOMIC_SWAP:
12308       Opc = X86ISD::ATOMSWAP64_DAG;
12309       break;
12310     }
12311     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12312     return;
12313   }
12314   case ISD::ATOMIC_LOAD:
12315     ReplaceATOMIC_LOAD(N, Results, DAG);
12316   }
12317 }
12318
12319 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12320   switch (Opcode) {
12321   default: return NULL;
12322   case X86ISD::BSF:                return "X86ISD::BSF";
12323   case X86ISD::BSR:                return "X86ISD::BSR";
12324   case X86ISD::SHLD:               return "X86ISD::SHLD";
12325   case X86ISD::SHRD:               return "X86ISD::SHRD";
12326   case X86ISD::FAND:               return "X86ISD::FAND";
12327   case X86ISD::FOR:                return "X86ISD::FOR";
12328   case X86ISD::FXOR:               return "X86ISD::FXOR";
12329   case X86ISD::FSRL:               return "X86ISD::FSRL";
12330   case X86ISD::FILD:               return "X86ISD::FILD";
12331   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12332   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12333   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12334   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12335   case X86ISD::FLD:                return "X86ISD::FLD";
12336   case X86ISD::FST:                return "X86ISD::FST";
12337   case X86ISD::CALL:               return "X86ISD::CALL";
12338   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12339   case X86ISD::BT:                 return "X86ISD::BT";
12340   case X86ISD::CMP:                return "X86ISD::CMP";
12341   case X86ISD::COMI:               return "X86ISD::COMI";
12342   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12343   case X86ISD::SETCC:              return "X86ISD::SETCC";
12344   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12345   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12346   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12347   case X86ISD::CMOV:               return "X86ISD::CMOV";
12348   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12349   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12350   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12351   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12352   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12353   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12354   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12355   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12356   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12357   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12358   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12359   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12360   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12361   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12362   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12363   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12364   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12365   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12366   case X86ISD::HADD:               return "X86ISD::HADD";
12367   case X86ISD::HSUB:               return "X86ISD::HSUB";
12368   case X86ISD::FHADD:              return "X86ISD::FHADD";
12369   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12370   case X86ISD::UMAX:               return "X86ISD::UMAX";
12371   case X86ISD::UMIN:               return "X86ISD::UMIN";
12372   case X86ISD::SMAX:               return "X86ISD::SMAX";
12373   case X86ISD::SMIN:               return "X86ISD::SMIN";
12374   case X86ISD::FMAX:               return "X86ISD::FMAX";
12375   case X86ISD::FMIN:               return "X86ISD::FMIN";
12376   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12377   case X86ISD::FMINC:              return "X86ISD::FMINC";
12378   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12379   case X86ISD::FRCP:               return "X86ISD::FRCP";
12380   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12381   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12382   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12383   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12384   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12385   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12386   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12387   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12388   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12389   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12390   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12391   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12392   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12393   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12394   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12395   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12396   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12397   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12398   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12399   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12400   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12401   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12402   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12403   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12404   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12405   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12406   case X86ISD::VSHL:               return "X86ISD::VSHL";
12407   case X86ISD::VSRL:               return "X86ISD::VSRL";
12408   case X86ISD::VSRA:               return "X86ISD::VSRA";
12409   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12410   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12411   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12412   case X86ISD::CMPP:               return "X86ISD::CMPP";
12413   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12414   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12415   case X86ISD::ADD:                return "X86ISD::ADD";
12416   case X86ISD::SUB:                return "X86ISD::SUB";
12417   case X86ISD::ADC:                return "X86ISD::ADC";
12418   case X86ISD::SBB:                return "X86ISD::SBB";
12419   case X86ISD::SMUL:               return "X86ISD::SMUL";
12420   case X86ISD::UMUL:               return "X86ISD::UMUL";
12421   case X86ISD::INC:                return "X86ISD::INC";
12422   case X86ISD::DEC:                return "X86ISD::DEC";
12423   case X86ISD::OR:                 return "X86ISD::OR";
12424   case X86ISD::XOR:                return "X86ISD::XOR";
12425   case X86ISD::AND:                return "X86ISD::AND";
12426   case X86ISD::BLSI:               return "X86ISD::BLSI";
12427   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12428   case X86ISD::BLSR:               return "X86ISD::BLSR";
12429   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12430   case X86ISD::PTEST:              return "X86ISD::PTEST";
12431   case X86ISD::TESTP:              return "X86ISD::TESTP";
12432   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12433   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12434   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12435   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12436   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12437   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12438   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12439   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12440   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12441   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12442   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12443   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12444   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12445   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12446   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12447   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12448   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12449   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12450   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12451   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12452   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12453   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12454   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12455   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12456   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12457   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12458   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12459   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12460   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12461   case X86ISD::SAHF:               return "X86ISD::SAHF";
12462   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12463   case X86ISD::FMADD:              return "X86ISD::FMADD";
12464   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12465   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12466   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12467   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12468   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12469   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12470   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12471   }
12472 }
12473
12474 // isLegalAddressingMode - Return true if the addressing mode represented
12475 // by AM is legal for this target, for a load/store of the specified type.
12476 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12477                                               Type *Ty) const {
12478   // X86 supports extremely general addressing modes.
12479   CodeModel::Model M = getTargetMachine().getCodeModel();
12480   Reloc::Model R = getTargetMachine().getRelocationModel();
12481
12482   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12483   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12484     return false;
12485
12486   if (AM.BaseGV) {
12487     unsigned GVFlags =
12488       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12489
12490     // If a reference to this global requires an extra load, we can't fold it.
12491     if (isGlobalStubReference(GVFlags))
12492       return false;
12493
12494     // If BaseGV requires a register for the PIC base, we cannot also have a
12495     // BaseReg specified.
12496     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12497       return false;
12498
12499     // If lower 4G is not available, then we must use rip-relative addressing.
12500     if ((M != CodeModel::Small || R != Reloc::Static) &&
12501         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12502       return false;
12503   }
12504
12505   switch (AM.Scale) {
12506   case 0:
12507   case 1:
12508   case 2:
12509   case 4:
12510   case 8:
12511     // These scales always work.
12512     break;
12513   case 3:
12514   case 5:
12515   case 9:
12516     // These scales are formed with basereg+scalereg.  Only accept if there is
12517     // no basereg yet.
12518     if (AM.HasBaseReg)
12519       return false;
12520     break;
12521   default:  // Other stuff never works.
12522     return false;
12523   }
12524
12525   return true;
12526 }
12527
12528 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12529   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12530     return false;
12531   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12532   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12533   return NumBits1 > NumBits2;
12534 }
12535
12536 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12537   return isInt<32>(Imm);
12538 }
12539
12540 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12541   // Can also use sub to handle negated immediates.
12542   return isInt<32>(Imm);
12543 }
12544
12545 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12546   if (!VT1.isInteger() || !VT2.isInteger())
12547     return false;
12548   unsigned NumBits1 = VT1.getSizeInBits();
12549   unsigned NumBits2 = VT2.getSizeInBits();
12550   return NumBits1 > NumBits2;
12551 }
12552
12553 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12554   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12555   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12556 }
12557
12558 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12559   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12560   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12561 }
12562
12563 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12564   EVT VT1 = Val.getValueType();
12565   if (isZExtFree(VT1, VT2))
12566     return true;
12567
12568   if (Val.getOpcode() != ISD::LOAD)
12569     return false;
12570
12571   if (!VT1.isSimple() || !VT1.isInteger() ||
12572       !VT2.isSimple() || !VT2.isInteger())
12573     return false;
12574
12575   switch (VT1.getSimpleVT().SimpleTy) {
12576   default: break;
12577   case MVT::i8:
12578   case MVT::i16:
12579   case MVT::i32:
12580     // X86 has 8, 16, and 32-bit zero-extending loads.
12581     return true;
12582   }
12583
12584   return false;
12585 }
12586
12587 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12588   // i16 instructions are longer (0x66 prefix) and potentially slower.
12589   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12590 }
12591
12592 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12593 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12594 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12595 /// are assumed to be legal.
12596 bool
12597 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12598                                       EVT VT) const {
12599   // Very little shuffling can be done for 64-bit vectors right now.
12600   if (VT.getSizeInBits() == 64)
12601     return false;
12602
12603   // FIXME: pshufb, blends, shifts.
12604   return (VT.getVectorNumElements() == 2 ||
12605           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12606           isMOVLMask(M, VT) ||
12607           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12608           isPSHUFDMask(M, VT) ||
12609           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12610           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12611           isPALIGNRMask(M, VT, Subtarget) ||
12612           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12613           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12614           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12615           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12616 }
12617
12618 bool
12619 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12620                                           EVT VT) const {
12621   unsigned NumElts = VT.getVectorNumElements();
12622   // FIXME: This collection of masks seems suspect.
12623   if (NumElts == 2)
12624     return true;
12625   if (NumElts == 4 && VT.is128BitVector()) {
12626     return (isMOVLMask(Mask, VT)  ||
12627             isCommutedMOVLMask(Mask, VT, true) ||
12628             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12629             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12630   }
12631   return false;
12632 }
12633
12634 //===----------------------------------------------------------------------===//
12635 //                           X86 Scheduler Hooks
12636 //===----------------------------------------------------------------------===//
12637
12638 /// Utility function to emit xbegin specifying the start of an RTM region.
12639 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12640                                      const TargetInstrInfo *TII) {
12641   DebugLoc DL = MI->getDebugLoc();
12642
12643   const BasicBlock *BB = MBB->getBasicBlock();
12644   MachineFunction::iterator I = MBB;
12645   ++I;
12646
12647   // For the v = xbegin(), we generate
12648   //
12649   // thisMBB:
12650   //  xbegin sinkMBB
12651   //
12652   // mainMBB:
12653   //  eax = -1
12654   //
12655   // sinkMBB:
12656   //  v = eax
12657
12658   MachineBasicBlock *thisMBB = MBB;
12659   MachineFunction *MF = MBB->getParent();
12660   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12661   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12662   MF->insert(I, mainMBB);
12663   MF->insert(I, sinkMBB);
12664
12665   // Transfer the remainder of BB and its successor edges to sinkMBB.
12666   sinkMBB->splice(sinkMBB->begin(), MBB,
12667                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12668   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12669
12670   // thisMBB:
12671   //  xbegin sinkMBB
12672   //  # fallthrough to mainMBB
12673   //  # abortion to sinkMBB
12674   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12675   thisMBB->addSuccessor(mainMBB);
12676   thisMBB->addSuccessor(sinkMBB);
12677
12678   // mainMBB:
12679   //  EAX = -1
12680   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12681   mainMBB->addSuccessor(sinkMBB);
12682
12683   // sinkMBB:
12684   // EAX is live into the sinkMBB
12685   sinkMBB->addLiveIn(X86::EAX);
12686   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12687           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12688     .addReg(X86::EAX);
12689
12690   MI->eraseFromParent();
12691   return sinkMBB;
12692 }
12693
12694 // Get CMPXCHG opcode for the specified data type.
12695 static unsigned getCmpXChgOpcode(EVT VT) {
12696   switch (VT.getSimpleVT().SimpleTy) {
12697   case MVT::i8:  return X86::LCMPXCHG8;
12698   case MVT::i16: return X86::LCMPXCHG16;
12699   case MVT::i32: return X86::LCMPXCHG32;
12700   case MVT::i64: return X86::LCMPXCHG64;
12701   default:
12702     break;
12703   }
12704   llvm_unreachable("Invalid operand size!");
12705 }
12706
12707 // Get LOAD opcode for the specified data type.
12708 static unsigned getLoadOpcode(EVT VT) {
12709   switch (VT.getSimpleVT().SimpleTy) {
12710   case MVT::i8:  return X86::MOV8rm;
12711   case MVT::i16: return X86::MOV16rm;
12712   case MVT::i32: return X86::MOV32rm;
12713   case MVT::i64: return X86::MOV64rm;
12714   default:
12715     break;
12716   }
12717   llvm_unreachable("Invalid operand size!");
12718 }
12719
12720 // Get opcode of the non-atomic one from the specified atomic instruction.
12721 static unsigned getNonAtomicOpcode(unsigned Opc) {
12722   switch (Opc) {
12723   case X86::ATOMAND8:  return X86::AND8rr;
12724   case X86::ATOMAND16: return X86::AND16rr;
12725   case X86::ATOMAND32: return X86::AND32rr;
12726   case X86::ATOMAND64: return X86::AND64rr;
12727   case X86::ATOMOR8:   return X86::OR8rr;
12728   case X86::ATOMOR16:  return X86::OR16rr;
12729   case X86::ATOMOR32:  return X86::OR32rr;
12730   case X86::ATOMOR64:  return X86::OR64rr;
12731   case X86::ATOMXOR8:  return X86::XOR8rr;
12732   case X86::ATOMXOR16: return X86::XOR16rr;
12733   case X86::ATOMXOR32: return X86::XOR32rr;
12734   case X86::ATOMXOR64: return X86::XOR64rr;
12735   }
12736   llvm_unreachable("Unhandled atomic-load-op opcode!");
12737 }
12738
12739 // Get opcode of the non-atomic one from the specified atomic instruction with
12740 // extra opcode.
12741 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12742                                                unsigned &ExtraOpc) {
12743   switch (Opc) {
12744   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12745   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12746   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12747   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12748   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12749   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12750   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12751   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12752   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12753   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12754   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12755   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12756   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12757   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12758   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12759   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12760   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12761   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12762   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12763   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12764   }
12765   llvm_unreachable("Unhandled atomic-load-op opcode!");
12766 }
12767
12768 // Get opcode of the non-atomic one from the specified atomic instruction for
12769 // 64-bit data type on 32-bit target.
12770 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12771   switch (Opc) {
12772   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12773   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12774   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12775   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12776   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12777   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12778   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12779   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12780   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12781   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12782   }
12783   llvm_unreachable("Unhandled atomic-load-op opcode!");
12784 }
12785
12786 // Get opcode of the non-atomic one from the specified atomic instruction for
12787 // 64-bit data type on 32-bit target with extra opcode.
12788 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12789                                                    unsigned &HiOpc,
12790                                                    unsigned &ExtraOpc) {
12791   switch (Opc) {
12792   case X86::ATOMNAND6432:
12793     ExtraOpc = X86::NOT32r;
12794     HiOpc = X86::AND32rr;
12795     return X86::AND32rr;
12796   }
12797   llvm_unreachable("Unhandled atomic-load-op opcode!");
12798 }
12799
12800 // Get pseudo CMOV opcode from the specified data type.
12801 static unsigned getPseudoCMOVOpc(EVT VT) {
12802   switch (VT.getSimpleVT().SimpleTy) {
12803   case MVT::i8:  return X86::CMOV_GR8;
12804   case MVT::i16: return X86::CMOV_GR16;
12805   case MVT::i32: return X86::CMOV_GR32;
12806   default:
12807     break;
12808   }
12809   llvm_unreachable("Unknown CMOV opcode!");
12810 }
12811
12812 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12813 // They will be translated into a spin-loop or compare-exchange loop from
12814 //
12815 //    ...
12816 //    dst = atomic-fetch-op MI.addr, MI.val
12817 //    ...
12818 //
12819 // to
12820 //
12821 //    ...
12822 //    EAX = LOAD MI.addr
12823 // loop:
12824 //    t1 = OP MI.val, EAX
12825 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12826 //    JNE loop
12827 // sink:
12828 //    dst = EAX
12829 //    ...
12830 MachineBasicBlock *
12831 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12832                                        MachineBasicBlock *MBB) const {
12833   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12834   DebugLoc DL = MI->getDebugLoc();
12835
12836   MachineFunction *MF = MBB->getParent();
12837   MachineRegisterInfo &MRI = MF->getRegInfo();
12838
12839   const BasicBlock *BB = MBB->getBasicBlock();
12840   MachineFunction::iterator I = MBB;
12841   ++I;
12842
12843   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12844          "Unexpected number of operands");
12845
12846   assert(MI->hasOneMemOperand() &&
12847          "Expected atomic-load-op to have one memoperand");
12848
12849   // Memory Reference
12850   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12851   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12852
12853   unsigned DstReg, SrcReg;
12854   unsigned MemOpndSlot;
12855
12856   unsigned CurOp = 0;
12857
12858   DstReg = MI->getOperand(CurOp++).getReg();
12859   MemOpndSlot = CurOp;
12860   CurOp += X86::AddrNumOperands;
12861   SrcReg = MI->getOperand(CurOp++).getReg();
12862
12863   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12864   MVT::SimpleValueType VT = *RC->vt_begin();
12865   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12866
12867   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12868   unsigned LOADOpc = getLoadOpcode(VT);
12869
12870   // For the atomic load-arith operator, we generate
12871   //
12872   //  thisMBB:
12873   //    EAX = LOAD [MI.addr]
12874   //  mainMBB:
12875   //    t1 = OP MI.val, EAX
12876   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12877   //    JNE mainMBB
12878   //  sinkMBB:
12879
12880   MachineBasicBlock *thisMBB = MBB;
12881   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12882   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12883   MF->insert(I, mainMBB);
12884   MF->insert(I, sinkMBB);
12885
12886   MachineInstrBuilder MIB;
12887
12888   // Transfer the remainder of BB and its successor edges to sinkMBB.
12889   sinkMBB->splice(sinkMBB->begin(), MBB,
12890                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12891   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12892
12893   // thisMBB:
12894   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12895   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12896     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12897   MIB.setMemRefs(MMOBegin, MMOEnd);
12898
12899   thisMBB->addSuccessor(mainMBB);
12900
12901   // mainMBB:
12902   MachineBasicBlock *origMainMBB = mainMBB;
12903   mainMBB->addLiveIn(AccPhyReg);
12904
12905   // Copy AccPhyReg as it is used more than once.
12906   unsigned AccReg = MRI.createVirtualRegister(RC);
12907   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12908     .addReg(AccPhyReg);
12909
12910   unsigned t1 = MRI.createVirtualRegister(RC);
12911   unsigned Opc = MI->getOpcode();
12912   switch (Opc) {
12913   default:
12914     llvm_unreachable("Unhandled atomic-load-op opcode!");
12915   case X86::ATOMAND8:
12916   case X86::ATOMAND16:
12917   case X86::ATOMAND32:
12918   case X86::ATOMAND64:
12919   case X86::ATOMOR8:
12920   case X86::ATOMOR16:
12921   case X86::ATOMOR32:
12922   case X86::ATOMOR64:
12923   case X86::ATOMXOR8:
12924   case X86::ATOMXOR16:
12925   case X86::ATOMXOR32:
12926   case X86::ATOMXOR64: {
12927     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12928     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12929       .addReg(AccReg);
12930     break;
12931   }
12932   case X86::ATOMNAND8:
12933   case X86::ATOMNAND16:
12934   case X86::ATOMNAND32:
12935   case X86::ATOMNAND64: {
12936     unsigned t2 = MRI.createVirtualRegister(RC);
12937     unsigned NOTOpc;
12938     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12939     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12940       .addReg(AccReg);
12941     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12942     break;
12943   }
12944   case X86::ATOMMAX8:
12945   case X86::ATOMMAX16:
12946   case X86::ATOMMAX32:
12947   case X86::ATOMMAX64:
12948   case X86::ATOMMIN8:
12949   case X86::ATOMMIN16:
12950   case X86::ATOMMIN32:
12951   case X86::ATOMMIN64:
12952   case X86::ATOMUMAX8:
12953   case X86::ATOMUMAX16:
12954   case X86::ATOMUMAX32:
12955   case X86::ATOMUMAX64:
12956   case X86::ATOMUMIN8:
12957   case X86::ATOMUMIN16:
12958   case X86::ATOMUMIN32:
12959   case X86::ATOMUMIN64: {
12960     unsigned CMPOpc;
12961     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12962
12963     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12964       .addReg(SrcReg)
12965       .addReg(AccReg);
12966
12967     if (Subtarget->hasCMov()) {
12968       if (VT != MVT::i8) {
12969         // Native support
12970         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12971           .addReg(SrcReg)
12972           .addReg(AccReg);
12973       } else {
12974         // Promote i8 to i32 to use CMOV32
12975         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12976         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12977         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12978         unsigned t2 = MRI.createVirtualRegister(RC32);
12979
12980         unsigned Undef = MRI.createVirtualRegister(RC32);
12981         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12982
12983         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12984           .addReg(Undef)
12985           .addReg(SrcReg)
12986           .addImm(X86::sub_8bit);
12987         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12988           .addReg(Undef)
12989           .addReg(AccReg)
12990           .addImm(X86::sub_8bit);
12991
12992         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12993           .addReg(SrcReg32)
12994           .addReg(AccReg32);
12995
12996         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12997           .addReg(t2, 0, X86::sub_8bit);
12998       }
12999     } else {
13000       // Use pseudo select and lower them.
13001       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13002              "Invalid atomic-load-op transformation!");
13003       unsigned SelOpc = getPseudoCMOVOpc(VT);
13004       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13005       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13006       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13007               .addReg(SrcReg).addReg(AccReg)
13008               .addImm(CC);
13009       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13010     }
13011     break;
13012   }
13013   }
13014
13015   // Copy AccPhyReg back from virtual register.
13016   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13017     .addReg(AccReg);
13018
13019   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13020   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13021     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13022   MIB.addReg(t1);
13023   MIB.setMemRefs(MMOBegin, MMOEnd);
13024
13025   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13026
13027   mainMBB->addSuccessor(origMainMBB);
13028   mainMBB->addSuccessor(sinkMBB);
13029
13030   // sinkMBB:
13031   sinkMBB->addLiveIn(AccPhyReg);
13032
13033   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13034           TII->get(TargetOpcode::COPY), DstReg)
13035     .addReg(AccPhyReg);
13036
13037   MI->eraseFromParent();
13038   return sinkMBB;
13039 }
13040
13041 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13042 // instructions. They will be translated into a spin-loop or compare-exchange
13043 // loop from
13044 //
13045 //    ...
13046 //    dst = atomic-fetch-op MI.addr, MI.val
13047 //    ...
13048 //
13049 // to
13050 //
13051 //    ...
13052 //    EAX = LOAD [MI.addr + 0]
13053 //    EDX = LOAD [MI.addr + 4]
13054 // loop:
13055 //    EBX = OP MI.val.lo, EAX
13056 //    ECX = OP MI.val.hi, EDX
13057 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13058 //    JNE loop
13059 // sink:
13060 //    dst = EDX:EAX
13061 //    ...
13062 MachineBasicBlock *
13063 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13064                                            MachineBasicBlock *MBB) const {
13065   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13066   DebugLoc DL = MI->getDebugLoc();
13067
13068   MachineFunction *MF = MBB->getParent();
13069   MachineRegisterInfo &MRI = MF->getRegInfo();
13070
13071   const BasicBlock *BB = MBB->getBasicBlock();
13072   MachineFunction::iterator I = MBB;
13073   ++I;
13074
13075   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13076          "Unexpected number of operands");
13077
13078   assert(MI->hasOneMemOperand() &&
13079          "Expected atomic-load-op32 to have one memoperand");
13080
13081   // Memory Reference
13082   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13083   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13084
13085   unsigned DstLoReg, DstHiReg;
13086   unsigned SrcLoReg, SrcHiReg;
13087   unsigned MemOpndSlot;
13088
13089   unsigned CurOp = 0;
13090
13091   DstLoReg = MI->getOperand(CurOp++).getReg();
13092   DstHiReg = MI->getOperand(CurOp++).getReg();
13093   MemOpndSlot = CurOp;
13094   CurOp += X86::AddrNumOperands;
13095   SrcLoReg = MI->getOperand(CurOp++).getReg();
13096   SrcHiReg = MI->getOperand(CurOp++).getReg();
13097
13098   const TargetRegisterClass *RC = &X86::GR32RegClass;
13099   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13100
13101   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13102   unsigned LOADOpc = X86::MOV32rm;
13103
13104   // For the atomic load-arith operator, we generate
13105   //
13106   //  thisMBB:
13107   //    EAX = LOAD [MI.addr + 0]
13108   //    EDX = LOAD [MI.addr + 4]
13109   //  mainMBB:
13110   //    EBX = OP MI.vallo, EAX
13111   //    ECX = OP MI.valhi, EDX
13112   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13113   //    JNE mainMBB
13114   //  sinkMBB:
13115
13116   MachineBasicBlock *thisMBB = MBB;
13117   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13118   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13119   MF->insert(I, mainMBB);
13120   MF->insert(I, sinkMBB);
13121
13122   MachineInstrBuilder MIB;
13123
13124   // Transfer the remainder of BB and its successor edges to sinkMBB.
13125   sinkMBB->splice(sinkMBB->begin(), MBB,
13126                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13127   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13128
13129   // thisMBB:
13130   // Lo
13131   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13132   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13133     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13134   MIB.setMemRefs(MMOBegin, MMOEnd);
13135   // Hi
13136   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13137   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13138     if (i == X86::AddrDisp)
13139       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13140     else
13141       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13142   }
13143   MIB.setMemRefs(MMOBegin, MMOEnd);
13144
13145   thisMBB->addSuccessor(mainMBB);
13146
13147   // mainMBB:
13148   MachineBasicBlock *origMainMBB = mainMBB;
13149   mainMBB->addLiveIn(X86::EAX);
13150   mainMBB->addLiveIn(X86::EDX);
13151
13152   // Copy EDX:EAX as they are used more than once.
13153   unsigned LoReg = MRI.createVirtualRegister(RC);
13154   unsigned HiReg = MRI.createVirtualRegister(RC);
13155   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13156   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13157
13158   unsigned t1L = MRI.createVirtualRegister(RC);
13159   unsigned t1H = MRI.createVirtualRegister(RC);
13160
13161   unsigned Opc = MI->getOpcode();
13162   switch (Opc) {
13163   default:
13164     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13165   case X86::ATOMAND6432:
13166   case X86::ATOMOR6432:
13167   case X86::ATOMXOR6432:
13168   case X86::ATOMADD6432:
13169   case X86::ATOMSUB6432: {
13170     unsigned HiOpc;
13171     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13172     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13173     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13174     break;
13175   }
13176   case X86::ATOMNAND6432: {
13177     unsigned HiOpc, NOTOpc;
13178     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13179     unsigned t2L = MRI.createVirtualRegister(RC);
13180     unsigned t2H = MRI.createVirtualRegister(RC);
13181     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13182     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13183     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13184     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13185     break;
13186   }
13187   case X86::ATOMMAX6432:
13188   case X86::ATOMMIN6432:
13189   case X86::ATOMUMAX6432:
13190   case X86::ATOMUMIN6432: {
13191     unsigned HiOpc;
13192     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13193     unsigned cL = MRI.createVirtualRegister(RC8);
13194     unsigned cH = MRI.createVirtualRegister(RC8);
13195     unsigned cL32 = MRI.createVirtualRegister(RC);
13196     unsigned cH32 = MRI.createVirtualRegister(RC);
13197     unsigned cc = MRI.createVirtualRegister(RC);
13198     // cl := cmp src_lo, lo
13199     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13200       .addReg(SrcLoReg).addReg(LoReg);
13201     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13202     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13203     // ch := cmp src_hi, hi
13204     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13205       .addReg(SrcHiReg).addReg(HiReg);
13206     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13207     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13208     // cc := if (src_hi == hi) ? cl : ch;
13209     if (Subtarget->hasCMov()) {
13210       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13211         .addReg(cH32).addReg(cL32);
13212     } else {
13213       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13214               .addReg(cH32).addReg(cL32)
13215               .addImm(X86::COND_E);
13216       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13217     }
13218     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13219     if (Subtarget->hasCMov()) {
13220       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13221         .addReg(SrcLoReg).addReg(LoReg);
13222       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13223         .addReg(SrcHiReg).addReg(HiReg);
13224     } else {
13225       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13226               .addReg(SrcLoReg).addReg(LoReg)
13227               .addImm(X86::COND_NE);
13228       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13229       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13230               .addReg(SrcHiReg).addReg(HiReg)
13231               .addImm(X86::COND_NE);
13232       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13233     }
13234     break;
13235   }
13236   case X86::ATOMSWAP6432: {
13237     unsigned HiOpc;
13238     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13239     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13240     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13241     break;
13242   }
13243   }
13244
13245   // Copy EDX:EAX back from HiReg:LoReg
13246   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13247   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13248   // Copy ECX:EBX from t1H:t1L
13249   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13250   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13251
13252   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13253   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13254     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13255   MIB.setMemRefs(MMOBegin, MMOEnd);
13256
13257   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13258
13259   mainMBB->addSuccessor(origMainMBB);
13260   mainMBB->addSuccessor(sinkMBB);
13261
13262   // sinkMBB:
13263   sinkMBB->addLiveIn(X86::EAX);
13264   sinkMBB->addLiveIn(X86::EDX);
13265
13266   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13267           TII->get(TargetOpcode::COPY), DstLoReg)
13268     .addReg(X86::EAX);
13269   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13270           TII->get(TargetOpcode::COPY), DstHiReg)
13271     .addReg(X86::EDX);
13272
13273   MI->eraseFromParent();
13274   return sinkMBB;
13275 }
13276
13277 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13278 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13279 // in the .td file.
13280 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13281                                        const TargetInstrInfo *TII) {
13282   unsigned Opc;
13283   switch (MI->getOpcode()) {
13284   default: llvm_unreachable("illegal opcode!");
13285   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13286   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13287   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13288   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13289   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13290   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13291   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13292   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13293   }
13294
13295   DebugLoc dl = MI->getDebugLoc();
13296   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13297
13298   unsigned NumArgs = MI->getNumOperands();
13299   for (unsigned i = 1; i < NumArgs; ++i) {
13300     MachineOperand &Op = MI->getOperand(i);
13301     if (!(Op.isReg() && Op.isImplicit()))
13302       MIB.addOperand(Op);
13303   }
13304   if (MI->hasOneMemOperand())
13305     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13306
13307   BuildMI(*BB, MI, dl,
13308     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13309     .addReg(X86::XMM0);
13310
13311   MI->eraseFromParent();
13312   return BB;
13313 }
13314
13315 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13316 // defs in an instruction pattern
13317 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13318                                        const TargetInstrInfo *TII) {
13319   unsigned Opc;
13320   switch (MI->getOpcode()) {
13321   default: llvm_unreachable("illegal opcode!");
13322   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13323   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13324   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13325   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13326   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13327   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13328   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13329   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13330   }
13331
13332   DebugLoc dl = MI->getDebugLoc();
13333   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13334
13335   unsigned NumArgs = MI->getNumOperands(); // remove the results
13336   for (unsigned i = 1; i < NumArgs; ++i) {
13337     MachineOperand &Op = MI->getOperand(i);
13338     if (!(Op.isReg() && Op.isImplicit()))
13339       MIB.addOperand(Op);
13340   }
13341   if (MI->hasOneMemOperand())
13342     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13343
13344   BuildMI(*BB, MI, dl,
13345     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13346     .addReg(X86::ECX);
13347
13348   MI->eraseFromParent();
13349   return BB;
13350 }
13351
13352 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13353                                        const TargetInstrInfo *TII,
13354                                        const X86Subtarget* Subtarget) {
13355   DebugLoc dl = MI->getDebugLoc();
13356
13357   // Address into RAX/EAX, other two args into ECX, EDX.
13358   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13359   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13360   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13361   for (int i = 0; i < X86::AddrNumOperands; ++i)
13362     MIB.addOperand(MI->getOperand(i));
13363
13364   unsigned ValOps = X86::AddrNumOperands;
13365   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13366     .addReg(MI->getOperand(ValOps).getReg());
13367   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13368     .addReg(MI->getOperand(ValOps+1).getReg());
13369
13370   // The instruction doesn't actually take any operands though.
13371   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13372
13373   MI->eraseFromParent(); // The pseudo is gone now.
13374   return BB;
13375 }
13376
13377 MachineBasicBlock *
13378 X86TargetLowering::EmitVAARG64WithCustomInserter(
13379                    MachineInstr *MI,
13380                    MachineBasicBlock *MBB) const {
13381   // Emit va_arg instruction on X86-64.
13382
13383   // Operands to this pseudo-instruction:
13384   // 0  ) Output        : destination address (reg)
13385   // 1-5) Input         : va_list address (addr, i64mem)
13386   // 6  ) ArgSize       : Size (in bytes) of vararg type
13387   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13388   // 8  ) Align         : Alignment of type
13389   // 9  ) EFLAGS (implicit-def)
13390
13391   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13392   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13393
13394   unsigned DestReg = MI->getOperand(0).getReg();
13395   MachineOperand &Base = MI->getOperand(1);
13396   MachineOperand &Scale = MI->getOperand(2);
13397   MachineOperand &Index = MI->getOperand(3);
13398   MachineOperand &Disp = MI->getOperand(4);
13399   MachineOperand &Segment = MI->getOperand(5);
13400   unsigned ArgSize = MI->getOperand(6).getImm();
13401   unsigned ArgMode = MI->getOperand(7).getImm();
13402   unsigned Align = MI->getOperand(8).getImm();
13403
13404   // Memory Reference
13405   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13406   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13407   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13408
13409   // Machine Information
13410   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13411   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13412   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13413   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13414   DebugLoc DL = MI->getDebugLoc();
13415
13416   // struct va_list {
13417   //   i32   gp_offset
13418   //   i32   fp_offset
13419   //   i64   overflow_area (address)
13420   //   i64   reg_save_area (address)
13421   // }
13422   // sizeof(va_list) = 24
13423   // alignment(va_list) = 8
13424
13425   unsigned TotalNumIntRegs = 6;
13426   unsigned TotalNumXMMRegs = 8;
13427   bool UseGPOffset = (ArgMode == 1);
13428   bool UseFPOffset = (ArgMode == 2);
13429   unsigned MaxOffset = TotalNumIntRegs * 8 +
13430                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13431
13432   /* Align ArgSize to a multiple of 8 */
13433   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13434   bool NeedsAlign = (Align > 8);
13435
13436   MachineBasicBlock *thisMBB = MBB;
13437   MachineBasicBlock *overflowMBB;
13438   MachineBasicBlock *offsetMBB;
13439   MachineBasicBlock *endMBB;
13440
13441   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13442   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13443   unsigned OffsetReg = 0;
13444
13445   if (!UseGPOffset && !UseFPOffset) {
13446     // If we only pull from the overflow region, we don't create a branch.
13447     // We don't need to alter control flow.
13448     OffsetDestReg = 0; // unused
13449     OverflowDestReg = DestReg;
13450
13451     offsetMBB = NULL;
13452     overflowMBB = thisMBB;
13453     endMBB = thisMBB;
13454   } else {
13455     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13456     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13457     // If not, pull from overflow_area. (branch to overflowMBB)
13458     //
13459     //       thisMBB
13460     //         |     .
13461     //         |        .
13462     //     offsetMBB   overflowMBB
13463     //         |        .
13464     //         |     .
13465     //        endMBB
13466
13467     // Registers for the PHI in endMBB
13468     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13469     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13470
13471     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13472     MachineFunction *MF = MBB->getParent();
13473     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13474     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13475     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13476
13477     MachineFunction::iterator MBBIter = MBB;
13478     ++MBBIter;
13479
13480     // Insert the new basic blocks
13481     MF->insert(MBBIter, offsetMBB);
13482     MF->insert(MBBIter, overflowMBB);
13483     MF->insert(MBBIter, endMBB);
13484
13485     // Transfer the remainder of MBB and its successor edges to endMBB.
13486     endMBB->splice(endMBB->begin(), thisMBB,
13487                     llvm::next(MachineBasicBlock::iterator(MI)),
13488                     thisMBB->end());
13489     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13490
13491     // Make offsetMBB and overflowMBB successors of thisMBB
13492     thisMBB->addSuccessor(offsetMBB);
13493     thisMBB->addSuccessor(overflowMBB);
13494
13495     // endMBB is a successor of both offsetMBB and overflowMBB
13496     offsetMBB->addSuccessor(endMBB);
13497     overflowMBB->addSuccessor(endMBB);
13498
13499     // Load the offset value into a register
13500     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13501     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13502       .addOperand(Base)
13503       .addOperand(Scale)
13504       .addOperand(Index)
13505       .addDisp(Disp, UseFPOffset ? 4 : 0)
13506       .addOperand(Segment)
13507       .setMemRefs(MMOBegin, MMOEnd);
13508
13509     // Check if there is enough room left to pull this argument.
13510     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13511       .addReg(OffsetReg)
13512       .addImm(MaxOffset + 8 - ArgSizeA8);
13513
13514     // Branch to "overflowMBB" if offset >= max
13515     // Fall through to "offsetMBB" otherwise
13516     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13517       .addMBB(overflowMBB);
13518   }
13519
13520   // In offsetMBB, emit code to use the reg_save_area.
13521   if (offsetMBB) {
13522     assert(OffsetReg != 0);
13523
13524     // Read the reg_save_area address.
13525     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13526     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13527       .addOperand(Base)
13528       .addOperand(Scale)
13529       .addOperand(Index)
13530       .addDisp(Disp, 16)
13531       .addOperand(Segment)
13532       .setMemRefs(MMOBegin, MMOEnd);
13533
13534     // Zero-extend the offset
13535     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13536       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13537         .addImm(0)
13538         .addReg(OffsetReg)
13539         .addImm(X86::sub_32bit);
13540
13541     // Add the offset to the reg_save_area to get the final address.
13542     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13543       .addReg(OffsetReg64)
13544       .addReg(RegSaveReg);
13545
13546     // Compute the offset for the next argument
13547     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13548     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13549       .addReg(OffsetReg)
13550       .addImm(UseFPOffset ? 16 : 8);
13551
13552     // Store it back into the va_list.
13553     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13554       .addOperand(Base)
13555       .addOperand(Scale)
13556       .addOperand(Index)
13557       .addDisp(Disp, UseFPOffset ? 4 : 0)
13558       .addOperand(Segment)
13559       .addReg(NextOffsetReg)
13560       .setMemRefs(MMOBegin, MMOEnd);
13561
13562     // Jump to endMBB
13563     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13564       .addMBB(endMBB);
13565   }
13566
13567   //
13568   // Emit code to use overflow area
13569   //
13570
13571   // Load the overflow_area address into a register.
13572   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13573   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13574     .addOperand(Base)
13575     .addOperand(Scale)
13576     .addOperand(Index)
13577     .addDisp(Disp, 8)
13578     .addOperand(Segment)
13579     .setMemRefs(MMOBegin, MMOEnd);
13580
13581   // If we need to align it, do so. Otherwise, just copy the address
13582   // to OverflowDestReg.
13583   if (NeedsAlign) {
13584     // Align the overflow address
13585     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13586     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13587
13588     // aligned_addr = (addr + (align-1)) & ~(align-1)
13589     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13590       .addReg(OverflowAddrReg)
13591       .addImm(Align-1);
13592
13593     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13594       .addReg(TmpReg)
13595       .addImm(~(uint64_t)(Align-1));
13596   } else {
13597     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13598       .addReg(OverflowAddrReg);
13599   }
13600
13601   // Compute the next overflow address after this argument.
13602   // (the overflow address should be kept 8-byte aligned)
13603   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13604   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13605     .addReg(OverflowDestReg)
13606     .addImm(ArgSizeA8);
13607
13608   // Store the new overflow address.
13609   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13610     .addOperand(Base)
13611     .addOperand(Scale)
13612     .addOperand(Index)
13613     .addDisp(Disp, 8)
13614     .addOperand(Segment)
13615     .addReg(NextAddrReg)
13616     .setMemRefs(MMOBegin, MMOEnd);
13617
13618   // If we branched, emit the PHI to the front of endMBB.
13619   if (offsetMBB) {
13620     BuildMI(*endMBB, endMBB->begin(), DL,
13621             TII->get(X86::PHI), DestReg)
13622       .addReg(OffsetDestReg).addMBB(offsetMBB)
13623       .addReg(OverflowDestReg).addMBB(overflowMBB);
13624   }
13625
13626   // Erase the pseudo instruction
13627   MI->eraseFromParent();
13628
13629   return endMBB;
13630 }
13631
13632 MachineBasicBlock *
13633 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13634                                                  MachineInstr *MI,
13635                                                  MachineBasicBlock *MBB) const {
13636   // Emit code to save XMM registers to the stack. The ABI says that the
13637   // number of registers to save is given in %al, so it's theoretically
13638   // possible to do an indirect jump trick to avoid saving all of them,
13639   // however this code takes a simpler approach and just executes all
13640   // of the stores if %al is non-zero. It's less code, and it's probably
13641   // easier on the hardware branch predictor, and stores aren't all that
13642   // expensive anyway.
13643
13644   // Create the new basic blocks. One block contains all the XMM stores,
13645   // and one block is the final destination regardless of whether any
13646   // stores were performed.
13647   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13648   MachineFunction *F = MBB->getParent();
13649   MachineFunction::iterator MBBIter = MBB;
13650   ++MBBIter;
13651   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13652   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13653   F->insert(MBBIter, XMMSaveMBB);
13654   F->insert(MBBIter, EndMBB);
13655
13656   // Transfer the remainder of MBB and its successor edges to EndMBB.
13657   EndMBB->splice(EndMBB->begin(), MBB,
13658                  llvm::next(MachineBasicBlock::iterator(MI)),
13659                  MBB->end());
13660   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13661
13662   // The original block will now fall through to the XMM save block.
13663   MBB->addSuccessor(XMMSaveMBB);
13664   // The XMMSaveMBB will fall through to the end block.
13665   XMMSaveMBB->addSuccessor(EndMBB);
13666
13667   // Now add the instructions.
13668   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13669   DebugLoc DL = MI->getDebugLoc();
13670
13671   unsigned CountReg = MI->getOperand(0).getReg();
13672   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13673   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13674
13675   if (!Subtarget->isTargetWin64()) {
13676     // If %al is 0, branch around the XMM save block.
13677     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13678     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13679     MBB->addSuccessor(EndMBB);
13680   }
13681
13682   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13683   // In the XMM save block, save all the XMM argument registers.
13684   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13685     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13686     MachineMemOperand *MMO =
13687       F->getMachineMemOperand(
13688           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13689         MachineMemOperand::MOStore,
13690         /*Size=*/16, /*Align=*/16);
13691     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13692       .addFrameIndex(RegSaveFrameIndex)
13693       .addImm(/*Scale=*/1)
13694       .addReg(/*IndexReg=*/0)
13695       .addImm(/*Disp=*/Offset)
13696       .addReg(/*Segment=*/0)
13697       .addReg(MI->getOperand(i).getReg())
13698       .addMemOperand(MMO);
13699   }
13700
13701   MI->eraseFromParent();   // The pseudo instruction is gone now.
13702
13703   return EndMBB;
13704 }
13705
13706 // The EFLAGS operand of SelectItr might be missing a kill marker
13707 // because there were multiple uses of EFLAGS, and ISel didn't know
13708 // which to mark. Figure out whether SelectItr should have had a
13709 // kill marker, and set it if it should. Returns the correct kill
13710 // marker value.
13711 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13712                                      MachineBasicBlock* BB,
13713                                      const TargetRegisterInfo* TRI) {
13714   // Scan forward through BB for a use/def of EFLAGS.
13715   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13716   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13717     const MachineInstr& mi = *miI;
13718     if (mi.readsRegister(X86::EFLAGS))
13719       return false;
13720     if (mi.definesRegister(X86::EFLAGS))
13721       break; // Should have kill-flag - update below.
13722   }
13723
13724   // If we hit the end of the block, check whether EFLAGS is live into a
13725   // successor.
13726   if (miI == BB->end()) {
13727     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13728                                           sEnd = BB->succ_end();
13729          sItr != sEnd; ++sItr) {
13730       MachineBasicBlock* succ = *sItr;
13731       if (succ->isLiveIn(X86::EFLAGS))
13732         return false;
13733     }
13734   }
13735
13736   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13737   // out. SelectMI should have a kill flag on EFLAGS.
13738   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13739   return true;
13740 }
13741
13742 MachineBasicBlock *
13743 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13744                                      MachineBasicBlock *BB) const {
13745   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13746   DebugLoc DL = MI->getDebugLoc();
13747
13748   // To "insert" a SELECT_CC instruction, we actually have to insert the
13749   // diamond control-flow pattern.  The incoming instruction knows the
13750   // destination vreg to set, the condition code register to branch on, the
13751   // true/false values to select between, and a branch opcode to use.
13752   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13753   MachineFunction::iterator It = BB;
13754   ++It;
13755
13756   //  thisMBB:
13757   //  ...
13758   //   TrueVal = ...
13759   //   cmpTY ccX, r1, r2
13760   //   bCC copy1MBB
13761   //   fallthrough --> copy0MBB
13762   MachineBasicBlock *thisMBB = BB;
13763   MachineFunction *F = BB->getParent();
13764   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13765   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13766   F->insert(It, copy0MBB);
13767   F->insert(It, sinkMBB);
13768
13769   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13770   // live into the sink and copy blocks.
13771   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13772   if (!MI->killsRegister(X86::EFLAGS) &&
13773       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13774     copy0MBB->addLiveIn(X86::EFLAGS);
13775     sinkMBB->addLiveIn(X86::EFLAGS);
13776   }
13777
13778   // Transfer the remainder of BB and its successor edges to sinkMBB.
13779   sinkMBB->splice(sinkMBB->begin(), BB,
13780                   llvm::next(MachineBasicBlock::iterator(MI)),
13781                   BB->end());
13782   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13783
13784   // Add the true and fallthrough blocks as its successors.
13785   BB->addSuccessor(copy0MBB);
13786   BB->addSuccessor(sinkMBB);
13787
13788   // Create the conditional branch instruction.
13789   unsigned Opc =
13790     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13791   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13792
13793   //  copy0MBB:
13794   //   %FalseValue = ...
13795   //   # fallthrough to sinkMBB
13796   copy0MBB->addSuccessor(sinkMBB);
13797
13798   //  sinkMBB:
13799   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13800   //  ...
13801   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13802           TII->get(X86::PHI), MI->getOperand(0).getReg())
13803     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13804     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13805
13806   MI->eraseFromParent();   // The pseudo instruction is gone now.
13807   return sinkMBB;
13808 }
13809
13810 MachineBasicBlock *
13811 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13812                                         bool Is64Bit) const {
13813   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13814   DebugLoc DL = MI->getDebugLoc();
13815   MachineFunction *MF = BB->getParent();
13816   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13817
13818   assert(getTargetMachine().Options.EnableSegmentedStacks);
13819
13820   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13821   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13822
13823   // BB:
13824   //  ... [Till the alloca]
13825   // If stacklet is not large enough, jump to mallocMBB
13826   //
13827   // bumpMBB:
13828   //  Allocate by subtracting from RSP
13829   //  Jump to continueMBB
13830   //
13831   // mallocMBB:
13832   //  Allocate by call to runtime
13833   //
13834   // continueMBB:
13835   //  ...
13836   //  [rest of original BB]
13837   //
13838
13839   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13840   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13841   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13842
13843   MachineRegisterInfo &MRI = MF->getRegInfo();
13844   const TargetRegisterClass *AddrRegClass =
13845     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13846
13847   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13848     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13849     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13850     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13851     sizeVReg = MI->getOperand(1).getReg(),
13852     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13853
13854   MachineFunction::iterator MBBIter = BB;
13855   ++MBBIter;
13856
13857   MF->insert(MBBIter, bumpMBB);
13858   MF->insert(MBBIter, mallocMBB);
13859   MF->insert(MBBIter, continueMBB);
13860
13861   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13862                       (MachineBasicBlock::iterator(MI)), BB->end());
13863   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13864
13865   // Add code to the main basic block to check if the stack limit has been hit,
13866   // and if so, jump to mallocMBB otherwise to bumpMBB.
13867   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13868   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13869     .addReg(tmpSPVReg).addReg(sizeVReg);
13870   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13871     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13872     .addReg(SPLimitVReg);
13873   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13874
13875   // bumpMBB simply decreases the stack pointer, since we know the current
13876   // stacklet has enough space.
13877   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13878     .addReg(SPLimitVReg);
13879   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13880     .addReg(SPLimitVReg);
13881   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13882
13883   // Calls into a routine in libgcc to allocate more space from the heap.
13884   const uint32_t *RegMask =
13885     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13886   if (Is64Bit) {
13887     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13888       .addReg(sizeVReg);
13889     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13890       .addExternalSymbol("__morestack_allocate_stack_space")
13891       .addRegMask(RegMask)
13892       .addReg(X86::RDI, RegState::Implicit)
13893       .addReg(X86::RAX, RegState::ImplicitDefine);
13894   } else {
13895     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13896       .addImm(12);
13897     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13898     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13899       .addExternalSymbol("__morestack_allocate_stack_space")
13900       .addRegMask(RegMask)
13901       .addReg(X86::EAX, RegState::ImplicitDefine);
13902   }
13903
13904   if (!Is64Bit)
13905     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13906       .addImm(16);
13907
13908   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13909     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13910   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13911
13912   // Set up the CFG correctly.
13913   BB->addSuccessor(bumpMBB);
13914   BB->addSuccessor(mallocMBB);
13915   mallocMBB->addSuccessor(continueMBB);
13916   bumpMBB->addSuccessor(continueMBB);
13917
13918   // Take care of the PHI nodes.
13919   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13920           MI->getOperand(0).getReg())
13921     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13922     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13923
13924   // Delete the original pseudo instruction.
13925   MI->eraseFromParent();
13926
13927   // And we're done.
13928   return continueMBB;
13929 }
13930
13931 MachineBasicBlock *
13932 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13933                                           MachineBasicBlock *BB) const {
13934   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13935   DebugLoc DL = MI->getDebugLoc();
13936
13937   assert(!Subtarget->isTargetEnvMacho());
13938
13939   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13940   // non-trivial part is impdef of ESP.
13941
13942   if (Subtarget->isTargetWin64()) {
13943     if (Subtarget->isTargetCygMing()) {
13944       // ___chkstk(Mingw64):
13945       // Clobbers R10, R11, RAX and EFLAGS.
13946       // Updates RSP.
13947       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13948         .addExternalSymbol("___chkstk")
13949         .addReg(X86::RAX, RegState::Implicit)
13950         .addReg(X86::RSP, RegState::Implicit)
13951         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13952         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13953         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13954     } else {
13955       // __chkstk(MSVCRT): does not update stack pointer.
13956       // Clobbers R10, R11 and EFLAGS.
13957       // FIXME: RAX(allocated size) might be reused and not killed.
13958       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13959         .addExternalSymbol("__chkstk")
13960         .addReg(X86::RAX, RegState::Implicit)
13961         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13962       // RAX has the offset to subtracted from RSP.
13963       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13964         .addReg(X86::RSP)
13965         .addReg(X86::RAX);
13966     }
13967   } else {
13968     const char *StackProbeSymbol =
13969       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13970
13971     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13972       .addExternalSymbol(StackProbeSymbol)
13973       .addReg(X86::EAX, RegState::Implicit)
13974       .addReg(X86::ESP, RegState::Implicit)
13975       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13976       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13977       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13978   }
13979
13980   MI->eraseFromParent();   // The pseudo instruction is gone now.
13981   return BB;
13982 }
13983
13984 MachineBasicBlock *
13985 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13986                                       MachineBasicBlock *BB) const {
13987   // This is pretty easy.  We're taking the value that we received from
13988   // our load from the relocation, sticking it in either RDI (x86-64)
13989   // or EAX and doing an indirect call.  The return value will then
13990   // be in the normal return register.
13991   const X86InstrInfo *TII
13992     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13993   DebugLoc DL = MI->getDebugLoc();
13994   MachineFunction *F = BB->getParent();
13995
13996   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13997   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13998
13999   // Get a register mask for the lowered call.
14000   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14001   // proper register mask.
14002   const uint32_t *RegMask =
14003     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14004   if (Subtarget->is64Bit()) {
14005     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14006                                       TII->get(X86::MOV64rm), X86::RDI)
14007     .addReg(X86::RIP)
14008     .addImm(0).addReg(0)
14009     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14010                       MI->getOperand(3).getTargetFlags())
14011     .addReg(0);
14012     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14013     addDirectMem(MIB, X86::RDI);
14014     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14015   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14016     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14017                                       TII->get(X86::MOV32rm), X86::EAX)
14018     .addReg(0)
14019     .addImm(0).addReg(0)
14020     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14021                       MI->getOperand(3).getTargetFlags())
14022     .addReg(0);
14023     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14024     addDirectMem(MIB, X86::EAX);
14025     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14026   } else {
14027     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14028                                       TII->get(X86::MOV32rm), X86::EAX)
14029     .addReg(TII->getGlobalBaseReg(F))
14030     .addImm(0).addReg(0)
14031     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14032                       MI->getOperand(3).getTargetFlags())
14033     .addReg(0);
14034     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14035     addDirectMem(MIB, X86::EAX);
14036     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14037   }
14038
14039   MI->eraseFromParent(); // The pseudo instruction is gone now.
14040   return BB;
14041 }
14042
14043 MachineBasicBlock *
14044 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14045                                     MachineBasicBlock *MBB) const {
14046   DebugLoc DL = MI->getDebugLoc();
14047   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14048
14049   MachineFunction *MF = MBB->getParent();
14050   MachineRegisterInfo &MRI = MF->getRegInfo();
14051
14052   const BasicBlock *BB = MBB->getBasicBlock();
14053   MachineFunction::iterator I = MBB;
14054   ++I;
14055
14056   // Memory Reference
14057   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14058   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14059
14060   unsigned DstReg;
14061   unsigned MemOpndSlot = 0;
14062
14063   unsigned CurOp = 0;
14064
14065   DstReg = MI->getOperand(CurOp++).getReg();
14066   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14067   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14068   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14069   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14070
14071   MemOpndSlot = CurOp;
14072
14073   MVT PVT = getPointerTy();
14074   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14075          "Invalid Pointer Size!");
14076
14077   // For v = setjmp(buf), we generate
14078   //
14079   // thisMBB:
14080   //  buf[LabelOffset] = restoreMBB
14081   //  SjLjSetup restoreMBB
14082   //
14083   // mainMBB:
14084   //  v_main = 0
14085   //
14086   // sinkMBB:
14087   //  v = phi(main, restore)
14088   //
14089   // restoreMBB:
14090   //  v_restore = 1
14091
14092   MachineBasicBlock *thisMBB = MBB;
14093   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14094   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14095   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14096   MF->insert(I, mainMBB);
14097   MF->insert(I, sinkMBB);
14098   MF->push_back(restoreMBB);
14099
14100   MachineInstrBuilder MIB;
14101
14102   // Transfer the remainder of BB and its successor edges to sinkMBB.
14103   sinkMBB->splice(sinkMBB->begin(), MBB,
14104                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14105   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14106
14107   // thisMBB:
14108   unsigned PtrStoreOpc = 0;
14109   unsigned LabelReg = 0;
14110   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14111   Reloc::Model RM = getTargetMachine().getRelocationModel();
14112   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14113                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14114
14115   // Prepare IP either in reg or imm.
14116   if (!UseImmLabel) {
14117     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14118     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14119     LabelReg = MRI.createVirtualRegister(PtrRC);
14120     if (Subtarget->is64Bit()) {
14121       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14122               .addReg(X86::RIP)
14123               .addImm(0)
14124               .addReg(0)
14125               .addMBB(restoreMBB)
14126               .addReg(0);
14127     } else {
14128       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14129       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14130               .addReg(XII->getGlobalBaseReg(MF))
14131               .addImm(0)
14132               .addReg(0)
14133               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14134               .addReg(0);
14135     }
14136   } else
14137     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14138   // Store IP
14139   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14140   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14141     if (i == X86::AddrDisp)
14142       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14143     else
14144       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14145   }
14146   if (!UseImmLabel)
14147     MIB.addReg(LabelReg);
14148   else
14149     MIB.addMBB(restoreMBB);
14150   MIB.setMemRefs(MMOBegin, MMOEnd);
14151   // Setup
14152   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14153           .addMBB(restoreMBB);
14154   MIB.addRegMask(RegInfo->getNoPreservedMask());
14155   thisMBB->addSuccessor(mainMBB);
14156   thisMBB->addSuccessor(restoreMBB);
14157
14158   // mainMBB:
14159   //  EAX = 0
14160   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14161   mainMBB->addSuccessor(sinkMBB);
14162
14163   // sinkMBB:
14164   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14165           TII->get(X86::PHI), DstReg)
14166     .addReg(mainDstReg).addMBB(mainMBB)
14167     .addReg(restoreDstReg).addMBB(restoreMBB);
14168
14169   // restoreMBB:
14170   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14171   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14172   restoreMBB->addSuccessor(sinkMBB);
14173
14174   MI->eraseFromParent();
14175   return sinkMBB;
14176 }
14177
14178 MachineBasicBlock *
14179 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14180                                      MachineBasicBlock *MBB) const {
14181   DebugLoc DL = MI->getDebugLoc();
14182   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14183
14184   MachineFunction *MF = MBB->getParent();
14185   MachineRegisterInfo &MRI = MF->getRegInfo();
14186
14187   // Memory Reference
14188   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14189   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14190
14191   MVT PVT = getPointerTy();
14192   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14193          "Invalid Pointer Size!");
14194
14195   const TargetRegisterClass *RC =
14196     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14197   unsigned Tmp = MRI.createVirtualRegister(RC);
14198   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14199   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14200   unsigned SP = RegInfo->getStackRegister();
14201
14202   MachineInstrBuilder MIB;
14203
14204   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14205   const int64_t SPOffset = 2 * PVT.getStoreSize();
14206
14207   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14208   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14209
14210   // Reload FP
14211   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14212   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14213     MIB.addOperand(MI->getOperand(i));
14214   MIB.setMemRefs(MMOBegin, MMOEnd);
14215   // Reload IP
14216   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14217   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14218     if (i == X86::AddrDisp)
14219       MIB.addDisp(MI->getOperand(i), LabelOffset);
14220     else
14221       MIB.addOperand(MI->getOperand(i));
14222   }
14223   MIB.setMemRefs(MMOBegin, MMOEnd);
14224   // Reload SP
14225   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14227     if (i == X86::AddrDisp)
14228       MIB.addDisp(MI->getOperand(i), SPOffset);
14229     else
14230       MIB.addOperand(MI->getOperand(i));
14231   }
14232   MIB.setMemRefs(MMOBegin, MMOEnd);
14233   // Jump
14234   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14235
14236   MI->eraseFromParent();
14237   return MBB;
14238 }
14239
14240 MachineBasicBlock *
14241 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14242                                                MachineBasicBlock *BB) const {
14243   switch (MI->getOpcode()) {
14244   default: llvm_unreachable("Unexpected instr type to insert");
14245   case X86::TAILJMPd64:
14246   case X86::TAILJMPr64:
14247   case X86::TAILJMPm64:
14248     llvm_unreachable("TAILJMP64 would not be touched here.");
14249   case X86::TCRETURNdi64:
14250   case X86::TCRETURNri64:
14251   case X86::TCRETURNmi64:
14252     return BB;
14253   case X86::WIN_ALLOCA:
14254     return EmitLoweredWinAlloca(MI, BB);
14255   case X86::SEG_ALLOCA_32:
14256     return EmitLoweredSegAlloca(MI, BB, false);
14257   case X86::SEG_ALLOCA_64:
14258     return EmitLoweredSegAlloca(MI, BB, true);
14259   case X86::TLSCall_32:
14260   case X86::TLSCall_64:
14261     return EmitLoweredTLSCall(MI, BB);
14262   case X86::CMOV_GR8:
14263   case X86::CMOV_FR32:
14264   case X86::CMOV_FR64:
14265   case X86::CMOV_V4F32:
14266   case X86::CMOV_V2F64:
14267   case X86::CMOV_V2I64:
14268   case X86::CMOV_V8F32:
14269   case X86::CMOV_V4F64:
14270   case X86::CMOV_V4I64:
14271   case X86::CMOV_GR16:
14272   case X86::CMOV_GR32:
14273   case X86::CMOV_RFP32:
14274   case X86::CMOV_RFP64:
14275   case X86::CMOV_RFP80:
14276     return EmitLoweredSelect(MI, BB);
14277
14278   case X86::FP32_TO_INT16_IN_MEM:
14279   case X86::FP32_TO_INT32_IN_MEM:
14280   case X86::FP32_TO_INT64_IN_MEM:
14281   case X86::FP64_TO_INT16_IN_MEM:
14282   case X86::FP64_TO_INT32_IN_MEM:
14283   case X86::FP64_TO_INT64_IN_MEM:
14284   case X86::FP80_TO_INT16_IN_MEM:
14285   case X86::FP80_TO_INT32_IN_MEM:
14286   case X86::FP80_TO_INT64_IN_MEM: {
14287     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14288     DebugLoc DL = MI->getDebugLoc();
14289
14290     // Change the floating point control register to use "round towards zero"
14291     // mode when truncating to an integer value.
14292     MachineFunction *F = BB->getParent();
14293     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14294     addFrameReference(BuildMI(*BB, MI, DL,
14295                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14296
14297     // Load the old value of the high byte of the control word...
14298     unsigned OldCW =
14299       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14300     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14301                       CWFrameIdx);
14302
14303     // Set the high part to be round to zero...
14304     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14305       .addImm(0xC7F);
14306
14307     // Reload the modified control word now...
14308     addFrameReference(BuildMI(*BB, MI, DL,
14309                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14310
14311     // Restore the memory image of control word to original value
14312     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14313       .addReg(OldCW);
14314
14315     // Get the X86 opcode to use.
14316     unsigned Opc;
14317     switch (MI->getOpcode()) {
14318     default: llvm_unreachable("illegal opcode!");
14319     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14320     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14321     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14322     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14323     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14324     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14325     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14326     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14327     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14328     }
14329
14330     X86AddressMode AM;
14331     MachineOperand &Op = MI->getOperand(0);
14332     if (Op.isReg()) {
14333       AM.BaseType = X86AddressMode::RegBase;
14334       AM.Base.Reg = Op.getReg();
14335     } else {
14336       AM.BaseType = X86AddressMode::FrameIndexBase;
14337       AM.Base.FrameIndex = Op.getIndex();
14338     }
14339     Op = MI->getOperand(1);
14340     if (Op.isImm())
14341       AM.Scale = Op.getImm();
14342     Op = MI->getOperand(2);
14343     if (Op.isImm())
14344       AM.IndexReg = Op.getImm();
14345     Op = MI->getOperand(3);
14346     if (Op.isGlobal()) {
14347       AM.GV = Op.getGlobal();
14348     } else {
14349       AM.Disp = Op.getImm();
14350     }
14351     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14352                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14353
14354     // Reload the original control word now.
14355     addFrameReference(BuildMI(*BB, MI, DL,
14356                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14357
14358     MI->eraseFromParent();   // The pseudo instruction is gone now.
14359     return BB;
14360   }
14361     // String/text processing lowering.
14362   case X86::PCMPISTRM128REG:
14363   case X86::VPCMPISTRM128REG:
14364   case X86::PCMPISTRM128MEM:
14365   case X86::VPCMPISTRM128MEM:
14366   case X86::PCMPESTRM128REG:
14367   case X86::VPCMPESTRM128REG:
14368   case X86::PCMPESTRM128MEM:
14369   case X86::VPCMPESTRM128MEM:
14370     assert(Subtarget->hasSSE42() &&
14371            "Target must have SSE4.2 or AVX features enabled");
14372     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14373
14374   // String/text processing lowering.
14375   case X86::PCMPISTRIREG:
14376   case X86::VPCMPISTRIREG:
14377   case X86::PCMPISTRIMEM:
14378   case X86::VPCMPISTRIMEM:
14379   case X86::PCMPESTRIREG:
14380   case X86::VPCMPESTRIREG:
14381   case X86::PCMPESTRIMEM:
14382   case X86::VPCMPESTRIMEM:
14383     assert(Subtarget->hasSSE42() &&
14384            "Target must have SSE4.2 or AVX features enabled");
14385     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14386
14387   // Thread synchronization.
14388   case X86::MONITOR:
14389     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14390
14391   // xbegin
14392   case X86::XBEGIN:
14393     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14394
14395   // Atomic Lowering.
14396   case X86::ATOMAND8:
14397   case X86::ATOMAND16:
14398   case X86::ATOMAND32:
14399   case X86::ATOMAND64:
14400     // Fall through
14401   case X86::ATOMOR8:
14402   case X86::ATOMOR16:
14403   case X86::ATOMOR32:
14404   case X86::ATOMOR64:
14405     // Fall through
14406   case X86::ATOMXOR16:
14407   case X86::ATOMXOR8:
14408   case X86::ATOMXOR32:
14409   case X86::ATOMXOR64:
14410     // Fall through
14411   case X86::ATOMNAND8:
14412   case X86::ATOMNAND16:
14413   case X86::ATOMNAND32:
14414   case X86::ATOMNAND64:
14415     // Fall through
14416   case X86::ATOMMAX8:
14417   case X86::ATOMMAX16:
14418   case X86::ATOMMAX32:
14419   case X86::ATOMMAX64:
14420     // Fall through
14421   case X86::ATOMMIN8:
14422   case X86::ATOMMIN16:
14423   case X86::ATOMMIN32:
14424   case X86::ATOMMIN64:
14425     // Fall through
14426   case X86::ATOMUMAX8:
14427   case X86::ATOMUMAX16:
14428   case X86::ATOMUMAX32:
14429   case X86::ATOMUMAX64:
14430     // Fall through
14431   case X86::ATOMUMIN8:
14432   case X86::ATOMUMIN16:
14433   case X86::ATOMUMIN32:
14434   case X86::ATOMUMIN64:
14435     return EmitAtomicLoadArith(MI, BB);
14436
14437   // This group does 64-bit operations on a 32-bit host.
14438   case X86::ATOMAND6432:
14439   case X86::ATOMOR6432:
14440   case X86::ATOMXOR6432:
14441   case X86::ATOMNAND6432:
14442   case X86::ATOMADD6432:
14443   case X86::ATOMSUB6432:
14444   case X86::ATOMMAX6432:
14445   case X86::ATOMMIN6432:
14446   case X86::ATOMUMAX6432:
14447   case X86::ATOMUMIN6432:
14448   case X86::ATOMSWAP6432:
14449     return EmitAtomicLoadArith6432(MI, BB);
14450
14451   case X86::VASTART_SAVE_XMM_REGS:
14452     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14453
14454   case X86::VAARG_64:
14455     return EmitVAARG64WithCustomInserter(MI, BB);
14456
14457   case X86::EH_SjLj_SetJmp32:
14458   case X86::EH_SjLj_SetJmp64:
14459     return emitEHSjLjSetJmp(MI, BB);
14460
14461   case X86::EH_SjLj_LongJmp32:
14462   case X86::EH_SjLj_LongJmp64:
14463     return emitEHSjLjLongJmp(MI, BB);
14464   }
14465 }
14466
14467 //===----------------------------------------------------------------------===//
14468 //                           X86 Optimization Hooks
14469 //===----------------------------------------------------------------------===//
14470
14471 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14472                                                        APInt &KnownZero,
14473                                                        APInt &KnownOne,
14474                                                        const SelectionDAG &DAG,
14475                                                        unsigned Depth) const {
14476   unsigned BitWidth = KnownZero.getBitWidth();
14477   unsigned Opc = Op.getOpcode();
14478   assert((Opc >= ISD::BUILTIN_OP_END ||
14479           Opc == ISD::INTRINSIC_WO_CHAIN ||
14480           Opc == ISD::INTRINSIC_W_CHAIN ||
14481           Opc == ISD::INTRINSIC_VOID) &&
14482          "Should use MaskedValueIsZero if you don't know whether Op"
14483          " is a target node!");
14484
14485   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14486   switch (Opc) {
14487   default: break;
14488   case X86ISD::ADD:
14489   case X86ISD::SUB:
14490   case X86ISD::ADC:
14491   case X86ISD::SBB:
14492   case X86ISD::SMUL:
14493   case X86ISD::UMUL:
14494   case X86ISD::INC:
14495   case X86ISD::DEC:
14496   case X86ISD::OR:
14497   case X86ISD::XOR:
14498   case X86ISD::AND:
14499     // These nodes' second result is a boolean.
14500     if (Op.getResNo() == 0)
14501       break;
14502     // Fallthrough
14503   case X86ISD::SETCC:
14504     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14505     break;
14506   case ISD::INTRINSIC_WO_CHAIN: {
14507     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14508     unsigned NumLoBits = 0;
14509     switch (IntId) {
14510     default: break;
14511     case Intrinsic::x86_sse_movmsk_ps:
14512     case Intrinsic::x86_avx_movmsk_ps_256:
14513     case Intrinsic::x86_sse2_movmsk_pd:
14514     case Intrinsic::x86_avx_movmsk_pd_256:
14515     case Intrinsic::x86_mmx_pmovmskb:
14516     case Intrinsic::x86_sse2_pmovmskb_128:
14517     case Intrinsic::x86_avx2_pmovmskb: {
14518       // High bits of movmskp{s|d}, pmovmskb are known zero.
14519       switch (IntId) {
14520         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14521         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14522         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14523         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14524         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14525         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14526         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14527         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14528       }
14529       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14530       break;
14531     }
14532     }
14533     break;
14534   }
14535   }
14536 }
14537
14538 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14539                                                          unsigned Depth) const {
14540   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14541   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14542     return Op.getValueType().getScalarType().getSizeInBits();
14543
14544   // Fallback case.
14545   return 1;
14546 }
14547
14548 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14549 /// node is a GlobalAddress + offset.
14550 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14551                                        const GlobalValue* &GA,
14552                                        int64_t &Offset) const {
14553   if (N->getOpcode() == X86ISD::Wrapper) {
14554     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14555       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14556       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14557       return true;
14558     }
14559   }
14560   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14561 }
14562
14563 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14564 /// same as extracting the high 128-bit part of 256-bit vector and then
14565 /// inserting the result into the low part of a new 256-bit vector
14566 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14567   EVT VT = SVOp->getValueType(0);
14568   unsigned NumElems = VT.getVectorNumElements();
14569
14570   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14571   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14572     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14573         SVOp->getMaskElt(j) >= 0)
14574       return false;
14575
14576   return true;
14577 }
14578
14579 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14580 /// same as extracting the low 128-bit part of 256-bit vector and then
14581 /// inserting the result into the high part of a new 256-bit vector
14582 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14583   EVT VT = SVOp->getValueType(0);
14584   unsigned NumElems = VT.getVectorNumElements();
14585
14586   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14587   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14588     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14589         SVOp->getMaskElt(j) >= 0)
14590       return false;
14591
14592   return true;
14593 }
14594
14595 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14596 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14597                                         TargetLowering::DAGCombinerInfo &DCI,
14598                                         const X86Subtarget* Subtarget) {
14599   DebugLoc dl = N->getDebugLoc();
14600   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14601   SDValue V1 = SVOp->getOperand(0);
14602   SDValue V2 = SVOp->getOperand(1);
14603   EVT VT = SVOp->getValueType(0);
14604   unsigned NumElems = VT.getVectorNumElements();
14605
14606   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14607       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14608     //
14609     //                   0,0,0,...
14610     //                      |
14611     //    V      UNDEF    BUILD_VECTOR    UNDEF
14612     //     \      /           \           /
14613     //  CONCAT_VECTOR         CONCAT_VECTOR
14614     //         \                  /
14615     //          \                /
14616     //          RESULT: V + zero extended
14617     //
14618     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14619         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14620         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14621       return SDValue();
14622
14623     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14624       return SDValue();
14625
14626     // To match the shuffle mask, the first half of the mask should
14627     // be exactly the first vector, and all the rest a splat with the
14628     // first element of the second one.
14629     for (unsigned i = 0; i != NumElems/2; ++i)
14630       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14631           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14632         return SDValue();
14633
14634     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14635     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14636       if (Ld->hasNUsesOfValue(1, 0)) {
14637         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14638         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14639         SDValue ResNode =
14640           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14641                                   Ld->getMemoryVT(),
14642                                   Ld->getPointerInfo(),
14643                                   Ld->getAlignment(),
14644                                   false/*isVolatile*/, true/*ReadMem*/,
14645                                   false/*WriteMem*/);
14646
14647         // Make sure the newly-created LOAD is in the same position as Ld in
14648         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14649         // and update uses of Ld's output chain to use the TokenFactor.
14650         if (Ld->hasAnyUseOfValue(1)) {
14651           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14652                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14653           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14654           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14655                                  SDValue(ResNode.getNode(), 1));
14656         }
14657
14658         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14659       }
14660     }
14661
14662     // Emit a zeroed vector and insert the desired subvector on its
14663     // first half.
14664     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14665     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14666     return DCI.CombineTo(N, InsV);
14667   }
14668
14669   //===--------------------------------------------------------------------===//
14670   // Combine some shuffles into subvector extracts and inserts:
14671   //
14672
14673   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14674   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14675     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14676     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14677     return DCI.CombineTo(N, InsV);
14678   }
14679
14680   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14681   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14682     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14683     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14684     return DCI.CombineTo(N, InsV);
14685   }
14686
14687   return SDValue();
14688 }
14689
14690 /// PerformShuffleCombine - Performs several different shuffle combines.
14691 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14692                                      TargetLowering::DAGCombinerInfo &DCI,
14693                                      const X86Subtarget *Subtarget) {
14694   DebugLoc dl = N->getDebugLoc();
14695   EVT VT = N->getValueType(0);
14696
14697   // Don't create instructions with illegal types after legalize types has run.
14698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14699   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14700     return SDValue();
14701
14702   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14703   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14704       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14705     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14706
14707   // Only handle 128 wide vector from here on.
14708   if (!VT.is128BitVector())
14709     return SDValue();
14710
14711   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14712   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14713   // consecutive, non-overlapping, and in the right order.
14714   SmallVector<SDValue, 16> Elts;
14715   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14716     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14717
14718   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14719 }
14720
14721 /// PerformTruncateCombine - Converts truncate operation to
14722 /// a sequence of vector shuffle operations.
14723 /// It is possible when we truncate 256-bit vector to 128-bit vector
14724 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14725                                       TargetLowering::DAGCombinerInfo &DCI,
14726                                       const X86Subtarget *Subtarget)  {
14727   return SDValue();
14728 }
14729
14730 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14731 /// specific shuffle of a load can be folded into a single element load.
14732 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14733 /// shuffles have been customed lowered so we need to handle those here.
14734 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14735                                          TargetLowering::DAGCombinerInfo &DCI) {
14736   if (DCI.isBeforeLegalizeOps())
14737     return SDValue();
14738
14739   SDValue InVec = N->getOperand(0);
14740   SDValue EltNo = N->getOperand(1);
14741
14742   if (!isa<ConstantSDNode>(EltNo))
14743     return SDValue();
14744
14745   EVT VT = InVec.getValueType();
14746
14747   bool HasShuffleIntoBitcast = false;
14748   if (InVec.getOpcode() == ISD::BITCAST) {
14749     // Don't duplicate a load with other uses.
14750     if (!InVec.hasOneUse())
14751       return SDValue();
14752     EVT BCVT = InVec.getOperand(0).getValueType();
14753     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14754       return SDValue();
14755     InVec = InVec.getOperand(0);
14756     HasShuffleIntoBitcast = true;
14757   }
14758
14759   if (!isTargetShuffle(InVec.getOpcode()))
14760     return SDValue();
14761
14762   // Don't duplicate a load with other uses.
14763   if (!InVec.hasOneUse())
14764     return SDValue();
14765
14766   SmallVector<int, 16> ShuffleMask;
14767   bool UnaryShuffle;
14768   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14769                             UnaryShuffle))
14770     return SDValue();
14771
14772   // Select the input vector, guarding against out of range extract vector.
14773   unsigned NumElems = VT.getVectorNumElements();
14774   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14775   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14776   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14777                                          : InVec.getOperand(1);
14778
14779   // If inputs to shuffle are the same for both ops, then allow 2 uses
14780   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14781
14782   if (LdNode.getOpcode() == ISD::BITCAST) {
14783     // Don't duplicate a load with other uses.
14784     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14785       return SDValue();
14786
14787     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14788     LdNode = LdNode.getOperand(0);
14789   }
14790
14791   if (!ISD::isNormalLoad(LdNode.getNode()))
14792     return SDValue();
14793
14794   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14795
14796   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14797     return SDValue();
14798
14799   if (HasShuffleIntoBitcast) {
14800     // If there's a bitcast before the shuffle, check if the load type and
14801     // alignment is valid.
14802     unsigned Align = LN0->getAlignment();
14803     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14804     unsigned NewAlign = TLI.getDataLayout()->
14805       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14806
14807     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14808       return SDValue();
14809   }
14810
14811   // All checks match so transform back to vector_shuffle so that DAG combiner
14812   // can finish the job
14813   DebugLoc dl = N->getDebugLoc();
14814
14815   // Create shuffle node taking into account the case that its a unary shuffle
14816   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14817   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14818                                  InVec.getOperand(0), Shuffle,
14819                                  &ShuffleMask[0]);
14820   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14821   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14822                      EltNo);
14823 }
14824
14825 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14826 /// generation and convert it from being a bunch of shuffles and extracts
14827 /// to a simple store and scalar loads to extract the elements.
14828 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14829                                          TargetLowering::DAGCombinerInfo &DCI) {
14830   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14831   if (NewOp.getNode())
14832     return NewOp;
14833
14834   SDValue InputVector = N->getOperand(0);
14835   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14836   // from mmx to v2i32 has a single usage.
14837   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14838       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14839       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14840     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14841                        N->getValueType(0),
14842                        InputVector.getNode()->getOperand(0));
14843
14844   // Only operate on vectors of 4 elements, where the alternative shuffling
14845   // gets to be more expensive.
14846   if (InputVector.getValueType() != MVT::v4i32)
14847     return SDValue();
14848
14849   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14850   // single use which is a sign-extend or zero-extend, and all elements are
14851   // used.
14852   SmallVector<SDNode *, 4> Uses;
14853   unsigned ExtractedElements = 0;
14854   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14855        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14856     if (UI.getUse().getResNo() != InputVector.getResNo())
14857       return SDValue();
14858
14859     SDNode *Extract = *UI;
14860     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14861       return SDValue();
14862
14863     if (Extract->getValueType(0) != MVT::i32)
14864       return SDValue();
14865     if (!Extract->hasOneUse())
14866       return SDValue();
14867     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14868         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14869       return SDValue();
14870     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14871       return SDValue();
14872
14873     // Record which element was extracted.
14874     ExtractedElements |=
14875       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14876
14877     Uses.push_back(Extract);
14878   }
14879
14880   // If not all the elements were used, this may not be worthwhile.
14881   if (ExtractedElements != 15)
14882     return SDValue();
14883
14884   // Ok, we've now decided to do the transformation.
14885   DebugLoc dl = InputVector.getDebugLoc();
14886
14887   // Store the value to a temporary stack slot.
14888   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14889   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14890                             MachinePointerInfo(), false, false, 0);
14891
14892   // Replace each use (extract) with a load of the appropriate element.
14893   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14894        UE = Uses.end(); UI != UE; ++UI) {
14895     SDNode *Extract = *UI;
14896
14897     // cOMpute the element's address.
14898     SDValue Idx = Extract->getOperand(1);
14899     unsigned EltSize =
14900         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14901     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14902     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14903     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14904
14905     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14906                                      StackPtr, OffsetVal);
14907
14908     // Load the scalar.
14909     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14910                                      ScalarAddr, MachinePointerInfo(),
14911                                      false, false, false, 0);
14912
14913     // Replace the exact with the load.
14914     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14915   }
14916
14917   // The replacement was made in place; don't return anything.
14918   return SDValue();
14919 }
14920
14921 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14922 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14923                                    SDValue RHS, SelectionDAG &DAG,
14924                                    const X86Subtarget *Subtarget) {
14925   if (!VT.isVector())
14926     return 0;
14927
14928   switch (VT.getSimpleVT().SimpleTy) {
14929   default: return 0;
14930   case MVT::v32i8:
14931   case MVT::v16i16:
14932   case MVT::v8i32:
14933     if (!Subtarget->hasAVX2())
14934       return 0;
14935   case MVT::v16i8:
14936   case MVT::v8i16:
14937   case MVT::v4i32:
14938     if (!Subtarget->hasSSE2())
14939       return 0;
14940   }
14941
14942   // SSE2 has only a small subset of the operations.
14943   bool hasUnsigned = Subtarget->hasSSE41() ||
14944                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14945   bool hasSigned = Subtarget->hasSSE41() ||
14946                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14947
14948   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14949
14950   // Check for x CC y ? x : y.
14951   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14952       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14953     switch (CC) {
14954     default: break;
14955     case ISD::SETULT:
14956     case ISD::SETULE:
14957       return hasUnsigned ? X86ISD::UMIN : 0;
14958     case ISD::SETUGT:
14959     case ISD::SETUGE:
14960       return hasUnsigned ? X86ISD::UMAX : 0;
14961     case ISD::SETLT:
14962     case ISD::SETLE:
14963       return hasSigned ? X86ISD::SMIN : 0;
14964     case ISD::SETGT:
14965     case ISD::SETGE:
14966       return hasSigned ? X86ISD::SMAX : 0;
14967     }
14968   // Check for x CC y ? y : x -- a min/max with reversed arms.
14969   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14970              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14971     switch (CC) {
14972     default: break;
14973     case ISD::SETULT:
14974     case ISD::SETULE:
14975       return hasUnsigned ? X86ISD::UMAX : 0;
14976     case ISD::SETUGT:
14977     case ISD::SETUGE:
14978       return hasUnsigned ? X86ISD::UMIN : 0;
14979     case ISD::SETLT:
14980     case ISD::SETLE:
14981       return hasSigned ? X86ISD::SMAX : 0;
14982     case ISD::SETGT:
14983     case ISD::SETGE:
14984       return hasSigned ? X86ISD::SMIN : 0;
14985     }
14986   }
14987
14988   return 0;
14989 }
14990
14991 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14992 /// nodes.
14993 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14994                                     TargetLowering::DAGCombinerInfo &DCI,
14995                                     const X86Subtarget *Subtarget) {
14996   DebugLoc DL = N->getDebugLoc();
14997   SDValue Cond = N->getOperand(0);
14998   // Get the LHS/RHS of the select.
14999   SDValue LHS = N->getOperand(1);
15000   SDValue RHS = N->getOperand(2);
15001   EVT VT = LHS.getValueType();
15002
15003   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15004   // instructions match the semantics of the common C idiom x<y?x:y but not
15005   // x<=y?x:y, because of how they handle negative zero (which can be
15006   // ignored in unsafe-math mode).
15007   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15008       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15009       (Subtarget->hasSSE2() ||
15010        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15011     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15012
15013     unsigned Opcode = 0;
15014     // Check for x CC y ? x : y.
15015     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15016         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15017       switch (CC) {
15018       default: break;
15019       case ISD::SETULT:
15020         // Converting this to a min would handle NaNs incorrectly, and swapping
15021         // the operands would cause it to handle comparisons between positive
15022         // and negative zero incorrectly.
15023         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15024           if (!DAG.getTarget().Options.UnsafeFPMath &&
15025               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15026             break;
15027           std::swap(LHS, RHS);
15028         }
15029         Opcode = X86ISD::FMIN;
15030         break;
15031       case ISD::SETOLE:
15032         // Converting this to a min would handle comparisons between positive
15033         // and negative zero incorrectly.
15034         if (!DAG.getTarget().Options.UnsafeFPMath &&
15035             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15036           break;
15037         Opcode = X86ISD::FMIN;
15038         break;
15039       case ISD::SETULE:
15040         // Converting this to a min would handle both negative zeros and NaNs
15041         // incorrectly, but we can swap the operands to fix both.
15042         std::swap(LHS, RHS);
15043       case ISD::SETOLT:
15044       case ISD::SETLT:
15045       case ISD::SETLE:
15046         Opcode = X86ISD::FMIN;
15047         break;
15048
15049       case ISD::SETOGE:
15050         // Converting this to a max would handle comparisons between positive
15051         // and negative zero incorrectly.
15052         if (!DAG.getTarget().Options.UnsafeFPMath &&
15053             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15054           break;
15055         Opcode = X86ISD::FMAX;
15056         break;
15057       case ISD::SETUGT:
15058         // Converting this to a max would handle NaNs incorrectly, and swapping
15059         // the operands would cause it to handle comparisons between positive
15060         // and negative zero incorrectly.
15061         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15062           if (!DAG.getTarget().Options.UnsafeFPMath &&
15063               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15064             break;
15065           std::swap(LHS, RHS);
15066         }
15067         Opcode = X86ISD::FMAX;
15068         break;
15069       case ISD::SETUGE:
15070         // Converting this to a max would handle both negative zeros and NaNs
15071         // incorrectly, but we can swap the operands to fix both.
15072         std::swap(LHS, RHS);
15073       case ISD::SETOGT:
15074       case ISD::SETGT:
15075       case ISD::SETGE:
15076         Opcode = X86ISD::FMAX;
15077         break;
15078       }
15079     // Check for x CC y ? y : x -- a min/max with reversed arms.
15080     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15081                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15082       switch (CC) {
15083       default: break;
15084       case ISD::SETOGE:
15085         // Converting this to a min would handle comparisons between positive
15086         // and negative zero incorrectly, and swapping the operands would
15087         // cause it to handle NaNs incorrectly.
15088         if (!DAG.getTarget().Options.UnsafeFPMath &&
15089             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15090           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15091             break;
15092           std::swap(LHS, RHS);
15093         }
15094         Opcode = X86ISD::FMIN;
15095         break;
15096       case ISD::SETUGT:
15097         // Converting this to a min would handle NaNs incorrectly.
15098         if (!DAG.getTarget().Options.UnsafeFPMath &&
15099             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15100           break;
15101         Opcode = X86ISD::FMIN;
15102         break;
15103       case ISD::SETUGE:
15104         // Converting this to a min would handle both negative zeros and NaNs
15105         // incorrectly, but we can swap the operands to fix both.
15106         std::swap(LHS, RHS);
15107       case ISD::SETOGT:
15108       case ISD::SETGT:
15109       case ISD::SETGE:
15110         Opcode = X86ISD::FMIN;
15111         break;
15112
15113       case ISD::SETULT:
15114         // Converting this to a max would handle NaNs incorrectly.
15115         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15116           break;
15117         Opcode = X86ISD::FMAX;
15118         break;
15119       case ISD::SETOLE:
15120         // Converting this to a max would handle comparisons between positive
15121         // and negative zero incorrectly, and swapping the operands would
15122         // cause it to handle NaNs incorrectly.
15123         if (!DAG.getTarget().Options.UnsafeFPMath &&
15124             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15125           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15126             break;
15127           std::swap(LHS, RHS);
15128         }
15129         Opcode = X86ISD::FMAX;
15130         break;
15131       case ISD::SETULE:
15132         // Converting this to a max would handle both negative zeros and NaNs
15133         // incorrectly, but we can swap the operands to fix both.
15134         std::swap(LHS, RHS);
15135       case ISD::SETOLT:
15136       case ISD::SETLT:
15137       case ISD::SETLE:
15138         Opcode = X86ISD::FMAX;
15139         break;
15140       }
15141     }
15142
15143     if (Opcode)
15144       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15145   }
15146
15147   // If this is a select between two integer constants, try to do some
15148   // optimizations.
15149   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15150     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15151       // Don't do this for crazy integer types.
15152       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15153         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15154         // so that TrueC (the true value) is larger than FalseC.
15155         bool NeedsCondInvert = false;
15156
15157         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15158             // Efficiently invertible.
15159             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15160              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15161               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15162           NeedsCondInvert = true;
15163           std::swap(TrueC, FalseC);
15164         }
15165
15166         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15167         if (FalseC->getAPIntValue() == 0 &&
15168             TrueC->getAPIntValue().isPowerOf2()) {
15169           if (NeedsCondInvert) // Invert the condition if needed.
15170             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15171                                DAG.getConstant(1, Cond.getValueType()));
15172
15173           // Zero extend the condition if needed.
15174           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15175
15176           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15177           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15178                              DAG.getConstant(ShAmt, MVT::i8));
15179         }
15180
15181         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15182         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15183           if (NeedsCondInvert) // Invert the condition if needed.
15184             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15185                                DAG.getConstant(1, Cond.getValueType()));
15186
15187           // Zero extend the condition if needed.
15188           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15189                              FalseC->getValueType(0), Cond);
15190           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15191                              SDValue(FalseC, 0));
15192         }
15193
15194         // Optimize cases that will turn into an LEA instruction.  This requires
15195         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15196         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15197           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15198           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15199
15200           bool isFastMultiplier = false;
15201           if (Diff < 10) {
15202             switch ((unsigned char)Diff) {
15203               default: break;
15204               case 1:  // result = add base, cond
15205               case 2:  // result = lea base(    , cond*2)
15206               case 3:  // result = lea base(cond, cond*2)
15207               case 4:  // result = lea base(    , cond*4)
15208               case 5:  // result = lea base(cond, cond*4)
15209               case 8:  // result = lea base(    , cond*8)
15210               case 9:  // result = lea base(cond, cond*8)
15211                 isFastMultiplier = true;
15212                 break;
15213             }
15214           }
15215
15216           if (isFastMultiplier) {
15217             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15218             if (NeedsCondInvert) // Invert the condition if needed.
15219               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15220                                  DAG.getConstant(1, Cond.getValueType()));
15221
15222             // Zero extend the condition if needed.
15223             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15224                                Cond);
15225             // Scale the condition by the difference.
15226             if (Diff != 1)
15227               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15228                                  DAG.getConstant(Diff, Cond.getValueType()));
15229
15230             // Add the base if non-zero.
15231             if (FalseC->getAPIntValue() != 0)
15232               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15233                                  SDValue(FalseC, 0));
15234             return Cond;
15235           }
15236         }
15237       }
15238   }
15239
15240   // Canonicalize max and min:
15241   // (x > y) ? x : y -> (x >= y) ? x : y
15242   // (x < y) ? x : y -> (x <= y) ? x : y
15243   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15244   // the need for an extra compare
15245   // against zero. e.g.
15246   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15247   // subl   %esi, %edi
15248   // testl  %edi, %edi
15249   // movl   $0, %eax
15250   // cmovgl %edi, %eax
15251   // =>
15252   // xorl   %eax, %eax
15253   // subl   %esi, $edi
15254   // cmovsl %eax, %edi
15255   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15256       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15257       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15258     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15259     switch (CC) {
15260     default: break;
15261     case ISD::SETLT:
15262     case ISD::SETGT: {
15263       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15264       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15265                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15266       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15267     }
15268     }
15269   }
15270
15271   // Match VSELECTs into subs with unsigned saturation.
15272   if (!DCI.isBeforeLegalize() &&
15273       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15274       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15275       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15276        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15277     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15278
15279     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15280     // left side invert the predicate to simplify logic below.
15281     SDValue Other;
15282     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15283       Other = RHS;
15284       CC = ISD::getSetCCInverse(CC, true);
15285     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15286       Other = LHS;
15287     }
15288
15289     if (Other.getNode() && Other->getNumOperands() == 2 &&
15290         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15291       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15292       SDValue CondRHS = Cond->getOperand(1);
15293
15294       // Look for a general sub with unsigned saturation first.
15295       // x >= y ? x-y : 0 --> subus x, y
15296       // x >  y ? x-y : 0 --> subus x, y
15297       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15298           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15299         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15300
15301       // If the RHS is a constant we have to reverse the const canonicalization.
15302       // x > C-1 ? x+-C : 0 --> subus x, C
15303       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15304           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15305         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15306         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15307           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15308                                      DAG.getConstant(-A, VT.getScalarType()));
15309           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15310                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15311                                          V.data(), V.size()));
15312         }
15313       }
15314
15315       // Another special case: If C was a sign bit, the sub has been
15316       // canonicalized into a xor.
15317       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15318       //        it's safe to decanonicalize the xor?
15319       // x s< 0 ? x^C : 0 --> subus x, C
15320       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15321           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15322           isSplatVector(OpRHS.getNode())) {
15323         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15324         if (A.isSignBit())
15325           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15326       }
15327     }
15328   }
15329
15330   // Try to match a min/max vector operation.
15331   if (!DCI.isBeforeLegalize() &&
15332       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15333     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15334       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15335
15336   // If we know that this node is legal then we know that it is going to be
15337   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15338   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15339   // to simplify previous instructions.
15340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15341   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15342       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15343     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15344
15345     // Don't optimize vector selects that map to mask-registers.
15346     if (BitWidth == 1)
15347       return SDValue();
15348
15349     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15350     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15351
15352     APInt KnownZero, KnownOne;
15353     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15354                                           DCI.isBeforeLegalizeOps());
15355     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15356         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15357       DCI.CommitTargetLoweringOpt(TLO);
15358   }
15359
15360   return SDValue();
15361 }
15362
15363 // Check whether a boolean test is testing a boolean value generated by
15364 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15365 // code.
15366 //
15367 // Simplify the following patterns:
15368 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15369 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15370 // to (Op EFLAGS Cond)
15371 //
15372 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15373 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15374 // to (Op EFLAGS !Cond)
15375 //
15376 // where Op could be BRCOND or CMOV.
15377 //
15378 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15379   // Quit if not CMP and SUB with its value result used.
15380   if (Cmp.getOpcode() != X86ISD::CMP &&
15381       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15382       return SDValue();
15383
15384   // Quit if not used as a boolean value.
15385   if (CC != X86::COND_E && CC != X86::COND_NE)
15386     return SDValue();
15387
15388   // Check CMP operands. One of them should be 0 or 1 and the other should be
15389   // an SetCC or extended from it.
15390   SDValue Op1 = Cmp.getOperand(0);
15391   SDValue Op2 = Cmp.getOperand(1);
15392
15393   SDValue SetCC;
15394   const ConstantSDNode* C = 0;
15395   bool needOppositeCond = (CC == X86::COND_E);
15396
15397   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15398     SetCC = Op2;
15399   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15400     SetCC = Op1;
15401   else // Quit if all operands are not constants.
15402     return SDValue();
15403
15404   if (C->getZExtValue() == 1)
15405     needOppositeCond = !needOppositeCond;
15406   else if (C->getZExtValue() != 0)
15407     // Quit if the constant is neither 0 or 1.
15408     return SDValue();
15409
15410   // Skip 'zext' node.
15411   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15412     SetCC = SetCC.getOperand(0);
15413
15414   switch (SetCC.getOpcode()) {
15415   case X86ISD::SETCC:
15416     // Set the condition code or opposite one if necessary.
15417     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15418     if (needOppositeCond)
15419       CC = X86::GetOppositeBranchCondition(CC);
15420     return SetCC.getOperand(1);
15421   case X86ISD::CMOV: {
15422     // Check whether false/true value has canonical one, i.e. 0 or 1.
15423     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15424     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15425     // Quit if true value is not a constant.
15426     if (!TVal)
15427       return SDValue();
15428     // Quit if false value is not a constant.
15429     if (!FVal) {
15430       // A special case for rdrand, where 0 is set if false cond is found.
15431       SDValue Op = SetCC.getOperand(0);
15432       if (Op.getOpcode() != X86ISD::RDRAND)
15433         return SDValue();
15434     }
15435     // Quit if false value is not the constant 0 or 1.
15436     bool FValIsFalse = true;
15437     if (FVal && FVal->getZExtValue() != 0) {
15438       if (FVal->getZExtValue() != 1)
15439         return SDValue();
15440       // If FVal is 1, opposite cond is needed.
15441       needOppositeCond = !needOppositeCond;
15442       FValIsFalse = false;
15443     }
15444     // Quit if TVal is not the constant opposite of FVal.
15445     if (FValIsFalse && TVal->getZExtValue() != 1)
15446       return SDValue();
15447     if (!FValIsFalse && TVal->getZExtValue() != 0)
15448       return SDValue();
15449     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15450     if (needOppositeCond)
15451       CC = X86::GetOppositeBranchCondition(CC);
15452     return SetCC.getOperand(3);
15453   }
15454   }
15455
15456   return SDValue();
15457 }
15458
15459 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15460 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15461                                   TargetLowering::DAGCombinerInfo &DCI,
15462                                   const X86Subtarget *Subtarget) {
15463   DebugLoc DL = N->getDebugLoc();
15464
15465   // If the flag operand isn't dead, don't touch this CMOV.
15466   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15467     return SDValue();
15468
15469   SDValue FalseOp = N->getOperand(0);
15470   SDValue TrueOp = N->getOperand(1);
15471   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15472   SDValue Cond = N->getOperand(3);
15473
15474   if (CC == X86::COND_E || CC == X86::COND_NE) {
15475     switch (Cond.getOpcode()) {
15476     default: break;
15477     case X86ISD::BSR:
15478     case X86ISD::BSF:
15479       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15480       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15481         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15482     }
15483   }
15484
15485   SDValue Flags;
15486
15487   Flags = checkBoolTestSetCCCombine(Cond, CC);
15488   if (Flags.getNode() &&
15489       // Extra check as FCMOV only supports a subset of X86 cond.
15490       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15491     SDValue Ops[] = { FalseOp, TrueOp,
15492                       DAG.getConstant(CC, MVT::i8), Flags };
15493     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15494                        Ops, array_lengthof(Ops));
15495   }
15496
15497   // If this is a select between two integer constants, try to do some
15498   // optimizations.  Note that the operands are ordered the opposite of SELECT
15499   // operands.
15500   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15501     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15502       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15503       // larger than FalseC (the false value).
15504       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15505         CC = X86::GetOppositeBranchCondition(CC);
15506         std::swap(TrueC, FalseC);
15507         std::swap(TrueOp, FalseOp);
15508       }
15509
15510       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15511       // This is efficient for any integer data type (including i8/i16) and
15512       // shift amount.
15513       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15514         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15515                            DAG.getConstant(CC, MVT::i8), Cond);
15516
15517         // Zero extend the condition if needed.
15518         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15519
15520         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15521         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15522                            DAG.getConstant(ShAmt, MVT::i8));
15523         if (N->getNumValues() == 2)  // Dead flag value?
15524           return DCI.CombineTo(N, Cond, SDValue());
15525         return Cond;
15526       }
15527
15528       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15529       // for any integer data type, including i8/i16.
15530       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15531         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15532                            DAG.getConstant(CC, MVT::i8), Cond);
15533
15534         // Zero extend the condition if needed.
15535         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15536                            FalseC->getValueType(0), Cond);
15537         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15538                            SDValue(FalseC, 0));
15539
15540         if (N->getNumValues() == 2)  // Dead flag value?
15541           return DCI.CombineTo(N, Cond, SDValue());
15542         return Cond;
15543       }
15544
15545       // Optimize cases that will turn into an LEA instruction.  This requires
15546       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15547       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15548         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15549         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15550
15551         bool isFastMultiplier = false;
15552         if (Diff < 10) {
15553           switch ((unsigned char)Diff) {
15554           default: break;
15555           case 1:  // result = add base, cond
15556           case 2:  // result = lea base(    , cond*2)
15557           case 3:  // result = lea base(cond, cond*2)
15558           case 4:  // result = lea base(    , cond*4)
15559           case 5:  // result = lea base(cond, cond*4)
15560           case 8:  // result = lea base(    , cond*8)
15561           case 9:  // result = lea base(cond, cond*8)
15562             isFastMultiplier = true;
15563             break;
15564           }
15565         }
15566
15567         if (isFastMultiplier) {
15568           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15569           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15570                              DAG.getConstant(CC, MVT::i8), Cond);
15571           // Zero extend the condition if needed.
15572           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15573                              Cond);
15574           // Scale the condition by the difference.
15575           if (Diff != 1)
15576             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15577                                DAG.getConstant(Diff, Cond.getValueType()));
15578
15579           // Add the base if non-zero.
15580           if (FalseC->getAPIntValue() != 0)
15581             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15582                                SDValue(FalseC, 0));
15583           if (N->getNumValues() == 2)  // Dead flag value?
15584             return DCI.CombineTo(N, Cond, SDValue());
15585           return Cond;
15586         }
15587       }
15588     }
15589   }
15590
15591   // Handle these cases:
15592   //   (select (x != c), e, c) -> select (x != c), e, x),
15593   //   (select (x == c), c, e) -> select (x == c), x, e)
15594   // where the c is an integer constant, and the "select" is the combination
15595   // of CMOV and CMP.
15596   //
15597   // The rationale for this change is that the conditional-move from a constant
15598   // needs two instructions, however, conditional-move from a register needs
15599   // only one instruction.
15600   //
15601   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15602   //  some instruction-combining opportunities. This opt needs to be
15603   //  postponed as late as possible.
15604   //
15605   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15606     // the DCI.xxxx conditions are provided to postpone the optimization as
15607     // late as possible.
15608
15609     ConstantSDNode *CmpAgainst = 0;
15610     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15611         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15612         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15613
15614       if (CC == X86::COND_NE &&
15615           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15616         CC = X86::GetOppositeBranchCondition(CC);
15617         std::swap(TrueOp, FalseOp);
15618       }
15619
15620       if (CC == X86::COND_E &&
15621           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15622         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15623                           DAG.getConstant(CC, MVT::i8), Cond };
15624         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15625                            array_lengthof(Ops));
15626       }
15627     }
15628   }
15629
15630   return SDValue();
15631 }
15632
15633 /// PerformMulCombine - Optimize a single multiply with constant into two
15634 /// in order to implement it with two cheaper instructions, e.g.
15635 /// LEA + SHL, LEA + LEA.
15636 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15637                                  TargetLowering::DAGCombinerInfo &DCI) {
15638   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15639     return SDValue();
15640
15641   EVT VT = N->getValueType(0);
15642   if (VT != MVT::i64)
15643     return SDValue();
15644
15645   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15646   if (!C)
15647     return SDValue();
15648   uint64_t MulAmt = C->getZExtValue();
15649   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15650     return SDValue();
15651
15652   uint64_t MulAmt1 = 0;
15653   uint64_t MulAmt2 = 0;
15654   if ((MulAmt % 9) == 0) {
15655     MulAmt1 = 9;
15656     MulAmt2 = MulAmt / 9;
15657   } else if ((MulAmt % 5) == 0) {
15658     MulAmt1 = 5;
15659     MulAmt2 = MulAmt / 5;
15660   } else if ((MulAmt % 3) == 0) {
15661     MulAmt1 = 3;
15662     MulAmt2 = MulAmt / 3;
15663   }
15664   if (MulAmt2 &&
15665       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15666     DebugLoc DL = N->getDebugLoc();
15667
15668     if (isPowerOf2_64(MulAmt2) &&
15669         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15670       // If second multiplifer is pow2, issue it first. We want the multiply by
15671       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15672       // is an add.
15673       std::swap(MulAmt1, MulAmt2);
15674
15675     SDValue NewMul;
15676     if (isPowerOf2_64(MulAmt1))
15677       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15678                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15679     else
15680       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15681                            DAG.getConstant(MulAmt1, VT));
15682
15683     if (isPowerOf2_64(MulAmt2))
15684       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15685                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15686     else
15687       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15688                            DAG.getConstant(MulAmt2, VT));
15689
15690     // Do not add new nodes to DAG combiner worklist.
15691     DCI.CombineTo(N, NewMul, false);
15692   }
15693   return SDValue();
15694 }
15695
15696 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15697   SDValue N0 = N->getOperand(0);
15698   SDValue N1 = N->getOperand(1);
15699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15700   EVT VT = N0.getValueType();
15701
15702   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15703   // since the result of setcc_c is all zero's or all ones.
15704   if (VT.isInteger() && !VT.isVector() &&
15705       N1C && N0.getOpcode() == ISD::AND &&
15706       N0.getOperand(1).getOpcode() == ISD::Constant) {
15707     SDValue N00 = N0.getOperand(0);
15708     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15709         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15710           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15711          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15712       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15713       APInt ShAmt = N1C->getAPIntValue();
15714       Mask = Mask.shl(ShAmt);
15715       if (Mask != 0)
15716         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15717                            N00, DAG.getConstant(Mask, VT));
15718     }
15719   }
15720
15721   // Hardware support for vector shifts is sparse which makes us scalarize the
15722   // vector operations in many cases. Also, on sandybridge ADD is faster than
15723   // shl.
15724   // (shl V, 1) -> add V,V
15725   if (isSplatVector(N1.getNode())) {
15726     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15727     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15728     // We shift all of the values by one. In many cases we do not have
15729     // hardware support for this operation. This is better expressed as an ADD
15730     // of two values.
15731     if (N1C && (1 == N1C->getZExtValue())) {
15732       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15733     }
15734   }
15735
15736   return SDValue();
15737 }
15738
15739 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15740 ///                       when possible.
15741 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15742                                    TargetLowering::DAGCombinerInfo &DCI,
15743                                    const X86Subtarget *Subtarget) {
15744   EVT VT = N->getValueType(0);
15745   if (N->getOpcode() == ISD::SHL) {
15746     SDValue V = PerformSHLCombine(N, DAG);
15747     if (V.getNode()) return V;
15748   }
15749
15750   // On X86 with SSE2 support, we can transform this to a vector shift if
15751   // all elements are shifted by the same amount.  We can't do this in legalize
15752   // because the a constant vector is typically transformed to a constant pool
15753   // so we have no knowledge of the shift amount.
15754   if (!Subtarget->hasSSE2())
15755     return SDValue();
15756
15757   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15758       (!Subtarget->hasInt256() ||
15759        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15760     return SDValue();
15761
15762   SDValue ShAmtOp = N->getOperand(1);
15763   EVT EltVT = VT.getVectorElementType();
15764   DebugLoc DL = N->getDebugLoc();
15765   SDValue BaseShAmt = SDValue();
15766   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15767     unsigned NumElts = VT.getVectorNumElements();
15768     unsigned i = 0;
15769     for (; i != NumElts; ++i) {
15770       SDValue Arg = ShAmtOp.getOperand(i);
15771       if (Arg.getOpcode() == ISD::UNDEF) continue;
15772       BaseShAmt = Arg;
15773       break;
15774     }
15775     // Handle the case where the build_vector is all undef
15776     // FIXME: Should DAG allow this?
15777     if (i == NumElts)
15778       return SDValue();
15779
15780     for (; i != NumElts; ++i) {
15781       SDValue Arg = ShAmtOp.getOperand(i);
15782       if (Arg.getOpcode() == ISD::UNDEF) continue;
15783       if (Arg != BaseShAmt) {
15784         return SDValue();
15785       }
15786     }
15787   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15788              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15789     SDValue InVec = ShAmtOp.getOperand(0);
15790     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15791       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15792       unsigned i = 0;
15793       for (; i != NumElts; ++i) {
15794         SDValue Arg = InVec.getOperand(i);
15795         if (Arg.getOpcode() == ISD::UNDEF) continue;
15796         BaseShAmt = Arg;
15797         break;
15798       }
15799     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15800        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15801          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15802          if (C->getZExtValue() == SplatIdx)
15803            BaseShAmt = InVec.getOperand(1);
15804        }
15805     }
15806     if (BaseShAmt.getNode() == 0) {
15807       // Don't create instructions with illegal types after legalize
15808       // types has run.
15809       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15810           !DCI.isBeforeLegalize())
15811         return SDValue();
15812
15813       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15814                               DAG.getIntPtrConstant(0));
15815     }
15816   } else
15817     return SDValue();
15818
15819   // The shift amount is an i32.
15820   if (EltVT.bitsGT(MVT::i32))
15821     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15822   else if (EltVT.bitsLT(MVT::i32))
15823     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15824
15825   // The shift amount is identical so we can do a vector shift.
15826   SDValue  ValOp = N->getOperand(0);
15827   switch (N->getOpcode()) {
15828   default:
15829     llvm_unreachable("Unknown shift opcode!");
15830   case ISD::SHL:
15831     switch (VT.getSimpleVT().SimpleTy) {
15832     default: return SDValue();
15833     case MVT::v2i64:
15834     case MVT::v4i32:
15835     case MVT::v8i16:
15836     case MVT::v4i64:
15837     case MVT::v8i32:
15838     case MVT::v16i16:
15839       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15840     }
15841   case ISD::SRA:
15842     switch (VT.getSimpleVT().SimpleTy) {
15843     default: return SDValue();
15844     case MVT::v4i32:
15845     case MVT::v8i16:
15846     case MVT::v8i32:
15847     case MVT::v16i16:
15848       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15849     }
15850   case ISD::SRL:
15851     switch (VT.getSimpleVT().SimpleTy) {
15852     default: return SDValue();
15853     case MVT::v2i64:
15854     case MVT::v4i32:
15855     case MVT::v8i16:
15856     case MVT::v4i64:
15857     case MVT::v8i32:
15858     case MVT::v16i16:
15859       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15860     }
15861   }
15862 }
15863
15864 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15865 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15866 // and friends.  Likewise for OR -> CMPNEQSS.
15867 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15868                             TargetLowering::DAGCombinerInfo &DCI,
15869                             const X86Subtarget *Subtarget) {
15870   unsigned opcode;
15871
15872   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15873   // we're requiring SSE2 for both.
15874   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15875     SDValue N0 = N->getOperand(0);
15876     SDValue N1 = N->getOperand(1);
15877     SDValue CMP0 = N0->getOperand(1);
15878     SDValue CMP1 = N1->getOperand(1);
15879     DebugLoc DL = N->getDebugLoc();
15880
15881     // The SETCCs should both refer to the same CMP.
15882     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15883       return SDValue();
15884
15885     SDValue CMP00 = CMP0->getOperand(0);
15886     SDValue CMP01 = CMP0->getOperand(1);
15887     EVT     VT    = CMP00.getValueType();
15888
15889     if (VT == MVT::f32 || VT == MVT::f64) {
15890       bool ExpectingFlags = false;
15891       // Check for any users that want flags:
15892       for (SDNode::use_iterator UI = N->use_begin(),
15893              UE = N->use_end();
15894            !ExpectingFlags && UI != UE; ++UI)
15895         switch (UI->getOpcode()) {
15896         default:
15897         case ISD::BR_CC:
15898         case ISD::BRCOND:
15899         case ISD::SELECT:
15900           ExpectingFlags = true;
15901           break;
15902         case ISD::CopyToReg:
15903         case ISD::SIGN_EXTEND:
15904         case ISD::ZERO_EXTEND:
15905         case ISD::ANY_EXTEND:
15906           break;
15907         }
15908
15909       if (!ExpectingFlags) {
15910         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15911         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15912
15913         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15914           X86::CondCode tmp = cc0;
15915           cc0 = cc1;
15916           cc1 = tmp;
15917         }
15918
15919         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15920             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15921           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15922           X86ISD::NodeType NTOperator = is64BitFP ?
15923             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15924           // FIXME: need symbolic constants for these magic numbers.
15925           // See X86ATTInstPrinter.cpp:printSSECC().
15926           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15927           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15928                                               DAG.getConstant(x86cc, MVT::i8));
15929           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15930                                               OnesOrZeroesF);
15931           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15932                                       DAG.getConstant(1, MVT::i32));
15933           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15934           return OneBitOfTruth;
15935         }
15936       }
15937     }
15938   }
15939   return SDValue();
15940 }
15941
15942 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15943 /// so it can be folded inside ANDNP.
15944 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15945   EVT VT = N->getValueType(0);
15946
15947   // Match direct AllOnes for 128 and 256-bit vectors
15948   if (ISD::isBuildVectorAllOnes(N))
15949     return true;
15950
15951   // Look through a bit convert.
15952   if (N->getOpcode() == ISD::BITCAST)
15953     N = N->getOperand(0).getNode();
15954
15955   // Sometimes the operand may come from a insert_subvector building a 256-bit
15956   // allones vector
15957   if (VT.is256BitVector() &&
15958       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15959     SDValue V1 = N->getOperand(0);
15960     SDValue V2 = N->getOperand(1);
15961
15962     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15963         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15964         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15965         ISD::isBuildVectorAllOnes(V2.getNode()))
15966       return true;
15967   }
15968
15969   return false;
15970 }
15971
15972 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15973 // register. In most cases we actually compare or select YMM-sized registers
15974 // and mixing the two types creates horrible code. This method optimizes
15975 // some of the transition sequences.
15976 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15977                                  TargetLowering::DAGCombinerInfo &DCI,
15978                                  const X86Subtarget *Subtarget) {
15979   EVT VT = N->getValueType(0);
15980   if (!VT.is256BitVector())
15981     return SDValue();
15982
15983   assert((N->getOpcode() == ISD::ANY_EXTEND ||
15984           N->getOpcode() == ISD::ZERO_EXTEND ||
15985           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15986
15987   SDValue Narrow = N->getOperand(0);
15988   EVT NarrowVT = Narrow->getValueType(0);
15989   if (!NarrowVT.is128BitVector())
15990     return SDValue();
15991
15992   if (Narrow->getOpcode() != ISD::XOR &&
15993       Narrow->getOpcode() != ISD::AND &&
15994       Narrow->getOpcode() != ISD::OR)
15995     return SDValue();
15996
15997   SDValue N0  = Narrow->getOperand(0);
15998   SDValue N1  = Narrow->getOperand(1);
15999   DebugLoc DL = Narrow->getDebugLoc();
16000
16001   // The Left side has to be a trunc.
16002   if (N0.getOpcode() != ISD::TRUNCATE)
16003     return SDValue();
16004
16005   // The type of the truncated inputs.
16006   EVT WideVT = N0->getOperand(0)->getValueType(0);
16007   if (WideVT != VT)
16008     return SDValue();
16009
16010   // The right side has to be a 'trunc' or a constant vector.
16011   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16012   bool RHSConst = (isSplatVector(N1.getNode()) &&
16013                    isa<ConstantSDNode>(N1->getOperand(0)));
16014   if (!RHSTrunc && !RHSConst)
16015     return SDValue();
16016
16017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16018
16019   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16020     return SDValue();
16021
16022   // Set N0 and N1 to hold the inputs to the new wide operation.
16023   N0 = N0->getOperand(0);
16024   if (RHSConst) {
16025     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16026                      N1->getOperand(0));
16027     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16028     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16029   } else if (RHSTrunc) {
16030     N1 = N1->getOperand(0);
16031   }
16032
16033   // Generate the wide operation.
16034   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16035   unsigned Opcode = N->getOpcode();
16036   switch (Opcode) {
16037   case ISD::ANY_EXTEND:
16038     return Op;
16039   case ISD::ZERO_EXTEND: {
16040     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16041     APInt Mask = APInt::getAllOnesValue(InBits);
16042     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16043     return DAG.getNode(ISD::AND, DL, VT,
16044                        Op, DAG.getConstant(Mask, VT));
16045   }
16046   case ISD::SIGN_EXTEND:
16047     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16048                        Op, DAG.getValueType(NarrowVT));
16049   default:
16050     llvm_unreachable("Unexpected opcode");
16051   }
16052 }
16053
16054 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16055                                  TargetLowering::DAGCombinerInfo &DCI,
16056                                  const X86Subtarget *Subtarget) {
16057   EVT VT = N->getValueType(0);
16058   if (DCI.isBeforeLegalizeOps())
16059     return SDValue();
16060
16061   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16062   if (R.getNode())
16063     return R;
16064
16065   // Create BLSI, and BLSR instructions
16066   // BLSI is X & (-X)
16067   // BLSR is X & (X-1)
16068   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16069     SDValue N0 = N->getOperand(0);
16070     SDValue N1 = N->getOperand(1);
16071     DebugLoc DL = N->getDebugLoc();
16072
16073     // Check LHS for neg
16074     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16075         isZero(N0.getOperand(0)))
16076       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16077
16078     // Check RHS for neg
16079     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16080         isZero(N1.getOperand(0)))
16081       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16082
16083     // Check LHS for X-1
16084     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16085         isAllOnes(N0.getOperand(1)))
16086       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16087
16088     // Check RHS for X-1
16089     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16090         isAllOnes(N1.getOperand(1)))
16091       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16092
16093     return SDValue();
16094   }
16095
16096   // Want to form ANDNP nodes:
16097   // 1) In the hopes of then easily combining them with OR and AND nodes
16098   //    to form PBLEND/PSIGN.
16099   // 2) To match ANDN packed intrinsics
16100   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16101     return SDValue();
16102
16103   SDValue N0 = N->getOperand(0);
16104   SDValue N1 = N->getOperand(1);
16105   DebugLoc DL = N->getDebugLoc();
16106
16107   // Check LHS for vnot
16108   if (N0.getOpcode() == ISD::XOR &&
16109       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16110       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16111     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16112
16113   // Check RHS for vnot
16114   if (N1.getOpcode() == ISD::XOR &&
16115       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16116       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16117     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16118
16119   return SDValue();
16120 }
16121
16122 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16123                                 TargetLowering::DAGCombinerInfo &DCI,
16124                                 const X86Subtarget *Subtarget) {
16125   EVT VT = N->getValueType(0);
16126   if (DCI.isBeforeLegalizeOps())
16127     return SDValue();
16128
16129   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16130   if (R.getNode())
16131     return R;
16132
16133   SDValue N0 = N->getOperand(0);
16134   SDValue N1 = N->getOperand(1);
16135
16136   // look for psign/blend
16137   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16138     if (!Subtarget->hasSSSE3() ||
16139         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16140       return SDValue();
16141
16142     // Canonicalize pandn to RHS
16143     if (N0.getOpcode() == X86ISD::ANDNP)
16144       std::swap(N0, N1);
16145     // or (and (m, y), (pandn m, x))
16146     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16147       SDValue Mask = N1.getOperand(0);
16148       SDValue X    = N1.getOperand(1);
16149       SDValue Y;
16150       if (N0.getOperand(0) == Mask)
16151         Y = N0.getOperand(1);
16152       if (N0.getOperand(1) == Mask)
16153         Y = N0.getOperand(0);
16154
16155       // Check to see if the mask appeared in both the AND and ANDNP and
16156       if (!Y.getNode())
16157         return SDValue();
16158
16159       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16160       // Look through mask bitcast.
16161       if (Mask.getOpcode() == ISD::BITCAST)
16162         Mask = Mask.getOperand(0);
16163       if (X.getOpcode() == ISD::BITCAST)
16164         X = X.getOperand(0);
16165       if (Y.getOpcode() == ISD::BITCAST)
16166         Y = Y.getOperand(0);
16167
16168       EVT MaskVT = Mask.getValueType();
16169
16170       // Validate that the Mask operand is a vector sra node.
16171       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16172       // there is no psrai.b
16173       if (Mask.getOpcode() != X86ISD::VSRAI)
16174         return SDValue();
16175
16176       // Check that the SRA is all signbits.
16177       SDValue SraC = Mask.getOperand(1);
16178       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16179       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16180       if ((SraAmt + 1) != EltBits)
16181         return SDValue();
16182
16183       DebugLoc DL = N->getDebugLoc();
16184
16185       // We are going to replace the AND, OR, NAND with either BLEND
16186       // or PSIGN, which only look at the MSB. The VSRAI instruction
16187       // does not affect the highest bit, so we can get rid of it.
16188       Mask = Mask.getOperand(0);
16189
16190       // Now we know we at least have a plendvb with the mask val.  See if
16191       // we can form a psignb/w/d.
16192       // psign = x.type == y.type == mask.type && y = sub(0, x);
16193       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16194           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16195           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16196         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16197                "Unsupported VT for PSIGN");
16198         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16199         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16200       }
16201       // PBLENDVB only available on SSE 4.1
16202       if (!Subtarget->hasSSE41())
16203         return SDValue();
16204
16205       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16206
16207       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16208       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16209       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16210       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16211       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16212     }
16213   }
16214
16215   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16216     return SDValue();
16217
16218   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16219   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16220     std::swap(N0, N1);
16221   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16222     return SDValue();
16223   if (!N0.hasOneUse() || !N1.hasOneUse())
16224     return SDValue();
16225
16226   SDValue ShAmt0 = N0.getOperand(1);
16227   if (ShAmt0.getValueType() != MVT::i8)
16228     return SDValue();
16229   SDValue ShAmt1 = N1.getOperand(1);
16230   if (ShAmt1.getValueType() != MVT::i8)
16231     return SDValue();
16232   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16233     ShAmt0 = ShAmt0.getOperand(0);
16234   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16235     ShAmt1 = ShAmt1.getOperand(0);
16236
16237   DebugLoc DL = N->getDebugLoc();
16238   unsigned Opc = X86ISD::SHLD;
16239   SDValue Op0 = N0.getOperand(0);
16240   SDValue Op1 = N1.getOperand(0);
16241   if (ShAmt0.getOpcode() == ISD::SUB) {
16242     Opc = X86ISD::SHRD;
16243     std::swap(Op0, Op1);
16244     std::swap(ShAmt0, ShAmt1);
16245   }
16246
16247   unsigned Bits = VT.getSizeInBits();
16248   if (ShAmt1.getOpcode() == ISD::SUB) {
16249     SDValue Sum = ShAmt1.getOperand(0);
16250     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16251       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16252       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16253         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16254       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16255         return DAG.getNode(Opc, DL, VT,
16256                            Op0, Op1,
16257                            DAG.getNode(ISD::TRUNCATE, DL,
16258                                        MVT::i8, ShAmt0));
16259     }
16260   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16261     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16262     if (ShAmt0C &&
16263         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16264       return DAG.getNode(Opc, DL, VT,
16265                          N0.getOperand(0), N1.getOperand(0),
16266                          DAG.getNode(ISD::TRUNCATE, DL,
16267                                        MVT::i8, ShAmt0));
16268   }
16269
16270   return SDValue();
16271 }
16272
16273 // Generate NEG and CMOV for integer abs.
16274 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16275   EVT VT = N->getValueType(0);
16276
16277   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16278   // 8-bit integer abs to NEG and CMOV.
16279   if (VT.isInteger() && VT.getSizeInBits() == 8)
16280     return SDValue();
16281
16282   SDValue N0 = N->getOperand(0);
16283   SDValue N1 = N->getOperand(1);
16284   DebugLoc DL = N->getDebugLoc();
16285
16286   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16287   // and change it to SUB and CMOV.
16288   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16289       N0.getOpcode() == ISD::ADD &&
16290       N0.getOperand(1) == N1 &&
16291       N1.getOpcode() == ISD::SRA &&
16292       N1.getOperand(0) == N0.getOperand(0))
16293     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16294       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16295         // Generate SUB & CMOV.
16296         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16297                                   DAG.getConstant(0, VT), N0.getOperand(0));
16298
16299         SDValue Ops[] = { N0.getOperand(0), Neg,
16300                           DAG.getConstant(X86::COND_GE, MVT::i8),
16301                           SDValue(Neg.getNode(), 1) };
16302         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16303                            Ops, array_lengthof(Ops));
16304       }
16305   return SDValue();
16306 }
16307
16308 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16309 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16310                                  TargetLowering::DAGCombinerInfo &DCI,
16311                                  const X86Subtarget *Subtarget) {
16312   EVT VT = N->getValueType(0);
16313   if (DCI.isBeforeLegalizeOps())
16314     return SDValue();
16315
16316   if (Subtarget->hasCMov()) {
16317     SDValue RV = performIntegerAbsCombine(N, DAG);
16318     if (RV.getNode())
16319       return RV;
16320   }
16321
16322   // Try forming BMI if it is available.
16323   if (!Subtarget->hasBMI())
16324     return SDValue();
16325
16326   if (VT != MVT::i32 && VT != MVT::i64)
16327     return SDValue();
16328
16329   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16330
16331   // Create BLSMSK instructions by finding X ^ (X-1)
16332   SDValue N0 = N->getOperand(0);
16333   SDValue N1 = N->getOperand(1);
16334   DebugLoc DL = N->getDebugLoc();
16335
16336   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16337       isAllOnes(N0.getOperand(1)))
16338     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16339
16340   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16341       isAllOnes(N1.getOperand(1)))
16342     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16343
16344   return SDValue();
16345 }
16346
16347 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16348 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16349                                   TargetLowering::DAGCombinerInfo &DCI,
16350                                   const X86Subtarget *Subtarget) {
16351   LoadSDNode *Ld = cast<LoadSDNode>(N);
16352   EVT RegVT = Ld->getValueType(0);
16353   EVT MemVT = Ld->getMemoryVT();
16354   DebugLoc dl = Ld->getDebugLoc();
16355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16356   unsigned RegSz = RegVT.getSizeInBits();
16357
16358   ISD::LoadExtType Ext = Ld->getExtensionType();
16359   unsigned Alignment = Ld->getAlignment();
16360   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16361
16362   // On Sandybridge unaligned 256bit loads are inefficient.
16363   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16364       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16365     unsigned NumElems = RegVT.getVectorNumElements();
16366     if (NumElems < 2)
16367       return SDValue();
16368
16369     SDValue Ptr = Ld->getBasePtr();
16370     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16371
16372     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16373                                   NumElems/2);
16374     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16375                                 Ld->getPointerInfo(), Ld->isVolatile(),
16376                                 Ld->isNonTemporal(), Ld->isInvariant(),
16377                                 Alignment);
16378     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16379     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16380                                 Ld->getPointerInfo(), Ld->isVolatile(),
16381                                 Ld->isNonTemporal(), Ld->isInvariant(),
16382                                 std::max(Alignment/2U, 1U));
16383     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16384                              Load1.getValue(1),
16385                              Load2.getValue(1));
16386
16387     SDValue NewVec = DAG.getUNDEF(RegVT);
16388     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16389     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16390     return DCI.CombineTo(N, NewVec, TF, true);
16391   }
16392
16393   // If this is a vector EXT Load then attempt to optimize it using a
16394   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16395   // expansion is still better than scalar code.
16396   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16397   // emit a shuffle and a arithmetic shift.
16398   // TODO: It is possible to support ZExt by zeroing the undef values
16399   // during the shuffle phase or after the shuffle.
16400   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16401       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16402     assert(MemVT != RegVT && "Cannot extend to the same type");
16403     assert(MemVT.isVector() && "Must load a vector from memory");
16404
16405     unsigned NumElems = RegVT.getVectorNumElements();
16406     unsigned MemSz = MemVT.getSizeInBits();
16407     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16408
16409     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16410       return SDValue();
16411
16412     // All sizes must be a power of two.
16413     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16414       return SDValue();
16415
16416     // Attempt to load the original value using scalar loads.
16417     // Find the largest scalar type that divides the total loaded size.
16418     MVT SclrLoadTy = MVT::i8;
16419     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16420          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16421       MVT Tp = (MVT::SimpleValueType)tp;
16422       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16423         SclrLoadTy = Tp;
16424       }
16425     }
16426
16427     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16428     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16429         (64 <= MemSz))
16430       SclrLoadTy = MVT::f64;
16431
16432     // Calculate the number of scalar loads that we need to perform
16433     // in order to load our vector from memory.
16434     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16435     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16436       return SDValue();
16437
16438     unsigned loadRegZize = RegSz;
16439     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16440       loadRegZize /= 2;
16441
16442     // Represent our vector as a sequence of elements which are the
16443     // largest scalar that we can load.
16444     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16445       loadRegZize/SclrLoadTy.getSizeInBits());
16446
16447     // Represent the data using the same element type that is stored in
16448     // memory. In practice, we ''widen'' MemVT.
16449     EVT WideVecVT = 
16450           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16451                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16452
16453     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16454       "Invalid vector type");
16455
16456     // We can't shuffle using an illegal type.
16457     if (!TLI.isTypeLegal(WideVecVT))
16458       return SDValue();
16459
16460     SmallVector<SDValue, 8> Chains;
16461     SDValue Ptr = Ld->getBasePtr();
16462     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16463                                         TLI.getPointerTy());
16464     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16465
16466     for (unsigned i = 0; i < NumLoads; ++i) {
16467       // Perform a single load.
16468       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16469                                        Ptr, Ld->getPointerInfo(),
16470                                        Ld->isVolatile(), Ld->isNonTemporal(),
16471                                        Ld->isInvariant(), Ld->getAlignment());
16472       Chains.push_back(ScalarLoad.getValue(1));
16473       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16474       // another round of DAGCombining.
16475       if (i == 0)
16476         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16477       else
16478         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16479                           ScalarLoad, DAG.getIntPtrConstant(i));
16480
16481       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16482     }
16483
16484     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16485                                Chains.size());
16486
16487     // Bitcast the loaded value to a vector of the original element type, in
16488     // the size of the target vector type.
16489     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16490     unsigned SizeRatio = RegSz/MemSz;
16491
16492     if (Ext == ISD::SEXTLOAD) {
16493       // If we have SSE4.1 we can directly emit a VSEXT node.
16494       if (Subtarget->hasSSE41()) {
16495         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16496         return DCI.CombineTo(N, Sext, TF, true);
16497       }
16498
16499       // Otherwise we'll shuffle the small elements in the high bits of the
16500       // larger type and perform an arithmetic shift. If the shift is not legal
16501       // it's better to scalarize.
16502       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16503         return SDValue();
16504
16505       // Redistribute the loaded elements into the different locations.
16506       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16507       for (unsigned i = 0; i != NumElems; ++i)
16508         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16509
16510       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16511                                            DAG.getUNDEF(WideVecVT),
16512                                            &ShuffleVec[0]);
16513
16514       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16515
16516       // Build the arithmetic shift.
16517       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16518                      MemVT.getVectorElementType().getSizeInBits();
16519       SmallVector<SDValue, 8> C(NumElems,
16520                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16521       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16522       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16523
16524       return DCI.CombineTo(N, Shuff, TF, true);
16525     }
16526
16527     // Redistribute the loaded elements into the different locations.
16528     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16529     for (unsigned i = 0; i != NumElems; ++i)
16530       ShuffleVec[i*SizeRatio] = i;
16531
16532     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16533                                          DAG.getUNDEF(WideVecVT),
16534                                          &ShuffleVec[0]);
16535
16536     // Bitcast to the requested type.
16537     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16538     // Replace the original load with the new sequence
16539     // and return the new chain.
16540     return DCI.CombineTo(N, Shuff, TF, true);
16541   }
16542
16543   return SDValue();
16544 }
16545
16546 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16547 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16548                                    const X86Subtarget *Subtarget) {
16549   StoreSDNode *St = cast<StoreSDNode>(N);
16550   EVT VT = St->getValue().getValueType();
16551   EVT StVT = St->getMemoryVT();
16552   DebugLoc dl = St->getDebugLoc();
16553   SDValue StoredVal = St->getOperand(1);
16554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16555   unsigned Alignment = St->getAlignment();
16556   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16557
16558   // If we are saving a concatenation of two XMM registers, perform two stores.
16559   // On Sandy Bridge, 256-bit memory operations are executed by two
16560   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16561   // memory  operation.
16562   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16563       StVT == VT && !IsAligned) {
16564     unsigned NumElems = VT.getVectorNumElements();
16565     if (NumElems < 2)
16566       return SDValue();
16567
16568     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16569     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16570
16571     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16572     SDValue Ptr0 = St->getBasePtr();
16573     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16574
16575     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16576                                 St->getPointerInfo(), St->isVolatile(),
16577                                 St->isNonTemporal(), Alignment);
16578     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16579                                 St->getPointerInfo(), St->isVolatile(),
16580                                 St->isNonTemporal(),
16581                                 std::max(Alignment/2U, 1U));
16582     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16583   }
16584
16585   // Optimize trunc store (of multiple scalars) to shuffle and store.
16586   // First, pack all of the elements in one place. Next, store to memory
16587   // in fewer chunks.
16588   if (St->isTruncatingStore() && VT.isVector()) {
16589     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16590     unsigned NumElems = VT.getVectorNumElements();
16591     assert(StVT != VT && "Cannot truncate to the same type");
16592     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16593     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16594
16595     // From, To sizes and ElemCount must be pow of two
16596     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16597     // We are going to use the original vector elt for storing.
16598     // Accumulated smaller vector elements must be a multiple of the store size.
16599     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16600
16601     unsigned SizeRatio  = FromSz / ToSz;
16602
16603     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16604
16605     // Create a type on which we perform the shuffle
16606     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16607             StVT.getScalarType(), NumElems*SizeRatio);
16608
16609     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16610
16611     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16612     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16613     for (unsigned i = 0; i != NumElems; ++i)
16614       ShuffleVec[i] = i * SizeRatio;
16615
16616     // Can't shuffle using an illegal type.
16617     if (!TLI.isTypeLegal(WideVecVT))
16618       return SDValue();
16619
16620     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16621                                          DAG.getUNDEF(WideVecVT),
16622                                          &ShuffleVec[0]);
16623     // At this point all of the data is stored at the bottom of the
16624     // register. We now need to save it to mem.
16625
16626     // Find the largest store unit
16627     MVT StoreType = MVT::i8;
16628     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16629          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16630       MVT Tp = (MVT::SimpleValueType)tp;
16631       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16632         StoreType = Tp;
16633     }
16634
16635     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16636     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16637         (64 <= NumElems * ToSz))
16638       StoreType = MVT::f64;
16639
16640     // Bitcast the original vector into a vector of store-size units
16641     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16642             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16643     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16644     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16645     SmallVector<SDValue, 8> Chains;
16646     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16647                                         TLI.getPointerTy());
16648     SDValue Ptr = St->getBasePtr();
16649
16650     // Perform one or more big stores into memory.
16651     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16652       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16653                                    StoreType, ShuffWide,
16654                                    DAG.getIntPtrConstant(i));
16655       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16656                                 St->getPointerInfo(), St->isVolatile(),
16657                                 St->isNonTemporal(), St->getAlignment());
16658       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16659       Chains.push_back(Ch);
16660     }
16661
16662     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16663                                Chains.size());
16664   }
16665
16666   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16667   // the FP state in cases where an emms may be missing.
16668   // A preferable solution to the general problem is to figure out the right
16669   // places to insert EMMS.  This qualifies as a quick hack.
16670
16671   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16672   if (VT.getSizeInBits() != 64)
16673     return SDValue();
16674
16675   const Function *F = DAG.getMachineFunction().getFunction();
16676   bool NoImplicitFloatOps = F->getAttributes().
16677     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16678   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16679                      && Subtarget->hasSSE2();
16680   if ((VT.isVector() ||
16681        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16682       isa<LoadSDNode>(St->getValue()) &&
16683       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16684       St->getChain().hasOneUse() && !St->isVolatile()) {
16685     SDNode* LdVal = St->getValue().getNode();
16686     LoadSDNode *Ld = 0;
16687     int TokenFactorIndex = -1;
16688     SmallVector<SDValue, 8> Ops;
16689     SDNode* ChainVal = St->getChain().getNode();
16690     // Must be a store of a load.  We currently handle two cases:  the load
16691     // is a direct child, and it's under an intervening TokenFactor.  It is
16692     // possible to dig deeper under nested TokenFactors.
16693     if (ChainVal == LdVal)
16694       Ld = cast<LoadSDNode>(St->getChain());
16695     else if (St->getValue().hasOneUse() &&
16696              ChainVal->getOpcode() == ISD::TokenFactor) {
16697       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16698         if (ChainVal->getOperand(i).getNode() == LdVal) {
16699           TokenFactorIndex = i;
16700           Ld = cast<LoadSDNode>(St->getValue());
16701         } else
16702           Ops.push_back(ChainVal->getOperand(i));
16703       }
16704     }
16705
16706     if (!Ld || !ISD::isNormalLoad(Ld))
16707       return SDValue();
16708
16709     // If this is not the MMX case, i.e. we are just turning i64 load/store
16710     // into f64 load/store, avoid the transformation if there are multiple
16711     // uses of the loaded value.
16712     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16713       return SDValue();
16714
16715     DebugLoc LdDL = Ld->getDebugLoc();
16716     DebugLoc StDL = N->getDebugLoc();
16717     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16718     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16719     // pair instead.
16720     if (Subtarget->is64Bit() || F64IsLegal) {
16721       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16722       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16723                                   Ld->getPointerInfo(), Ld->isVolatile(),
16724                                   Ld->isNonTemporal(), Ld->isInvariant(),
16725                                   Ld->getAlignment());
16726       SDValue NewChain = NewLd.getValue(1);
16727       if (TokenFactorIndex != -1) {
16728         Ops.push_back(NewChain);
16729         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16730                                Ops.size());
16731       }
16732       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16733                           St->getPointerInfo(),
16734                           St->isVolatile(), St->isNonTemporal(),
16735                           St->getAlignment());
16736     }
16737
16738     // Otherwise, lower to two pairs of 32-bit loads / stores.
16739     SDValue LoAddr = Ld->getBasePtr();
16740     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16741                                  DAG.getConstant(4, MVT::i32));
16742
16743     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16744                                Ld->getPointerInfo(),
16745                                Ld->isVolatile(), Ld->isNonTemporal(),
16746                                Ld->isInvariant(), Ld->getAlignment());
16747     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16748                                Ld->getPointerInfo().getWithOffset(4),
16749                                Ld->isVolatile(), Ld->isNonTemporal(),
16750                                Ld->isInvariant(),
16751                                MinAlign(Ld->getAlignment(), 4));
16752
16753     SDValue NewChain = LoLd.getValue(1);
16754     if (TokenFactorIndex != -1) {
16755       Ops.push_back(LoLd);
16756       Ops.push_back(HiLd);
16757       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16758                              Ops.size());
16759     }
16760
16761     LoAddr = St->getBasePtr();
16762     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16763                          DAG.getConstant(4, MVT::i32));
16764
16765     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16766                                 St->getPointerInfo(),
16767                                 St->isVolatile(), St->isNonTemporal(),
16768                                 St->getAlignment());
16769     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16770                                 St->getPointerInfo().getWithOffset(4),
16771                                 St->isVolatile(),
16772                                 St->isNonTemporal(),
16773                                 MinAlign(St->getAlignment(), 4));
16774     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16775   }
16776   return SDValue();
16777 }
16778
16779 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16780 /// and return the operands for the horizontal operation in LHS and RHS.  A
16781 /// horizontal operation performs the binary operation on successive elements
16782 /// of its first operand, then on successive elements of its second operand,
16783 /// returning the resulting values in a vector.  For example, if
16784 ///   A = < float a0, float a1, float a2, float a3 >
16785 /// and
16786 ///   B = < float b0, float b1, float b2, float b3 >
16787 /// then the result of doing a horizontal operation on A and B is
16788 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16789 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16790 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16791 /// set to A, RHS to B, and the routine returns 'true'.
16792 /// Note that the binary operation should have the property that if one of the
16793 /// operands is UNDEF then the result is UNDEF.
16794 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16795   // Look for the following pattern: if
16796   //   A = < float a0, float a1, float a2, float a3 >
16797   //   B = < float b0, float b1, float b2, float b3 >
16798   // and
16799   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16800   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16801   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16802   // which is A horizontal-op B.
16803
16804   // At least one of the operands should be a vector shuffle.
16805   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16806       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16807     return false;
16808
16809   EVT VT = LHS.getValueType();
16810
16811   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16812          "Unsupported vector type for horizontal add/sub");
16813
16814   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16815   // operate independently on 128-bit lanes.
16816   unsigned NumElts = VT.getVectorNumElements();
16817   unsigned NumLanes = VT.getSizeInBits()/128;
16818   unsigned NumLaneElts = NumElts / NumLanes;
16819   assert((NumLaneElts % 2 == 0) &&
16820          "Vector type should have an even number of elements in each lane");
16821   unsigned HalfLaneElts = NumLaneElts/2;
16822
16823   // View LHS in the form
16824   //   LHS = VECTOR_SHUFFLE A, B, LMask
16825   // If LHS is not a shuffle then pretend it is the shuffle
16826   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16827   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16828   // type VT.
16829   SDValue A, B;
16830   SmallVector<int, 16> LMask(NumElts);
16831   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16832     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16833       A = LHS.getOperand(0);
16834     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16835       B = LHS.getOperand(1);
16836     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16837     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16838   } else {
16839     if (LHS.getOpcode() != ISD::UNDEF)
16840       A = LHS;
16841     for (unsigned i = 0; i != NumElts; ++i)
16842       LMask[i] = i;
16843   }
16844
16845   // Likewise, view RHS in the form
16846   //   RHS = VECTOR_SHUFFLE C, D, RMask
16847   SDValue C, D;
16848   SmallVector<int, 16> RMask(NumElts);
16849   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16850     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16851       C = RHS.getOperand(0);
16852     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16853       D = RHS.getOperand(1);
16854     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16855     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16856   } else {
16857     if (RHS.getOpcode() != ISD::UNDEF)
16858       C = RHS;
16859     for (unsigned i = 0; i != NumElts; ++i)
16860       RMask[i] = i;
16861   }
16862
16863   // Check that the shuffles are both shuffling the same vectors.
16864   if (!(A == C && B == D) && !(A == D && B == C))
16865     return false;
16866
16867   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16868   if (!A.getNode() && !B.getNode())
16869     return false;
16870
16871   // If A and B occur in reverse order in RHS, then "swap" them (which means
16872   // rewriting the mask).
16873   if (A != C)
16874     CommuteVectorShuffleMask(RMask, NumElts);
16875
16876   // At this point LHS and RHS are equivalent to
16877   //   LHS = VECTOR_SHUFFLE A, B, LMask
16878   //   RHS = VECTOR_SHUFFLE A, B, RMask
16879   // Check that the masks correspond to performing a horizontal operation.
16880   for (unsigned i = 0; i != NumElts; ++i) {
16881     int LIdx = LMask[i], RIdx = RMask[i];
16882
16883     // Ignore any UNDEF components.
16884     if (LIdx < 0 || RIdx < 0 ||
16885         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16886         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16887       continue;
16888
16889     // Check that successive elements are being operated on.  If not, this is
16890     // not a horizontal operation.
16891     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16892     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16893     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16894     if (!(LIdx == Index && RIdx == Index + 1) &&
16895         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16896       return false;
16897   }
16898
16899   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16900   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16901   return true;
16902 }
16903
16904 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16905 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16906                                   const X86Subtarget *Subtarget) {
16907   EVT VT = N->getValueType(0);
16908   SDValue LHS = N->getOperand(0);
16909   SDValue RHS = N->getOperand(1);
16910
16911   // Try to synthesize horizontal adds from adds of shuffles.
16912   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16913        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16914       isHorizontalBinOp(LHS, RHS, true))
16915     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16916   return SDValue();
16917 }
16918
16919 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16920 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16921                                   const X86Subtarget *Subtarget) {
16922   EVT VT = N->getValueType(0);
16923   SDValue LHS = N->getOperand(0);
16924   SDValue RHS = N->getOperand(1);
16925
16926   // Try to synthesize horizontal subs from subs of shuffles.
16927   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16928        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16929       isHorizontalBinOp(LHS, RHS, false))
16930     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16931   return SDValue();
16932 }
16933
16934 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16935 /// X86ISD::FXOR nodes.
16936 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16937   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16938   // F[X]OR(0.0, x) -> x
16939   // F[X]OR(x, 0.0) -> x
16940   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16941     if (C->getValueAPF().isPosZero())
16942       return N->getOperand(1);
16943   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16944     if (C->getValueAPF().isPosZero())
16945       return N->getOperand(0);
16946   return SDValue();
16947 }
16948
16949 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16950 /// X86ISD::FMAX nodes.
16951 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16952   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16953
16954   // Only perform optimizations if UnsafeMath is used.
16955   if (!DAG.getTarget().Options.UnsafeFPMath)
16956     return SDValue();
16957
16958   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16959   // into FMINC and FMAXC, which are Commutative operations.
16960   unsigned NewOp = 0;
16961   switch (N->getOpcode()) {
16962     default: llvm_unreachable("unknown opcode");
16963     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16964     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16965   }
16966
16967   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16968                      N->getOperand(0), N->getOperand(1));
16969 }
16970
16971 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16972 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16973   // FAND(0.0, x) -> 0.0
16974   // FAND(x, 0.0) -> 0.0
16975   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16976     if (C->getValueAPF().isPosZero())
16977       return N->getOperand(0);
16978   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16979     if (C->getValueAPF().isPosZero())
16980       return N->getOperand(1);
16981   return SDValue();
16982 }
16983
16984 static SDValue PerformBTCombine(SDNode *N,
16985                                 SelectionDAG &DAG,
16986                                 TargetLowering::DAGCombinerInfo &DCI) {
16987   // BT ignores high bits in the bit index operand.
16988   SDValue Op1 = N->getOperand(1);
16989   if (Op1.hasOneUse()) {
16990     unsigned BitWidth = Op1.getValueSizeInBits();
16991     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16992     APInt KnownZero, KnownOne;
16993     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16994                                           !DCI.isBeforeLegalizeOps());
16995     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16996     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16997         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16998       DCI.CommitTargetLoweringOpt(TLO);
16999   }
17000   return SDValue();
17001 }
17002
17003 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17004   SDValue Op = N->getOperand(0);
17005   if (Op.getOpcode() == ISD::BITCAST)
17006     Op = Op.getOperand(0);
17007   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17008   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17009       VT.getVectorElementType().getSizeInBits() ==
17010       OpVT.getVectorElementType().getSizeInBits()) {
17011     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17012   }
17013   return SDValue();
17014 }
17015
17016 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17017                                   TargetLowering::DAGCombinerInfo &DCI,
17018                                   const X86Subtarget *Subtarget) {
17019   if (!DCI.isBeforeLegalizeOps())
17020     return SDValue();
17021
17022   if (!Subtarget->hasFp256())
17023     return SDValue();
17024
17025   EVT VT = N->getValueType(0);
17026   if (VT.isVector() && VT.getSizeInBits() == 256) {
17027     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17028     if (R.getNode())
17029       return R;
17030   }
17031
17032   return SDValue();
17033 }
17034
17035 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17036                                  const X86Subtarget* Subtarget) {
17037   DebugLoc dl = N->getDebugLoc();
17038   EVT VT = N->getValueType(0);
17039
17040   // Let legalize expand this if it isn't a legal type yet.
17041   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17042     return SDValue();
17043
17044   EVT ScalarVT = VT.getScalarType();
17045   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17046       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17047     return SDValue();
17048
17049   SDValue A = N->getOperand(0);
17050   SDValue B = N->getOperand(1);
17051   SDValue C = N->getOperand(2);
17052
17053   bool NegA = (A.getOpcode() == ISD::FNEG);
17054   bool NegB = (B.getOpcode() == ISD::FNEG);
17055   bool NegC = (C.getOpcode() == ISD::FNEG);
17056
17057   // Negative multiplication when NegA xor NegB
17058   bool NegMul = (NegA != NegB);
17059   if (NegA)
17060     A = A.getOperand(0);
17061   if (NegB)
17062     B = B.getOperand(0);
17063   if (NegC)
17064     C = C.getOperand(0);
17065
17066   unsigned Opcode;
17067   if (!NegMul)
17068     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17069   else
17070     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17071
17072   return DAG.getNode(Opcode, dl, VT, A, B, C);
17073 }
17074
17075 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17076                                   TargetLowering::DAGCombinerInfo &DCI,
17077                                   const X86Subtarget *Subtarget) {
17078   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17079   //           (and (i32 x86isd::setcc_carry), 1)
17080   // This eliminates the zext. This transformation is necessary because
17081   // ISD::SETCC is always legalized to i8.
17082   DebugLoc dl = N->getDebugLoc();
17083   SDValue N0 = N->getOperand(0);
17084   EVT VT = N->getValueType(0);
17085
17086   if (N0.getOpcode() == ISD::AND &&
17087       N0.hasOneUse() &&
17088       N0.getOperand(0).hasOneUse()) {
17089     SDValue N00 = N0.getOperand(0);
17090     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17091       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17092       if (!C || C->getZExtValue() != 1)
17093         return SDValue();
17094       return DAG.getNode(ISD::AND, dl, VT,
17095                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17096                                      N00.getOperand(0), N00.getOperand(1)),
17097                          DAG.getConstant(1, VT));
17098     }
17099   }
17100
17101   if (VT.is256BitVector()) {
17102     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17103     if (R.getNode())
17104       return R;
17105   }
17106
17107   return SDValue();
17108 }
17109
17110 // Optimize x == -y --> x+y == 0
17111 //          x != -y --> x+y != 0
17112 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17113   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17114   SDValue LHS = N->getOperand(0);
17115   SDValue RHS = N->getOperand(1);
17116
17117   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17118     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17119       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17120         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17121                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17122         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17123                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17124       }
17125   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17127       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17128         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17129                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17130         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17131                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17132       }
17133   return SDValue();
17134 }
17135
17136 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
17137 // as "sbb reg,reg", since it can be extended without zext and produces 
17138 // an all-ones bit which is more useful than 0/1 in some cases.
17139 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17140   return DAG.getNode(ISD::AND, DL, MVT::i8,
17141                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17142                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17143                      DAG.getConstant(1, MVT::i8));
17144 }
17145
17146 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17147 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17148                                    TargetLowering::DAGCombinerInfo &DCI,
17149                                    const X86Subtarget *Subtarget) {
17150   DebugLoc DL = N->getDebugLoc();
17151   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17152   SDValue EFLAGS = N->getOperand(1);
17153
17154   if (CC == X86::COND_A) {
17155     // Try to convert COND_A into COND_B in an attempt to facilitate 
17156     // materializing "setb reg".
17157     //
17158     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17159     // cannot take an immediate as its first operand.
17160     //
17161     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
17162         EFLAGS.getValueType().isInteger() &&
17163         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17164       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17165                                    EFLAGS.getNode()->getVTList(),
17166                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17167       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17168       return MaterializeSETB(DL, NewEFLAGS, DAG);
17169     }
17170   }
17171
17172   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17173   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17174   // cases.
17175   if (CC == X86::COND_B)
17176     return MaterializeSETB(DL, EFLAGS, DAG);
17177
17178   SDValue Flags;
17179
17180   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17181   if (Flags.getNode()) {
17182     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17183     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17184   }
17185
17186   return SDValue();
17187 }
17188
17189 // Optimize branch condition evaluation.
17190 //
17191 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17192                                     TargetLowering::DAGCombinerInfo &DCI,
17193                                     const X86Subtarget *Subtarget) {
17194   DebugLoc DL = N->getDebugLoc();
17195   SDValue Chain = N->getOperand(0);
17196   SDValue Dest = N->getOperand(1);
17197   SDValue EFLAGS = N->getOperand(3);
17198   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17199
17200   SDValue Flags;
17201
17202   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17203   if (Flags.getNode()) {
17204     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17205     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17206                        Flags);
17207   }
17208
17209   return SDValue();
17210 }
17211
17212 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17213                                         const X86TargetLowering *XTLI) {
17214   SDValue Op0 = N->getOperand(0);
17215   EVT InVT = Op0->getValueType(0);
17216
17217   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17218   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17219     DebugLoc dl = N->getDebugLoc();
17220     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17221     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17222     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17223   }
17224
17225   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17226   // a 32-bit target where SSE doesn't support i64->FP operations.
17227   if (Op0.getOpcode() == ISD::LOAD) {
17228     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17229     EVT VT = Ld->getValueType(0);
17230     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17231         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17232         !XTLI->getSubtarget()->is64Bit() &&
17233         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17234       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17235                                           Ld->getChain(), Op0, DAG);
17236       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17237       return FILDChain;
17238     }
17239   }
17240   return SDValue();
17241 }
17242
17243 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17244 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17245                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17246   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17247   // the result is either zero or one (depending on the input carry bit).
17248   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17249   if (X86::isZeroNode(N->getOperand(0)) &&
17250       X86::isZeroNode(N->getOperand(1)) &&
17251       // We don't have a good way to replace an EFLAGS use, so only do this when
17252       // dead right now.
17253       SDValue(N, 1).use_empty()) {
17254     DebugLoc DL = N->getDebugLoc();
17255     EVT VT = N->getValueType(0);
17256     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17257     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17258                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17259                                            DAG.getConstant(X86::COND_B,MVT::i8),
17260                                            N->getOperand(2)),
17261                                DAG.getConstant(1, VT));
17262     return DCI.CombineTo(N, Res1, CarryOut);
17263   }
17264
17265   return SDValue();
17266 }
17267
17268 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17269 //      (add Y, (setne X, 0)) -> sbb -1, Y
17270 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17271 //      (sub (setne X, 0), Y) -> adc -1, Y
17272 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17273   DebugLoc DL = N->getDebugLoc();
17274
17275   // Look through ZExts.
17276   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17277   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17278     return SDValue();
17279
17280   SDValue SetCC = Ext.getOperand(0);
17281   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17282     return SDValue();
17283
17284   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17285   if (CC != X86::COND_E && CC != X86::COND_NE)
17286     return SDValue();
17287
17288   SDValue Cmp = SetCC.getOperand(1);
17289   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17290       !X86::isZeroNode(Cmp.getOperand(1)) ||
17291       !Cmp.getOperand(0).getValueType().isInteger())
17292     return SDValue();
17293
17294   SDValue CmpOp0 = Cmp.getOperand(0);
17295   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17296                                DAG.getConstant(1, CmpOp0.getValueType()));
17297
17298   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17299   if (CC == X86::COND_NE)
17300     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17301                        DL, OtherVal.getValueType(), OtherVal,
17302                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17303   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17304                      DL, OtherVal.getValueType(), OtherVal,
17305                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17306 }
17307
17308 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17309 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17310                                  const X86Subtarget *Subtarget) {
17311   EVT VT = N->getValueType(0);
17312   SDValue Op0 = N->getOperand(0);
17313   SDValue Op1 = N->getOperand(1);
17314
17315   // Try to synthesize horizontal adds from adds of shuffles.
17316   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17317        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17318       isHorizontalBinOp(Op0, Op1, true))
17319     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17320
17321   return OptimizeConditionalInDecrement(N, DAG);
17322 }
17323
17324 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17325                                  const X86Subtarget *Subtarget) {
17326   SDValue Op0 = N->getOperand(0);
17327   SDValue Op1 = N->getOperand(1);
17328
17329   // X86 can't encode an immediate LHS of a sub. See if we can push the
17330   // negation into a preceding instruction.
17331   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17332     // If the RHS of the sub is a XOR with one use and a constant, invert the
17333     // immediate. Then add one to the LHS of the sub so we can turn
17334     // X-Y -> X+~Y+1, saving one register.
17335     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17336         isa<ConstantSDNode>(Op1.getOperand(1))) {
17337       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17338       EVT VT = Op0.getValueType();
17339       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17340                                    Op1.getOperand(0),
17341                                    DAG.getConstant(~XorC, VT));
17342       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17343                          DAG.getConstant(C->getAPIntValue()+1, VT));
17344     }
17345   }
17346
17347   // Try to synthesize horizontal adds from adds of shuffles.
17348   EVT VT = N->getValueType(0);
17349   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17350        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17351       isHorizontalBinOp(Op0, Op1, true))
17352     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17353
17354   return OptimizeConditionalInDecrement(N, DAG);
17355 }
17356
17357 /// performVZEXTCombine - Performs build vector combines
17358 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17359                                         TargetLowering::DAGCombinerInfo &DCI,
17360                                         const X86Subtarget *Subtarget) {
17361   // (vzext (bitcast (vzext (x)) -> (vzext x)
17362   SDValue In = N->getOperand(0);
17363   while (In.getOpcode() == ISD::BITCAST)
17364     In = In.getOperand(0);
17365
17366   if (In.getOpcode() != X86ISD::VZEXT)
17367     return SDValue();
17368
17369   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17370 }
17371
17372 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17373                                              DAGCombinerInfo &DCI) const {
17374   SelectionDAG &DAG = DCI.DAG;
17375   switch (N->getOpcode()) {
17376   default: break;
17377   case ISD::EXTRACT_VECTOR_ELT:
17378     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17379   case ISD::VSELECT:
17380   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17381   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17382   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17383   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17384   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17385   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17386   case ISD::SHL:
17387   case ISD::SRA:
17388   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17389   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17390   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17391   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17392   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17393   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17394   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17395   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17396   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17397   case X86ISD::FXOR:
17398   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17399   case X86ISD::FMIN:
17400   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17401   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17402   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17403   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17404   case ISD::ANY_EXTEND:
17405   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17406   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17407   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17408   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17409   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17410   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17411   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17412   case X86ISD::SHUFP:       // Handle all target specific shuffles
17413   case X86ISD::PALIGN:
17414   case X86ISD::UNPCKH:
17415   case X86ISD::UNPCKL:
17416   case X86ISD::MOVHLPS:
17417   case X86ISD::MOVLHPS:
17418   case X86ISD::PSHUFD:
17419   case X86ISD::PSHUFHW:
17420   case X86ISD::PSHUFLW:
17421   case X86ISD::MOVSS:
17422   case X86ISD::MOVSD:
17423   case X86ISD::VPERMILP:
17424   case X86ISD::VPERM2X128:
17425   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17426   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17427   }
17428
17429   return SDValue();
17430 }
17431
17432 /// isTypeDesirableForOp - Return true if the target has native support for
17433 /// the specified value type and it is 'desirable' to use the type for the
17434 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17435 /// instruction encodings are longer and some i16 instructions are slow.
17436 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17437   if (!isTypeLegal(VT))
17438     return false;
17439   if (VT != MVT::i16)
17440     return true;
17441
17442   switch (Opc) {
17443   default:
17444     return true;
17445   case ISD::LOAD:
17446   case ISD::SIGN_EXTEND:
17447   case ISD::ZERO_EXTEND:
17448   case ISD::ANY_EXTEND:
17449   case ISD::SHL:
17450   case ISD::SRL:
17451   case ISD::SUB:
17452   case ISD::ADD:
17453   case ISD::MUL:
17454   case ISD::AND:
17455   case ISD::OR:
17456   case ISD::XOR:
17457     return false;
17458   }
17459 }
17460
17461 /// IsDesirableToPromoteOp - This method query the target whether it is
17462 /// beneficial for dag combiner to promote the specified node. If true, it
17463 /// should return the desired promotion type by reference.
17464 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17465   EVT VT = Op.getValueType();
17466   if (VT != MVT::i16)
17467     return false;
17468
17469   bool Promote = false;
17470   bool Commute = false;
17471   switch (Op.getOpcode()) {
17472   default: break;
17473   case ISD::LOAD: {
17474     LoadSDNode *LD = cast<LoadSDNode>(Op);
17475     // If the non-extending load has a single use and it's not live out, then it
17476     // might be folded.
17477     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17478                                                      Op.hasOneUse()*/) {
17479       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17480              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17481         // The only case where we'd want to promote LOAD (rather then it being
17482         // promoted as an operand is when it's only use is liveout.
17483         if (UI->getOpcode() != ISD::CopyToReg)
17484           return false;
17485       }
17486     }
17487     Promote = true;
17488     break;
17489   }
17490   case ISD::SIGN_EXTEND:
17491   case ISD::ZERO_EXTEND:
17492   case ISD::ANY_EXTEND:
17493     Promote = true;
17494     break;
17495   case ISD::SHL:
17496   case ISD::SRL: {
17497     SDValue N0 = Op.getOperand(0);
17498     // Look out for (store (shl (load), x)).
17499     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17500       return false;
17501     Promote = true;
17502     break;
17503   }
17504   case ISD::ADD:
17505   case ISD::MUL:
17506   case ISD::AND:
17507   case ISD::OR:
17508   case ISD::XOR:
17509     Commute = true;
17510     // fallthrough
17511   case ISD::SUB: {
17512     SDValue N0 = Op.getOperand(0);
17513     SDValue N1 = Op.getOperand(1);
17514     if (!Commute && MayFoldLoad(N1))
17515       return false;
17516     // Avoid disabling potential load folding opportunities.
17517     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17518       return false;
17519     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17520       return false;
17521     Promote = true;
17522   }
17523   }
17524
17525   PVT = MVT::i32;
17526   return Promote;
17527 }
17528
17529 //===----------------------------------------------------------------------===//
17530 //                           X86 Inline Assembly Support
17531 //===----------------------------------------------------------------------===//
17532
17533 namespace {
17534   // Helper to match a string separated by whitespace.
17535   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17536     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17537
17538     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17539       StringRef piece(*args[i]);
17540       if (!s.startswith(piece)) // Check if the piece matches.
17541         return false;
17542
17543       s = s.substr(piece.size());
17544       StringRef::size_type pos = s.find_first_not_of(" \t");
17545       if (pos == 0) // We matched a prefix.
17546         return false;
17547
17548       s = s.substr(pos);
17549     }
17550
17551     return s.empty();
17552   }
17553   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17554 }
17555
17556 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17557   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17558
17559   std::string AsmStr = IA->getAsmString();
17560
17561   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17562   if (!Ty || Ty->getBitWidth() % 16 != 0)
17563     return false;
17564
17565   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17566   SmallVector<StringRef, 4> AsmPieces;
17567   SplitString(AsmStr, AsmPieces, ";\n");
17568
17569   switch (AsmPieces.size()) {
17570   default: return false;
17571   case 1:
17572     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17573     // we will turn this bswap into something that will be lowered to logical
17574     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17575     // lower so don't worry about this.
17576     // bswap $0
17577     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17578         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17579         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17580         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17581         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17582         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17583       // No need to check constraints, nothing other than the equivalent of
17584       // "=r,0" would be valid here.
17585       return IntrinsicLowering::LowerToByteSwap(CI);
17586     }
17587
17588     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17589     if (CI->getType()->isIntegerTy(16) &&
17590         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17591         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17592          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17593       AsmPieces.clear();
17594       const std::string &ConstraintsStr = IA->getConstraintString();
17595       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17596       std::sort(AsmPieces.begin(), AsmPieces.end());
17597       if (AsmPieces.size() == 4 &&
17598           AsmPieces[0] == "~{cc}" &&
17599           AsmPieces[1] == "~{dirflag}" &&
17600           AsmPieces[2] == "~{flags}" &&
17601           AsmPieces[3] == "~{fpsr}")
17602       return IntrinsicLowering::LowerToByteSwap(CI);
17603     }
17604     break;
17605   case 3:
17606     if (CI->getType()->isIntegerTy(32) &&
17607         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17608         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17609         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17610         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17611       AsmPieces.clear();
17612       const std::string &ConstraintsStr = IA->getConstraintString();
17613       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17614       std::sort(AsmPieces.begin(), AsmPieces.end());
17615       if (AsmPieces.size() == 4 &&
17616           AsmPieces[0] == "~{cc}" &&
17617           AsmPieces[1] == "~{dirflag}" &&
17618           AsmPieces[2] == "~{flags}" &&
17619           AsmPieces[3] == "~{fpsr}")
17620         return IntrinsicLowering::LowerToByteSwap(CI);
17621     }
17622
17623     if (CI->getType()->isIntegerTy(64)) {
17624       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17625       if (Constraints.size() >= 2 &&
17626           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17627           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17628         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17629         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17630             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17631             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17632           return IntrinsicLowering::LowerToByteSwap(CI);
17633       }
17634     }
17635     break;
17636   }
17637   return false;
17638 }
17639
17640 /// getConstraintType - Given a constraint letter, return the type of
17641 /// constraint it is for this target.
17642 X86TargetLowering::ConstraintType
17643 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17644   if (Constraint.size() == 1) {
17645     switch (Constraint[0]) {
17646     case 'R':
17647     case 'q':
17648     case 'Q':
17649     case 'f':
17650     case 't':
17651     case 'u':
17652     case 'y':
17653     case 'x':
17654     case 'Y':
17655     case 'l':
17656       return C_RegisterClass;
17657     case 'a':
17658     case 'b':
17659     case 'c':
17660     case 'd':
17661     case 'S':
17662     case 'D':
17663     case 'A':
17664       return C_Register;
17665     case 'I':
17666     case 'J':
17667     case 'K':
17668     case 'L':
17669     case 'M':
17670     case 'N':
17671     case 'G':
17672     case 'C':
17673     case 'e':
17674     case 'Z':
17675       return C_Other;
17676     default:
17677       break;
17678     }
17679   }
17680   return TargetLowering::getConstraintType(Constraint);
17681 }
17682
17683 /// Examine constraint type and operand type and determine a weight value.
17684 /// This object must already have been set up with the operand type
17685 /// and the current alternative constraint selected.
17686 TargetLowering::ConstraintWeight
17687   X86TargetLowering::getSingleConstraintMatchWeight(
17688     AsmOperandInfo &info, const char *constraint) const {
17689   ConstraintWeight weight = CW_Invalid;
17690   Value *CallOperandVal = info.CallOperandVal;
17691     // If we don't have a value, we can't do a match,
17692     // but allow it at the lowest weight.
17693   if (CallOperandVal == NULL)
17694     return CW_Default;
17695   Type *type = CallOperandVal->getType();
17696   // Look at the constraint type.
17697   switch (*constraint) {
17698   default:
17699     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17700   case 'R':
17701   case 'q':
17702   case 'Q':
17703   case 'a':
17704   case 'b':
17705   case 'c':
17706   case 'd':
17707   case 'S':
17708   case 'D':
17709   case 'A':
17710     if (CallOperandVal->getType()->isIntegerTy())
17711       weight = CW_SpecificReg;
17712     break;
17713   case 'f':
17714   case 't':
17715   case 'u':
17716     if (type->isFloatingPointTy())
17717       weight = CW_SpecificReg;
17718     break;
17719   case 'y':
17720     if (type->isX86_MMXTy() && Subtarget->hasMMX())
17721       weight = CW_SpecificReg;
17722     break;
17723   case 'x':
17724   case 'Y':
17725     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17726         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17727       weight = CW_Register;
17728     break;
17729   case 'I':
17730     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17731       if (C->getZExtValue() <= 31)
17732         weight = CW_Constant;
17733     }
17734     break;
17735   case 'J':
17736     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17737       if (C->getZExtValue() <= 63)
17738         weight = CW_Constant;
17739     }
17740     break;
17741   case 'K':
17742     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17743       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17744         weight = CW_Constant;
17745     }
17746     break;
17747   case 'L':
17748     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17749       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17750         weight = CW_Constant;
17751     }
17752     break;
17753   case 'M':
17754     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17755       if (C->getZExtValue() <= 3)
17756         weight = CW_Constant;
17757     }
17758     break;
17759   case 'N':
17760     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17761       if (C->getZExtValue() <= 0xff)
17762         weight = CW_Constant;
17763     }
17764     break;
17765   case 'G':
17766   case 'C':
17767     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17768       weight = CW_Constant;
17769     }
17770     break;
17771   case 'e':
17772     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17773       if ((C->getSExtValue() >= -0x80000000LL) &&
17774           (C->getSExtValue() <= 0x7fffffffLL))
17775         weight = CW_Constant;
17776     }
17777     break;
17778   case 'Z':
17779     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17780       if (C->getZExtValue() <= 0xffffffff)
17781         weight = CW_Constant;
17782     }
17783     break;
17784   }
17785   return weight;
17786 }
17787
17788 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17789 /// with another that has more specific requirements based on the type of the
17790 /// corresponding operand.
17791 const char *X86TargetLowering::
17792 LowerXConstraint(EVT ConstraintVT) const {
17793   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17794   // 'f' like normal targets.
17795   if (ConstraintVT.isFloatingPoint()) {
17796     if (Subtarget->hasSSE2())
17797       return "Y";
17798     if (Subtarget->hasSSE1())
17799       return "x";
17800   }
17801
17802   return TargetLowering::LowerXConstraint(ConstraintVT);
17803 }
17804
17805 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17806 /// vector.  If it is invalid, don't add anything to Ops.
17807 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17808                                                      std::string &Constraint,
17809                                                      std::vector<SDValue>&Ops,
17810                                                      SelectionDAG &DAG) const {
17811   SDValue Result(0, 0);
17812
17813   // Only support length 1 constraints for now.
17814   if (Constraint.length() > 1) return;
17815
17816   char ConstraintLetter = Constraint[0];
17817   switch (ConstraintLetter) {
17818   default: break;
17819   case 'I':
17820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17821       if (C->getZExtValue() <= 31) {
17822         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17823         break;
17824       }
17825     }
17826     return;
17827   case 'J':
17828     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17829       if (C->getZExtValue() <= 63) {
17830         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17831         break;
17832       }
17833     }
17834     return;
17835   case 'K':
17836     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17837       if (isInt<8>(C->getSExtValue())) {
17838         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17839         break;
17840       }
17841     }
17842     return;
17843   case 'N':
17844     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17845       if (C->getZExtValue() <= 255) {
17846         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17847         break;
17848       }
17849     }
17850     return;
17851   case 'e': {
17852     // 32-bit signed value
17853     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17854       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17855                                            C->getSExtValue())) {
17856         // Widen to 64 bits here to get it sign extended.
17857         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17858         break;
17859       }
17860     // FIXME gcc accepts some relocatable values here too, but only in certain
17861     // memory models; it's complicated.
17862     }
17863     return;
17864   }
17865   case 'Z': {
17866     // 32-bit unsigned value
17867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17868       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17869                                            C->getZExtValue())) {
17870         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17871         break;
17872       }
17873     }
17874     // FIXME gcc accepts some relocatable values here too, but only in certain
17875     // memory models; it's complicated.
17876     return;
17877   }
17878   case 'i': {
17879     // Literal immediates are always ok.
17880     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17881       // Widen to 64 bits here to get it sign extended.
17882       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17883       break;
17884     }
17885
17886     // In any sort of PIC mode addresses need to be computed at runtime by
17887     // adding in a register or some sort of table lookup.  These can't
17888     // be used as immediates.
17889     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17890       return;
17891
17892     // If we are in non-pic codegen mode, we allow the address of a global (with
17893     // an optional displacement) to be used with 'i'.
17894     GlobalAddressSDNode *GA = 0;
17895     int64_t Offset = 0;
17896
17897     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17898     while (1) {
17899       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17900         Offset += GA->getOffset();
17901         break;
17902       } else if (Op.getOpcode() == ISD::ADD) {
17903         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17904           Offset += C->getZExtValue();
17905           Op = Op.getOperand(0);
17906           continue;
17907         }
17908       } else if (Op.getOpcode() == ISD::SUB) {
17909         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17910           Offset += -C->getZExtValue();
17911           Op = Op.getOperand(0);
17912           continue;
17913         }
17914       }
17915
17916       // Otherwise, this isn't something we can handle, reject it.
17917       return;
17918     }
17919
17920     const GlobalValue *GV = GA->getGlobal();
17921     // If we require an extra load to get this address, as in PIC mode, we
17922     // can't accept it.
17923     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17924                                                         getTargetMachine())))
17925       return;
17926
17927     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17928                                         GA->getValueType(0), Offset);
17929     break;
17930   }
17931   }
17932
17933   if (Result.getNode()) {
17934     Ops.push_back(Result);
17935     return;
17936   }
17937   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17938 }
17939
17940 std::pair<unsigned, const TargetRegisterClass*>
17941 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17942                                                 EVT VT) const {
17943   // First, see if this is a constraint that directly corresponds to an LLVM
17944   // register class.
17945   if (Constraint.size() == 1) {
17946     // GCC Constraint Letters
17947     switch (Constraint[0]) {
17948     default: break;
17949       // TODO: Slight differences here in allocation order and leaving
17950       // RIP in the class. Do they matter any more here than they do
17951       // in the normal allocation?
17952     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17953       if (Subtarget->is64Bit()) {
17954         if (VT == MVT::i32 || VT == MVT::f32)
17955           return std::make_pair(0U, &X86::GR32RegClass);
17956         if (VT == MVT::i16)
17957           return std::make_pair(0U, &X86::GR16RegClass);
17958         if (VT == MVT::i8 || VT == MVT::i1)
17959           return std::make_pair(0U, &X86::GR8RegClass);
17960         if (VT == MVT::i64 || VT == MVT::f64)
17961           return std::make_pair(0U, &X86::GR64RegClass);
17962         break;
17963       }
17964       // 32-bit fallthrough
17965     case 'Q':   // Q_REGS
17966       if (VT == MVT::i32 || VT == MVT::f32)
17967         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17968       if (VT == MVT::i16)
17969         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17970       if (VT == MVT::i8 || VT == MVT::i1)
17971         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17972       if (VT == MVT::i64)
17973         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17974       break;
17975     case 'r':   // GENERAL_REGS
17976     case 'l':   // INDEX_REGS
17977       if (VT == MVT::i8 || VT == MVT::i1)
17978         return std::make_pair(0U, &X86::GR8RegClass);
17979       if (VT == MVT::i16)
17980         return std::make_pair(0U, &X86::GR16RegClass);
17981       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17982         return std::make_pair(0U, &X86::GR32RegClass);
17983       return std::make_pair(0U, &X86::GR64RegClass);
17984     case 'R':   // LEGACY_REGS
17985       if (VT == MVT::i8 || VT == MVT::i1)
17986         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17987       if (VT == MVT::i16)
17988         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17989       if (VT == MVT::i32 || !Subtarget->is64Bit())
17990         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17991       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17992     case 'f':  // FP Stack registers.
17993       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17994       // value to the correct fpstack register class.
17995       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17996         return std::make_pair(0U, &X86::RFP32RegClass);
17997       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17998         return std::make_pair(0U, &X86::RFP64RegClass);
17999       return std::make_pair(0U, &X86::RFP80RegClass);
18000     case 'y':   // MMX_REGS if MMX allowed.
18001       if (!Subtarget->hasMMX()) break;
18002       return std::make_pair(0U, &X86::VR64RegClass);
18003     case 'Y':   // SSE_REGS if SSE2 allowed
18004       if (!Subtarget->hasSSE2()) break;
18005       // FALL THROUGH.
18006     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18007       if (!Subtarget->hasSSE1()) break;
18008
18009       switch (VT.getSimpleVT().SimpleTy) {
18010       default: break;
18011       // Scalar SSE types.
18012       case MVT::f32:
18013       case MVT::i32:
18014         return std::make_pair(0U, &X86::FR32RegClass);
18015       case MVT::f64:
18016       case MVT::i64:
18017         return std::make_pair(0U, &X86::FR64RegClass);
18018       // Vector types.
18019       case MVT::v16i8:
18020       case MVT::v8i16:
18021       case MVT::v4i32:
18022       case MVT::v2i64:
18023       case MVT::v4f32:
18024       case MVT::v2f64:
18025         return std::make_pair(0U, &X86::VR128RegClass);
18026       // AVX types.
18027       case MVT::v32i8:
18028       case MVT::v16i16:
18029       case MVT::v8i32:
18030       case MVT::v4i64:
18031       case MVT::v8f32:
18032       case MVT::v4f64:
18033         return std::make_pair(0U, &X86::VR256RegClass);
18034       }
18035       break;
18036     }
18037   }
18038
18039   // Use the default implementation in TargetLowering to convert the register
18040   // constraint into a member of a register class.
18041   std::pair<unsigned, const TargetRegisterClass*> Res;
18042   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18043
18044   // Not found as a standard register?
18045   if (Res.second == 0) {
18046     // Map st(0) -> st(7) -> ST0
18047     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18048         tolower(Constraint[1]) == 's' &&
18049         tolower(Constraint[2]) == 't' &&
18050         Constraint[3] == '(' &&
18051         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18052         Constraint[5] == ')' &&
18053         Constraint[6] == '}') {
18054
18055       Res.first = X86::ST0+Constraint[4]-'0';
18056       Res.second = &X86::RFP80RegClass;
18057       return Res;
18058     }
18059
18060     // GCC allows "st(0)" to be called just plain "st".
18061     if (StringRef("{st}").equals_lower(Constraint)) {
18062       Res.first = X86::ST0;
18063       Res.second = &X86::RFP80RegClass;
18064       return Res;
18065     }
18066
18067     // flags -> EFLAGS
18068     if (StringRef("{flags}").equals_lower(Constraint)) {
18069       Res.first = X86::EFLAGS;
18070       Res.second = &X86::CCRRegClass;
18071       return Res;
18072     }
18073
18074     // 'A' means EAX + EDX.
18075     if (Constraint == "A") {
18076       Res.first = X86::EAX;
18077       Res.second = &X86::GR32_ADRegClass;
18078       return Res;
18079     }
18080     return Res;
18081   }
18082
18083   // Otherwise, check to see if this is a register class of the wrong value
18084   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18085   // turn into {ax},{dx}.
18086   if (Res.second->hasType(VT))
18087     return Res;   // Correct type already, nothing to do.
18088
18089   // All of the single-register GCC register classes map their values onto
18090   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18091   // really want an 8-bit or 32-bit register, map to the appropriate register
18092   // class and return the appropriate register.
18093   if (Res.second == &X86::GR16RegClass) {
18094     if (VT == MVT::i8) {
18095       unsigned DestReg = 0;
18096       switch (Res.first) {
18097       default: break;
18098       case X86::AX: DestReg = X86::AL; break;
18099       case X86::DX: DestReg = X86::DL; break;
18100       case X86::CX: DestReg = X86::CL; break;
18101       case X86::BX: DestReg = X86::BL; break;
18102       }
18103       if (DestReg) {
18104         Res.first = DestReg;
18105         Res.second = &X86::GR8RegClass;
18106       }
18107     } else if (VT == MVT::i32) {
18108       unsigned DestReg = 0;
18109       switch (Res.first) {
18110       default: break;
18111       case X86::AX: DestReg = X86::EAX; break;
18112       case X86::DX: DestReg = X86::EDX; break;
18113       case X86::CX: DestReg = X86::ECX; break;
18114       case X86::BX: DestReg = X86::EBX; break;
18115       case X86::SI: DestReg = X86::ESI; break;
18116       case X86::DI: DestReg = X86::EDI; break;
18117       case X86::BP: DestReg = X86::EBP; break;
18118       case X86::SP: DestReg = X86::ESP; break;
18119       }
18120       if (DestReg) {
18121         Res.first = DestReg;
18122         Res.second = &X86::GR32RegClass;
18123       }
18124     } else if (VT == MVT::i64) {
18125       unsigned DestReg = 0;
18126       switch (Res.first) {
18127       default: break;
18128       case X86::AX: DestReg = X86::RAX; break;
18129       case X86::DX: DestReg = X86::RDX; break;
18130       case X86::CX: DestReg = X86::RCX; break;
18131       case X86::BX: DestReg = X86::RBX; break;
18132       case X86::SI: DestReg = X86::RSI; break;
18133       case X86::DI: DestReg = X86::RDI; break;
18134       case X86::BP: DestReg = X86::RBP; break;
18135       case X86::SP: DestReg = X86::RSP; break;
18136       }
18137       if (DestReg) {
18138         Res.first = DestReg;
18139         Res.second = &X86::GR64RegClass;
18140       }
18141     }
18142   } else if (Res.second == &X86::FR32RegClass ||
18143              Res.second == &X86::FR64RegClass ||
18144              Res.second == &X86::VR128RegClass) {
18145     // Handle references to XMM physical registers that got mapped into the
18146     // wrong class.  This can happen with constraints like {xmm0} where the
18147     // target independent register mapper will just pick the first match it can
18148     // find, ignoring the required type.
18149
18150     if (VT == MVT::f32 || VT == MVT::i32)
18151       Res.second = &X86::FR32RegClass;
18152     else if (VT == MVT::f64 || VT == MVT::i64)
18153       Res.second = &X86::FR64RegClass;
18154     else if (X86::VR128RegClass.hasType(VT))
18155       Res.second = &X86::VR128RegClass;
18156     else if (X86::VR256RegClass.hasType(VT))
18157       Res.second = &X86::VR256RegClass;
18158   }
18159
18160   return Res;
18161 }