X86: Don't call malloc for 4 bits. No functionality change.
[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 "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <bitset>
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 static cl::opt<bool> UseRegMask("x86-use-regmask",
61                                 cl::desc("Use register masks for x86 calls"));
62
63 // Forward declarations.
64 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65                        SDValue V2);
66
67 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
68 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
69 /// simple subregister reference.  Idx is an index in the 128 bits we
70 /// want.  It need not be aligned to a 128-bit bounday.  That makes
71 /// lowering EXTRACT_VECTOR_ELT operations easier.
72 static SDValue Extract128BitVector(SDValue Vec,
73                                    SDValue Idx,
74                                    SelectionDAG &DAG,
75                                    DebugLoc dl) {
76   EVT VT = Vec.getValueType();
77   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
78   EVT ElVT = VT.getVectorElementType();
79   int Factor = VT.getSizeInBits()/128;
80   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
81                                   VT.getVectorNumElements()/Factor);
82
83   // Extract from UNDEF is UNDEF.
84   if (Vec.getOpcode() == ISD::UNDEF)
85     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
86
87   if (isa<ConstantSDNode>(Idx)) {
88     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
89
90     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
91     // we can match to VEXTRACTF128.
92     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
93
94     // This is the index of the first element of the 128-bit chunk
95     // we want.
96     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
97                                  * ElemsPerChunk);
98
99     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
100     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
101                                  VecIdx);
102
103     return Result;
104   }
105
106   return SDValue();
107 }
108
109 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
110 /// sets things up to match to an AVX VINSERTF128 instruction or a
111 /// simple superregister reference.  Idx is an index in the 128 bits
112 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
113 /// lowering INSERT_VECTOR_ELT operations easier.
114 static SDValue Insert128BitVector(SDValue Result,
115                                   SDValue Vec,
116                                   SDValue Idx,
117                                   SelectionDAG &DAG,
118                                   DebugLoc dl) {
119   if (isa<ConstantSDNode>(Idx)) {
120     EVT VT = Vec.getValueType();
121     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
122
123     EVT ElVT = VT.getVectorElementType();
124     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
125     EVT ResultVT = Result.getValueType();
126
127     // Insert the relevant 128 bits.
128     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
129
130     // This is the index of the first element of the 128-bit chunk
131     // we want.
132     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
133                                  * ElemsPerChunk);
134
135     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
136     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
137                          VecIdx);
138     return Result;
139   }
140
141   return SDValue();
142 }
143
144 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
145   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
146   bool is64Bit = Subtarget->is64Bit();
147
148   if (Subtarget->isTargetEnvMacho()) {
149     if (is64Bit)
150       return new X8664_MachoTargetObjectFile();
151     return new TargetLoweringObjectFileMachO();
152   }
153
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
167
168   RegInfo = TM.getRegisterInfo();
169   TD = getTargetData();
170
171   // Set up the TargetLowering object.
172   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
173
174   // X86 is weird, it always uses i8 for shift amounts and setcc results.
175   setBooleanContents(ZeroOrOneBooleanContent);
176   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
177   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
178
179   // For 64-bit since we have so many registers use the ILP scheduler, for
180   // 32-bit code use the register pressure specific scheduling.
181   // For 32 bit Atom, use Hybrid (register pressure + latency) scheduling.
182   if (Subtarget->is64Bit())
183     setSchedulingPreference(Sched::ILP);
184   else if (Subtarget->isAtom()) 
185     setSchedulingPreference(Sched::Hybrid);
186   else
187     setSchedulingPreference(Sched::RegPressure);
188   setStackPointerRegisterToSaveRestore(X86StackPtr);
189
190   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
191     // Setup Windows compiler runtime calls.
192     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
193     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
194     setLibcallName(RTLIB::SREM_I64, "_allrem");
195     setLibcallName(RTLIB::UREM_I64, "_aullrem");
196     setLibcallName(RTLIB::MUL_I64, "_allmul");
197     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
198     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
199     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
201     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
202     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
203     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
205     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
206   }
207
208   if (Subtarget->isTargetDarwin()) {
209     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
210     setUseUnderscoreSetJmp(false);
211     setUseUnderscoreLongJmp(false);
212   } else if (Subtarget->isTargetMingw()) {
213     // MS runtime is weird: it exports _setjmp, but longjmp!
214     setUseUnderscoreSetJmp(true);
215     setUseUnderscoreLongJmp(false);
216   } else {
217     setUseUnderscoreSetJmp(true);
218     setUseUnderscoreLongJmp(true);
219   }
220
221   // Set up the register classes.
222   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
223   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
224   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
225   if (Subtarget->is64Bit())
226     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
227
228   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
229
230   // We don't accept any truncstore of integer registers.
231   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
232   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
233   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
234   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
237
238   // SETOEQ and SETUNE require checking two conditions.
239   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
240   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
241   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
242   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
243   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
245
246   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
247   // operation.
248   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
249   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
251
252   if (Subtarget->is64Bit()) {
253     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
254     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
255   } else if (!TM.Options.UseSoftFloat) {
256     // We have an algorithm for SSE2->double, and we turn this into a
257     // 64-bit FILD followed by conditional FADD for other targets.
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
259     // We have an algorithm for SSE2, and we turn this into a 64-bit
260     // FILD for other targets.
261     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
262   }
263
264   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
265   // this operation.
266   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
267   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
268
269   if (!TM.Options.UseSoftFloat) {
270     // SSE has no i16 to fp conversion, only i32
271     if (X86ScalarSSEf32) {
272       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
273       // f32 and f64 cases are Legal, f80 case is not
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
275     } else {
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
278     }
279   } else {
280     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
281     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
282   }
283
284   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
285   // are Legal, f80 is custom lowered.
286   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
287   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
288
289   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
290   // this operation.
291   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
292   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
293
294   if (X86ScalarSSEf32) {
295     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
296     // f32 and f64 cases are Legal, f80 case is not
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
298   } else {
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
301   }
302
303   // Handle FP_TO_UINT by promoting the destination to a larger signed
304   // conversion.
305   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
306   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
308
309   if (Subtarget->is64Bit()) {
310     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
311     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
312   } else if (!TM.Options.UseSoftFloat) {
313     // Since AVX is a superset of SSE3, only check for SSE here.
314     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
315       // Expand FP_TO_UINT into a select.
316       // FIXME: We would like to use a Custom expander here eventually to do
317       // the optimal thing for SSE vs. the default expansion in the legalizer.
318       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
319     else
320       // With SSE3 we can use fisttpll to convert to a signed i64; without
321       // SSE, we're stuck with a fistpll.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
323   }
324
325   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
326   if (!X86ScalarSSEf64) {
327     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
328     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
329     if (Subtarget->is64Bit()) {
330       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
331       // Without SSE, i64->f64 goes through memory.
332       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
333     }
334   }
335
336   // Scalar integer divide and remainder are lowered to use operations that
337   // produce two results, to match the available instructions. This exposes
338   // the two-result form to trivial CSE, which is able to combine x/y and x%y
339   // into a single instruction.
340   //
341   // Scalar integer multiply-high is also lowered to use two-result
342   // operations, to match the available instructions. However, plain multiply
343   // (low) operations are left as Legal, as there are single-result
344   // instructions for this in x86. Using the two-result multiply instructions
345   // when both high and low results are needed must be arranged by dagcombine.
346   for (unsigned i = 0, e = 4; i != e; ++i) {
347     MVT VT = IntVTs[i];
348     setOperationAction(ISD::MULHS, VT, Expand);
349     setOperationAction(ISD::MULHU, VT, Expand);
350     setOperationAction(ISD::SDIV, VT, Expand);
351     setOperationAction(ISD::UDIV, VT, Expand);
352     setOperationAction(ISD::SREM, VT, Expand);
353     setOperationAction(ISD::UREM, VT, Expand);
354
355     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
356     setOperationAction(ISD::ADDC, VT, Custom);
357     setOperationAction(ISD::ADDE, VT, Custom);
358     setOperationAction(ISD::SUBC, VT, Custom);
359     setOperationAction(ISD::SUBE, VT, Custom);
360   }
361
362   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
363   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
364   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
365   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
366   if (Subtarget->is64Bit())
367     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
368   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
369   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
370   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
371   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
372   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
373   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
374   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
375   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
376
377   // Promote the i8 variants and force them on up to i32 which has a shorter
378   // encoding.
379   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
380   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
381   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
382   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
383   if (Subtarget->hasBMI()) {
384     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
385     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
386     if (Subtarget->is64Bit())
387       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
388   } else {
389     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
390     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
391     if (Subtarget->is64Bit())
392       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
393   }
394
395   if (Subtarget->hasLZCNT()) {
396     // When promoting the i8 variants, force them to i32 for a shorter
397     // encoding.
398     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
399     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
401     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
402     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
403     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
404     if (Subtarget->is64Bit())
405       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
406   } else {
407     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
408     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
409     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
412     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
413     if (Subtarget->is64Bit()) {
414       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
415       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
416     }
417   }
418
419   if (Subtarget->hasPOPCNT()) {
420     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
421   } else {
422     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
423     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
424     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
425     if (Subtarget->is64Bit())
426       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
427   }
428
429   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
430   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
431
432   // These should be promoted to a larger select which is supported.
433   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
434   // X86 wants to expand cmov itself.
435   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
436   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
439   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
442   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
449     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
450   }
451   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
452
453   // Darwin ABI issue.
454   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
455   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
456   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
457   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
458   if (Subtarget->is64Bit())
459     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
460   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
461   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
462   if (Subtarget->is64Bit()) {
463     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
464     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
465     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
466     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
467     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
468   }
469   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
470   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
471   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
472   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
473   if (Subtarget->is64Bit()) {
474     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
475     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
476     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
477   }
478
479   if (Subtarget->hasSSE1())
480     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
481
482   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
483   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
484
485   // On X86 and X86-64, atomic operations are lowered to locked instructions.
486   // Locked instructions, in turn, have implicit fence semantics (all memory
487   // operations are flushed before issuing the locked instruction, and they
488   // are not buffered), so we can fold away the common pattern of
489   // fence-atomic-fence.
490   setShouldFoldAtomicFences(true);
491
492   // Expand certain atomics
493   for (unsigned i = 0, e = 4; i != e; ++i) {
494     MVT VT = IntVTs[i];
495     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
496     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
497     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
498   }
499
500   if (!Subtarget->is64Bit()) {
501     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
509   }
510
511   if (Subtarget->hasCmpxchg16b()) {
512     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
537   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
538
539   setOperationAction(ISD::TRAP, MVT::Other, Legal);
540
541   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
542   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
543   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
544   if (Subtarget->is64Bit()) {
545     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
546     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
547   } else {
548     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
549     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
550   }
551
552   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
553   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
554
555   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
556     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
557                        MVT::i64 : MVT::i32, Custom);
558   else if (TM.Options.EnableSegmentedStacks)
559     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560                        MVT::i64 : MVT::i32, Custom);
561   else
562     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
563                        MVT::i64 : MVT::i32, Expand);
564
565   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
566     // f32 and f64 use SSE.
567     // Set up the FP register classes.
568     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
569     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
570
571     // Use ANDPD to simulate FABS.
572     setOperationAction(ISD::FABS , MVT::f64, Custom);
573     setOperationAction(ISD::FABS , MVT::f32, Custom);
574
575     // Use XORP to simulate FNEG.
576     setOperationAction(ISD::FNEG , MVT::f64, Custom);
577     setOperationAction(ISD::FNEG , MVT::f32, Custom);
578
579     // Use ANDPD and ORPD to simulate FCOPYSIGN.
580     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
581     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
582
583     // Lower this to FGETSIGNx86 plus an AND.
584     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
585     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
586
587     // We don't support sin/cos/fmod
588     setOperationAction(ISD::FSIN , MVT::f64, Expand);
589     setOperationAction(ISD::FCOS , MVT::f64, Expand);
590     setOperationAction(ISD::FSIN , MVT::f32, Expand);
591     setOperationAction(ISD::FCOS , MVT::f32, Expand);
592
593     // Expand FP immediates into loads from the stack, except for the special
594     // cases we handle.
595     addLegalFPImmediate(APFloat(+0.0)); // xorpd
596     addLegalFPImmediate(APFloat(+0.0f)); // xorps
597   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
598     // Use SSE for f32, x87 for f64.
599     // Set up the FP register classes.
600     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
601     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
602
603     // Use ANDPS to simulate FABS.
604     setOperationAction(ISD::FABS , MVT::f32, Custom);
605
606     // Use XORP to simulate FNEG.
607     setOperationAction(ISD::FNEG , MVT::f32, Custom);
608
609     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
610
611     // Use ANDPS and ORPS to simulate FCOPYSIGN.
612     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
614
615     // We don't support sin/cos/fmod
616     setOperationAction(ISD::FSIN , MVT::f32, Expand);
617     setOperationAction(ISD::FCOS , MVT::f32, Expand);
618
619     // Special cases we handle for FP constants.
620     addLegalFPImmediate(APFloat(+0.0f)); // xorps
621     addLegalFPImmediate(APFloat(+0.0)); // FLD0
622     addLegalFPImmediate(APFloat(+1.0)); // FLD1
623     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
624     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
625
626     if (!TM.Options.UnsafeFPMath) {
627       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
628       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
629     }
630   } else if (!TM.Options.UseSoftFloat) {
631     // f32 and f64 in x87.
632     // Set up the FP register classes.
633     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
634     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
635
636     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
637     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
638     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
640
641     if (!TM.Options.UnsafeFPMath) {
642       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
643       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
644     }
645     addLegalFPImmediate(APFloat(+0.0)); // FLD0
646     addLegalFPImmediate(APFloat(+1.0)); // FLD1
647     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
648     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
649     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
653   }
654
655   // We don't support FMA.
656   setOperationAction(ISD::FMA, MVT::f64, Expand);
657   setOperationAction(ISD::FMA, MVT::f32, Expand);
658
659   // Long double always uses X87.
660   if (!TM.Options.UseSoftFloat) {
661     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
662     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
663     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
664     {
665       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
666       addLegalFPImmediate(TmpFlt);  // FLD0
667       TmpFlt.changeSign();
668       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
669
670       bool ignored;
671       APFloat TmpFlt2(+1.0);
672       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
673                       &ignored);
674       addLegalFPImmediate(TmpFlt2);  // FLD1
675       TmpFlt2.changeSign();
676       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
677     }
678
679     if (!TM.Options.UnsafeFPMath) {
680       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
681       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
682     }
683
684     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
685     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
686     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
687     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
688     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
689     setOperationAction(ISD::FMA, MVT::f80, Expand);
690   }
691
692   // Always use a library call for pow.
693   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
694   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
695   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
696
697   setOperationAction(ISD::FLOG, MVT::f80, Expand);
698   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
699   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
700   setOperationAction(ISD::FEXP, MVT::f80, Expand);
701   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
702
703   // First set operation action for all vector types to either promote
704   // (for widening) or expand (for scalarization). Then we will selectively
705   // turn on ones that can be effectively codegen'd.
706   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
707        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
708     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
725     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
726     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
760     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
765     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
766          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
767       setTruncStoreAction((MVT::SimpleValueType)VT,
768                           (MVT::SimpleValueType)InnerVT, Expand);
769     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
770     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
771     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
772   }
773
774   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
775   // with -msoft-float, disable use of MMX as well.
776   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
777     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
778     // No operations on x86mmx supported, everything uses intrinsics.
779   }
780
781   // MMX-sized vectors (other than x86mmx) are expected to be expanded
782   // into smaller operations.
783   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
784   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
785   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
786   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
787   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
788   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
789   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
790   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
791   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
792   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
793   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
794   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
795   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
796   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
797   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
798   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
800   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
801   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
802   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
803   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
805   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
806   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
807   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
809   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
810   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
811   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
812
813   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
814     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
822     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
823     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
824     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
825     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
826     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
828   }
829
830   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
831     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
832
833     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
834     // registers cannot be used even for integer operations.
835     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
836     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
837     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
838     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
839
840     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
841     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
842     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
843     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
844     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
845     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
846     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
847     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
848     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
849     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
850     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
852     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
853     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
854     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
855     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
856
857     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
858     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
859     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
860     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
861
862     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
863     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
865     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
866     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
867
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
870     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
871     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
872     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
873
874     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
875     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
876       EVT VT = (MVT::SimpleValueType)i;
877       // Do not attempt to custom lower non-power-of-2 vectors
878       if (!isPowerOf2_32(VT.getVectorNumElements()))
879         continue;
880       // Do not attempt to custom lower non-128-bit vectors
881       if (!VT.is128BitVector())
882         continue;
883       setOperationAction(ISD::BUILD_VECTOR,
884                          VT.getSimpleVT().SimpleTy, Custom);
885       setOperationAction(ISD::VECTOR_SHUFFLE,
886                          VT.getSimpleVT().SimpleTy, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
888                          VT.getSimpleVT().SimpleTy, Custom);
889     }
890
891     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
892     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
893     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
895     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
896     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
897
898     if (Subtarget->is64Bit()) {
899       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
900       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
901     }
902
903     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
904     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
905       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
906       EVT VT = SVT;
907
908       // Do not attempt to promote non-128-bit vectors
909       if (!VT.is128BitVector())
910         continue;
911
912       setOperationAction(ISD::AND,    SVT, Promote);
913       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
914       setOperationAction(ISD::OR,     SVT, Promote);
915       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
916       setOperationAction(ISD::XOR,    SVT, Promote);
917       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
918       setOperationAction(ISD::LOAD,   SVT, Promote);
919       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
920       setOperationAction(ISD::SELECT, SVT, Promote);
921       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
922     }
923
924     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
925
926     // Custom lower v2i64 and v2f64 selects.
927     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
928     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
929     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
930     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
931
932     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
933     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
934   }
935
936   if (Subtarget->hasSSE41()) {
937     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
938     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
939     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
940     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
941     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
942     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
943     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
944     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
945     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
946     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
947
948     // FIXME: Do we need to handle scalar-to-vector here?
949     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
950
951     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
954     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
956
957     // i8 and i16 vectors are custom , because the source register and source
958     // source memory operand types are not the same width.  f32 vectors are
959     // custom since the immediate controlling the insert encodes additional
960     // information.
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
965
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
968     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
970
971     // FIXME: these should be Legal but thats only for the case where
972     // the index is constant.  For now custom expand to deal with that.
973     if (Subtarget->is64Bit()) {
974       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
976     }
977   }
978
979   if (Subtarget->hasSSE2()) {
980     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
981     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
982
983     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
985
986     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
988
989     if (Subtarget->hasAVX2()) {
990       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
991       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
992
993       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
994       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
995
996       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
997     } else {
998       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
999       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1000
1001       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1002       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1003
1004       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1005     }
1006   }
1007
1008   if (Subtarget->hasSSE42())
1009     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1010
1011   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1012     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
1013     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1014     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
1015     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
1016     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
1017     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
1018
1019     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1022
1023     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1026     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1028     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1029
1030     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1033     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1035     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1036
1037     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1038     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1039     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1040
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1045     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1046     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1047
1048     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1049     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1050
1051     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1052     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1053
1054     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1055     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1056
1057     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1059     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1060     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1061
1062     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1063     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1064     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1065
1066     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1068     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1069     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1070
1071     if (Subtarget->hasAVX2()) {
1072       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1074       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1075       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1076
1077       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1079       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1080       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1081
1082       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1083       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1084       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1085       // Don't lower v32i8 because there is no 128-bit byte mul
1086
1087       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1088
1089       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1090       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1091
1092       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1093       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1094
1095       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1096     } else {
1097       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1099       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1100       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1101
1102       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1104       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1105       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1106
1107       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1108       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1109       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1110       // Don't lower v32i8 because there is no 128-bit byte mul
1111
1112       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1113       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1114
1115       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1117
1118       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1119     }
1120
1121     // Custom lower several nodes for 256-bit types.
1122     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1123                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1124       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1125       EVT VT = SVT;
1126
1127       // Extract subvector is special because the value type
1128       // (result) is 128-bit but the source is 256-bit wide.
1129       if (VT.is128BitVector())
1130         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1131
1132       // Do not attempt to custom lower other non-256-bit vectors
1133       if (!VT.is256BitVector())
1134         continue;
1135
1136       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1137       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1138       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1139       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1140       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1141       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1142     }
1143
1144     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1145     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1146       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1147       EVT VT = SVT;
1148
1149       // Do not attempt to promote non-256-bit vectors
1150       if (!VT.is256BitVector())
1151         continue;
1152
1153       setOperationAction(ISD::AND,    SVT, Promote);
1154       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1155       setOperationAction(ISD::OR,     SVT, Promote);
1156       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1157       setOperationAction(ISD::XOR,    SVT, Promote);
1158       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1159       setOperationAction(ISD::LOAD,   SVT, Promote);
1160       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1161       setOperationAction(ISD::SELECT, SVT, Promote);
1162       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1163     }
1164   }
1165
1166   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1167   // of this type with custom code.
1168   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1169          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1170     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1171                        Custom);
1172   }
1173
1174   // We want to custom lower some of our intrinsics.
1175   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1176
1177
1178   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1179   // handle type legalization for these operations here.
1180   //
1181   // FIXME: We really should do custom legalization for addition and
1182   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1183   // than generic legalization for 64-bit multiplication-with-overflow, though.
1184   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1185     // Add/Sub/Mul with overflow operations are custom lowered.
1186     MVT VT = IntVTs[i];
1187     setOperationAction(ISD::SADDO, VT, Custom);
1188     setOperationAction(ISD::UADDO, VT, Custom);
1189     setOperationAction(ISD::SSUBO, VT, Custom);
1190     setOperationAction(ISD::USUBO, VT, Custom);
1191     setOperationAction(ISD::SMULO, VT, Custom);
1192     setOperationAction(ISD::UMULO, VT, Custom);
1193   }
1194
1195   // There are no 8-bit 3-address imul/mul instructions
1196   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1197   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1198
1199   if (!Subtarget->is64Bit()) {
1200     // These libcalls are not available in 32-bit.
1201     setLibcallName(RTLIB::SHL_I128, 0);
1202     setLibcallName(RTLIB::SRL_I128, 0);
1203     setLibcallName(RTLIB::SRA_I128, 0);
1204   }
1205
1206   // We have target-specific dag combine patterns for the following nodes:
1207   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1208   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1209   setTargetDAGCombine(ISD::VSELECT);
1210   setTargetDAGCombine(ISD::SELECT);
1211   setTargetDAGCombine(ISD::SHL);
1212   setTargetDAGCombine(ISD::SRA);
1213   setTargetDAGCombine(ISD::SRL);
1214   setTargetDAGCombine(ISD::OR);
1215   setTargetDAGCombine(ISD::AND);
1216   setTargetDAGCombine(ISD::ADD);
1217   setTargetDAGCombine(ISD::FADD);
1218   setTargetDAGCombine(ISD::FSUB);
1219   setTargetDAGCombine(ISD::SUB);
1220   setTargetDAGCombine(ISD::LOAD);
1221   setTargetDAGCombine(ISD::STORE);
1222   setTargetDAGCombine(ISD::ZERO_EXTEND);
1223   setTargetDAGCombine(ISD::SIGN_EXTEND);
1224   setTargetDAGCombine(ISD::TRUNCATE);
1225   setTargetDAGCombine(ISD::SINT_TO_FP);
1226   if (Subtarget->is64Bit())
1227     setTargetDAGCombine(ISD::MUL);
1228   if (Subtarget->hasBMI())
1229     setTargetDAGCombine(ISD::XOR);
1230
1231   computeRegisterProperties();
1232
1233   // On Darwin, -Os means optimize for size without hurting performance,
1234   // do not reduce the limit.
1235   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1236   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1237   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1238   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1239   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1240   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1241   setPrefLoopAlignment(4); // 2^4 bytes.
1242   benefitFromCodePlacementOpt = true;
1243
1244   setPrefFunctionAlignment(4); // 2^4 bytes.
1245 }
1246
1247
1248 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1249   if (!VT.isVector()) return MVT::i8;
1250   return VT.changeVectorElementTypeToInteger();
1251 }
1252
1253
1254 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1255 /// the desired ByVal argument alignment.
1256 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1257   if (MaxAlign == 16)
1258     return;
1259   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1260     if (VTy->getBitWidth() == 128)
1261       MaxAlign = 16;
1262   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1263     unsigned EltAlign = 0;
1264     getMaxByValAlign(ATy->getElementType(), EltAlign);
1265     if (EltAlign > MaxAlign)
1266       MaxAlign = EltAlign;
1267   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1268     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1269       unsigned EltAlign = 0;
1270       getMaxByValAlign(STy->getElementType(i), EltAlign);
1271       if (EltAlign > MaxAlign)
1272         MaxAlign = EltAlign;
1273       if (MaxAlign == 16)
1274         break;
1275     }
1276   }
1277   return;
1278 }
1279
1280 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1281 /// function arguments in the caller parameter area. For X86, aggregates
1282 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1283 /// are at 4-byte boundaries.
1284 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1285   if (Subtarget->is64Bit()) {
1286     // Max of 8 and alignment of type.
1287     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1288     if (TyAlign > 8)
1289       return TyAlign;
1290     return 8;
1291   }
1292
1293   unsigned Align = 4;
1294   if (Subtarget->hasSSE1())
1295     getMaxByValAlign(Ty, Align);
1296   return Align;
1297 }
1298
1299 /// getOptimalMemOpType - Returns the target specific optimal type for load
1300 /// and store operations as a result of memset, memcpy, and memmove
1301 /// lowering. If DstAlign is zero that means it's safe to destination
1302 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1303 /// means there isn't a need to check it against alignment requirement,
1304 /// probably because the source does not need to be loaded. If
1305 /// 'IsZeroVal' is true, that means it's safe to return a
1306 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1307 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1308 /// constant so it does not need to be loaded.
1309 /// It returns EVT::Other if the type should be determined using generic
1310 /// target-independent logic.
1311 EVT
1312 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1313                                        unsigned DstAlign, unsigned SrcAlign,
1314                                        bool IsZeroVal,
1315                                        bool MemcpyStrSrc,
1316                                        MachineFunction &MF) const {
1317   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1318   // linux.  This is because the stack realignment code can't handle certain
1319   // cases like PR2962.  This should be removed when PR2962 is fixed.
1320   const Function *F = MF.getFunction();
1321   if (IsZeroVal &&
1322       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1323     if (Size >= 16 &&
1324         (Subtarget->isUnalignedMemAccessFast() ||
1325          ((DstAlign == 0 || DstAlign >= 16) &&
1326           (SrcAlign == 0 || SrcAlign >= 16))) &&
1327         Subtarget->getStackAlignment() >= 16) {
1328       if (Subtarget->getStackAlignment() >= 32) {
1329         if (Subtarget->hasAVX2())
1330           return MVT::v8i32;
1331         if (Subtarget->hasAVX())
1332           return MVT::v8f32;
1333       }
1334       if (Subtarget->hasSSE2())
1335         return MVT::v4i32;
1336       if (Subtarget->hasSSE1())
1337         return MVT::v4f32;
1338     } else if (!MemcpyStrSrc && Size >= 8 &&
1339                !Subtarget->is64Bit() &&
1340                Subtarget->getStackAlignment() >= 8 &&
1341                Subtarget->hasSSE2()) {
1342       // Do not use f64 to lower memcpy if source is string constant. It's
1343       // better to use i32 to avoid the loads.
1344       return MVT::f64;
1345     }
1346   }
1347   if (Subtarget->is64Bit() && Size >= 8)
1348     return MVT::i64;
1349   return MVT::i32;
1350 }
1351
1352 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1353 /// current function.  The returned value is a member of the
1354 /// MachineJumpTableInfo::JTEntryKind enum.
1355 unsigned X86TargetLowering::getJumpTableEncoding() const {
1356   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1357   // symbol.
1358   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1359       Subtarget->isPICStyleGOT())
1360     return MachineJumpTableInfo::EK_Custom32;
1361
1362   // Otherwise, use the normal jump table encoding heuristics.
1363   return TargetLowering::getJumpTableEncoding();
1364 }
1365
1366 const MCExpr *
1367 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1368                                              const MachineBasicBlock *MBB,
1369                                              unsigned uid,MCContext &Ctx) const{
1370   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1371          Subtarget->isPICStyleGOT());
1372   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1373   // entries.
1374   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1375                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1376 }
1377
1378 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1379 /// jumptable.
1380 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1381                                                     SelectionDAG &DAG) const {
1382   if (!Subtarget->is64Bit())
1383     // This doesn't have DebugLoc associated with it, but is not really the
1384     // same as a Register.
1385     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1386   return Table;
1387 }
1388
1389 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1390 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1391 /// MCExpr.
1392 const MCExpr *X86TargetLowering::
1393 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1394                              MCContext &Ctx) const {
1395   // X86-64 uses RIP relative addressing based on the jump table label.
1396   if (Subtarget->isPICStyleRIPRel())
1397     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1398
1399   // Otherwise, the reference is relative to the PIC base.
1400   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1401 }
1402
1403 // FIXME: Why this routine is here? Move to RegInfo!
1404 std::pair<const TargetRegisterClass*, uint8_t>
1405 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1406   const TargetRegisterClass *RRC = 0;
1407   uint8_t Cost = 1;
1408   switch (VT.getSimpleVT().SimpleTy) {
1409   default:
1410     return TargetLowering::findRepresentativeClass(VT);
1411   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1412     RRC = (Subtarget->is64Bit()
1413            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1414     break;
1415   case MVT::x86mmx:
1416     RRC = X86::VR64RegisterClass;
1417     break;
1418   case MVT::f32: case MVT::f64:
1419   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1420   case MVT::v4f32: case MVT::v2f64:
1421   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1422   case MVT::v4f64:
1423     RRC = X86::VR128RegisterClass;
1424     break;
1425   }
1426   return std::make_pair(RRC, Cost);
1427 }
1428
1429 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1430                                                unsigned &Offset) const {
1431   if (!Subtarget->isTargetLinux())
1432     return false;
1433
1434   if (Subtarget->is64Bit()) {
1435     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1436     Offset = 0x28;
1437     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1438       AddressSpace = 256;
1439     else
1440       AddressSpace = 257;
1441   } else {
1442     // %gs:0x14 on i386
1443     Offset = 0x14;
1444     AddressSpace = 256;
1445   }
1446   return true;
1447 }
1448
1449
1450 //===----------------------------------------------------------------------===//
1451 //               Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1453
1454 #include "X86GenCallingConv.inc"
1455
1456 bool
1457 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1458                                   MachineFunction &MF, bool isVarArg,
1459                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1460                         LLVMContext &Context) const {
1461   SmallVector<CCValAssign, 16> RVLocs;
1462   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1463                  RVLocs, Context);
1464   return CCInfo.CheckReturn(Outs, RetCC_X86);
1465 }
1466
1467 SDValue
1468 X86TargetLowering::LowerReturn(SDValue Chain,
1469                                CallingConv::ID CallConv, bool isVarArg,
1470                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1471                                const SmallVectorImpl<SDValue> &OutVals,
1472                                DebugLoc dl, SelectionDAG &DAG) const {
1473   MachineFunction &MF = DAG.getMachineFunction();
1474   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1475
1476   SmallVector<CCValAssign, 16> RVLocs;
1477   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478                  RVLocs, *DAG.getContext());
1479   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1480
1481   // Add the regs to the liveout set for the function.
1482   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1483   for (unsigned i = 0; i != RVLocs.size(); ++i)
1484     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1485       MRI.addLiveOut(RVLocs[i].getLocReg());
1486
1487   SDValue Flag;
1488
1489   SmallVector<SDValue, 6> RetOps;
1490   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491   // Operand #1 = Bytes To Pop
1492   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1493                    MVT::i16));
1494
1495   // Copy the result values into the output registers.
1496   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1497     CCValAssign &VA = RVLocs[i];
1498     assert(VA.isRegLoc() && "Can only return in registers!");
1499     SDValue ValToCopy = OutVals[i];
1500     EVT ValVT = ValToCopy.getValueType();
1501
1502     // If this is x86-64, and we disabled SSE, we can't return FP values,
1503     // or SSE or MMX vectors.
1504     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1505          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1506           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1507       report_fatal_error("SSE register return with SSE disabled");
1508     }
1509     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1510     // llvm-gcc has never done it right and no one has noticed, so this
1511     // should be OK for now.
1512     if (ValVT == MVT::f64 &&
1513         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1514       report_fatal_error("SSE2 register return with SSE2 disabled");
1515
1516     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1517     // the RET instruction and handled by the FP Stackifier.
1518     if (VA.getLocReg() == X86::ST0 ||
1519         VA.getLocReg() == X86::ST1) {
1520       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1521       // change the value to the FP stack register class.
1522       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1523         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1524       RetOps.push_back(ValToCopy);
1525       // Don't emit a copytoreg.
1526       continue;
1527     }
1528
1529     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1530     // which is returned in RAX / RDX.
1531     if (Subtarget->is64Bit()) {
1532       if (ValVT == MVT::x86mmx) {
1533         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1534           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1535           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1536                                   ValToCopy);
1537           // If we don't have SSE2 available, convert to v4f32 so the generated
1538           // register is legal.
1539           if (!Subtarget->hasSSE2())
1540             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1541         }
1542       }
1543     }
1544
1545     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1546     Flag = Chain.getValue(1);
1547   }
1548
1549   // The x86-64 ABI for returning structs by value requires that we copy
1550   // the sret argument into %rax for the return. We saved the argument into
1551   // a virtual register in the entry block, so now we copy the value out
1552   // and into %rax.
1553   if (Subtarget->is64Bit() &&
1554       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1555     MachineFunction &MF = DAG.getMachineFunction();
1556     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1557     unsigned Reg = FuncInfo->getSRetReturnReg();
1558     assert(Reg &&
1559            "SRetReturnReg should have been set in LowerFormalArguments().");
1560     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1561
1562     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1563     Flag = Chain.getValue(1);
1564
1565     // RAX now acts like a return value.
1566     MRI.addLiveOut(X86::RAX);
1567   }
1568
1569   RetOps[0] = Chain;  // Update chain.
1570
1571   // Add the flag if we have it.
1572   if (Flag.getNode())
1573     RetOps.push_back(Flag);
1574
1575   return DAG.getNode(X86ISD::RET_FLAG, dl,
1576                      MVT::Other, &RetOps[0], RetOps.size());
1577 }
1578
1579 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1580   if (N->getNumValues() != 1)
1581     return false;
1582   if (!N->hasNUsesOfValue(1, 0))
1583     return false;
1584
1585   SDNode *Copy = *N->use_begin();
1586   if (Copy->getOpcode() != ISD::CopyToReg &&
1587       Copy->getOpcode() != ISD::FP_EXTEND)
1588     return false;
1589
1590   bool HasRet = false;
1591   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1592        UI != UE; ++UI) {
1593     if (UI->getOpcode() != X86ISD::RET_FLAG)
1594       return false;
1595     HasRet = true;
1596   }
1597
1598   return HasRet;
1599 }
1600
1601 EVT
1602 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1603                                             ISD::NodeType ExtendKind) const {
1604   MVT ReturnMVT;
1605   // TODO: Is this also valid on 32-bit?
1606   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1607     ReturnMVT = MVT::i8;
1608   else
1609     ReturnMVT = MVT::i32;
1610
1611   EVT MinVT = getRegisterType(Context, ReturnMVT);
1612   return VT.bitsLT(MinVT) ? MinVT : VT;
1613 }
1614
1615 /// LowerCallResult - Lower the result values of a call into the
1616 /// appropriate copies out of appropriate physical registers.
1617 ///
1618 SDValue
1619 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1620                                    CallingConv::ID CallConv, bool isVarArg,
1621                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1622                                    DebugLoc dl, SelectionDAG &DAG,
1623                                    SmallVectorImpl<SDValue> &InVals) const {
1624
1625   // Assign locations to each value returned by this call.
1626   SmallVector<CCValAssign, 16> RVLocs;
1627   bool Is64Bit = Subtarget->is64Bit();
1628   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1629                  getTargetMachine(), RVLocs, *DAG.getContext());
1630   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1631
1632   // Copy all of the result registers out of their specified physreg.
1633   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1634     CCValAssign &VA = RVLocs[i];
1635     EVT CopyVT = VA.getValVT();
1636
1637     // If this is x86-64, and we disabled SSE, we can't return FP values
1638     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1639         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1640       report_fatal_error("SSE register return with SSE disabled");
1641     }
1642
1643     SDValue Val;
1644
1645     // If this is a call to a function that returns an fp value on the floating
1646     // point stack, we must guarantee the the value is popped from the stack, so
1647     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1648     // if the return value is not used. We use the FpPOP_RETVAL instruction
1649     // instead.
1650     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1651       // If we prefer to use the value in xmm registers, copy it out as f80 and
1652       // use a truncate to move it from fp stack reg to xmm reg.
1653       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1654       SDValue Ops[] = { Chain, InFlag };
1655       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1656                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1657       Val = Chain.getValue(0);
1658
1659       // Round the f80 to the right size, which also moves it to the appropriate
1660       // xmm register.
1661       if (CopyVT != VA.getValVT())
1662         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1663                           // This truncation won't change the value.
1664                           DAG.getIntPtrConstant(1));
1665     } else {
1666       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1667                                  CopyVT, InFlag).getValue(1);
1668       Val = Chain.getValue(0);
1669     }
1670     InFlag = Chain.getValue(2);
1671     InVals.push_back(Val);
1672   }
1673
1674   return Chain;
1675 }
1676
1677
1678 //===----------------------------------------------------------------------===//
1679 //                C & StdCall & Fast Calling Convention implementation
1680 //===----------------------------------------------------------------------===//
1681 //  StdCall calling convention seems to be standard for many Windows' API
1682 //  routines and around. It differs from C calling convention just a little:
1683 //  callee should clean up the stack, not caller. Symbols should be also
1684 //  decorated in some fancy way :) It doesn't support any vector arguments.
1685 //  For info on fast calling convention see Fast Calling Convention (tail call)
1686 //  implementation LowerX86_32FastCCCallTo.
1687
1688 /// CallIsStructReturn - Determines whether a call uses struct return
1689 /// semantics.
1690 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1691   if (Outs.empty())
1692     return false;
1693
1694   return Outs[0].Flags.isSRet();
1695 }
1696
1697 /// ArgsAreStructReturn - Determines whether a function uses struct
1698 /// return semantics.
1699 static bool
1700 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1701   if (Ins.empty())
1702     return false;
1703
1704   return Ins[0].Flags.isSRet();
1705 }
1706
1707 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1708 /// by "Src" to address "Dst" with size and alignment information specified by
1709 /// the specific parameter attribute. The copy will be passed as a byval
1710 /// function parameter.
1711 static SDValue
1712 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1713                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1714                           DebugLoc dl) {
1715   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1716
1717   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1718                        /*isVolatile*/false, /*AlwaysInline=*/true,
1719                        MachinePointerInfo(), MachinePointerInfo());
1720 }
1721
1722 /// IsTailCallConvention - Return true if the calling convention is one that
1723 /// supports tail call optimization.
1724 static bool IsTailCallConvention(CallingConv::ID CC) {
1725   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1726 }
1727
1728 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1729   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1730     return false;
1731
1732   CallSite CS(CI);
1733   CallingConv::ID CalleeCC = CS.getCallingConv();
1734   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1735     return false;
1736
1737   return true;
1738 }
1739
1740 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1741 /// a tailcall target by changing its ABI.
1742 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1743                                    bool GuaranteedTailCallOpt) {
1744   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1745 }
1746
1747 SDValue
1748 X86TargetLowering::LowerMemArgument(SDValue Chain,
1749                                     CallingConv::ID CallConv,
1750                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1751                                     DebugLoc dl, SelectionDAG &DAG,
1752                                     const CCValAssign &VA,
1753                                     MachineFrameInfo *MFI,
1754                                     unsigned i) const {
1755   // Create the nodes corresponding to a load from this parameter slot.
1756   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1757   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1758                               getTargetMachine().Options.GuaranteedTailCallOpt);
1759   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1760   EVT ValVT;
1761
1762   // If value is passed by pointer we have address passed instead of the value
1763   // itself.
1764   if (VA.getLocInfo() == CCValAssign::Indirect)
1765     ValVT = VA.getLocVT();
1766   else
1767     ValVT = VA.getValVT();
1768
1769   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1770   // changed with more analysis.
1771   // In case of tail call optimization mark all arguments mutable. Since they
1772   // could be overwritten by lowering of arguments in case of a tail call.
1773   if (Flags.isByVal()) {
1774     unsigned Bytes = Flags.getByValSize();
1775     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1776     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1777     return DAG.getFrameIndex(FI, getPointerTy());
1778   } else {
1779     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1780                                     VA.getLocMemOffset(), isImmutable);
1781     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1782     return DAG.getLoad(ValVT, dl, Chain, FIN,
1783                        MachinePointerInfo::getFixedStack(FI),
1784                        false, false, false, 0);
1785   }
1786 }
1787
1788 SDValue
1789 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1790                                         CallingConv::ID CallConv,
1791                                         bool isVarArg,
1792                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1793                                         DebugLoc dl,
1794                                         SelectionDAG &DAG,
1795                                         SmallVectorImpl<SDValue> &InVals)
1796                                           const {
1797   MachineFunction &MF = DAG.getMachineFunction();
1798   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1799
1800   const Function* Fn = MF.getFunction();
1801   if (Fn->hasExternalLinkage() &&
1802       Subtarget->isTargetCygMing() &&
1803       Fn->getName() == "main")
1804     FuncInfo->setForceFramePointer(true);
1805
1806   MachineFrameInfo *MFI = MF.getFrameInfo();
1807   bool Is64Bit = Subtarget->is64Bit();
1808   bool IsWindows = Subtarget->isTargetWindows();
1809   bool IsWin64 = Subtarget->isTargetWin64();
1810
1811   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1812          "Var args not supported with calling convention fastcc or ghc");
1813
1814   // Assign locations to all of the incoming arguments.
1815   SmallVector<CCValAssign, 16> ArgLocs;
1816   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1817                  ArgLocs, *DAG.getContext());
1818
1819   // Allocate shadow area for Win64
1820   if (IsWin64) {
1821     CCInfo.AllocateStack(32, 8);
1822   }
1823
1824   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1825
1826   unsigned LastVal = ~0U;
1827   SDValue ArgValue;
1828   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1829     CCValAssign &VA = ArgLocs[i];
1830     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1831     // places.
1832     assert(VA.getValNo() != LastVal &&
1833            "Don't support value assigned to multiple locs yet");
1834     (void)LastVal;
1835     LastVal = VA.getValNo();
1836
1837     if (VA.isRegLoc()) {
1838       EVT RegVT = VA.getLocVT();
1839       TargetRegisterClass *RC = NULL;
1840       if (RegVT == MVT::i32)
1841         RC = X86::GR32RegisterClass;
1842       else if (Is64Bit && RegVT == MVT::i64)
1843         RC = X86::GR64RegisterClass;
1844       else if (RegVT == MVT::f32)
1845         RC = X86::FR32RegisterClass;
1846       else if (RegVT == MVT::f64)
1847         RC = X86::FR64RegisterClass;
1848       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1849         RC = X86::VR256RegisterClass;
1850       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1851         RC = X86::VR128RegisterClass;
1852       else if (RegVT == MVT::x86mmx)
1853         RC = X86::VR64RegisterClass;
1854       else
1855         llvm_unreachable("Unknown argument type!");
1856
1857       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1858       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1859
1860       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1861       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1862       // right size.
1863       if (VA.getLocInfo() == CCValAssign::SExt)
1864         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1865                                DAG.getValueType(VA.getValVT()));
1866       else if (VA.getLocInfo() == CCValAssign::ZExt)
1867         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1868                                DAG.getValueType(VA.getValVT()));
1869       else if (VA.getLocInfo() == CCValAssign::BCvt)
1870         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1871
1872       if (VA.isExtInLoc()) {
1873         // Handle MMX values passed in XMM regs.
1874         if (RegVT.isVector()) {
1875           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1876                                  ArgValue);
1877         } else
1878           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1879       }
1880     } else {
1881       assert(VA.isMemLoc());
1882       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1883     }
1884
1885     // If value is passed via pointer - do a load.
1886     if (VA.getLocInfo() == CCValAssign::Indirect)
1887       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1888                              MachinePointerInfo(), false, false, false, 0);
1889
1890     InVals.push_back(ArgValue);
1891   }
1892
1893   // The x86-64 ABI for returning structs by value requires that we copy
1894   // the sret argument into %rax for the return. Save the argument into
1895   // a virtual register so that we can access it from the return points.
1896   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1897     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1898     unsigned Reg = FuncInfo->getSRetReturnReg();
1899     if (!Reg) {
1900       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1901       FuncInfo->setSRetReturnReg(Reg);
1902     }
1903     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1904     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1905   }
1906
1907   unsigned StackSize = CCInfo.getNextStackOffset();
1908   // Align stack specially for tail calls.
1909   if (FuncIsMadeTailCallSafe(CallConv,
1910                              MF.getTarget().Options.GuaranteedTailCallOpt))
1911     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1912
1913   // If the function takes variable number of arguments, make a frame index for
1914   // the start of the first vararg value... for expansion of llvm.va_start.
1915   if (isVarArg) {
1916     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1917                     CallConv != CallingConv::X86_ThisCall)) {
1918       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1919     }
1920     if (Is64Bit) {
1921       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1922
1923       // FIXME: We should really autogenerate these arrays
1924       static const unsigned GPR64ArgRegsWin64[] = {
1925         X86::RCX, X86::RDX, X86::R8,  X86::R9
1926       };
1927       static const unsigned GPR64ArgRegs64Bit[] = {
1928         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1929       };
1930       static const unsigned XMMArgRegs64Bit[] = {
1931         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1932         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1933       };
1934       const unsigned *GPR64ArgRegs;
1935       unsigned NumXMMRegs = 0;
1936
1937       if (IsWin64) {
1938         // The XMM registers which might contain var arg parameters are shadowed
1939         // in their paired GPR.  So we only need to save the GPR to their home
1940         // slots.
1941         TotalNumIntRegs = 4;
1942         GPR64ArgRegs = GPR64ArgRegsWin64;
1943       } else {
1944         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1945         GPR64ArgRegs = GPR64ArgRegs64Bit;
1946
1947         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1948                                                 TotalNumXMMRegs);
1949       }
1950       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1951                                                        TotalNumIntRegs);
1952
1953       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1954       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1955              "SSE register cannot be used when SSE is disabled!");
1956       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1957                NoImplicitFloatOps) &&
1958              "SSE register cannot be used when SSE is disabled!");
1959       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1960           !Subtarget->hasSSE1())
1961         // Kernel mode asks for SSE to be disabled, so don't push them
1962         // on the stack.
1963         TotalNumXMMRegs = 0;
1964
1965       if (IsWin64) {
1966         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1967         // Get to the caller-allocated home save location.  Add 8 to account
1968         // for the return address.
1969         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1970         FuncInfo->setRegSaveFrameIndex(
1971           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1972         // Fixup to set vararg frame on shadow area (4 x i64).
1973         if (NumIntRegs < 4)
1974           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1975       } else {
1976         // For X86-64, if there are vararg parameters that are passed via
1977         // registers, then we must store them to their spots on the stack so
1978         // they may be loaded by deferencing the result of va_next.
1979         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1980         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1981         FuncInfo->setRegSaveFrameIndex(
1982           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1983                                false));
1984       }
1985
1986       // Store the integer parameter registers.
1987       SmallVector<SDValue, 8> MemOps;
1988       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1989                                         getPointerTy());
1990       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1991       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1992         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1993                                   DAG.getIntPtrConstant(Offset));
1994         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1995                                      X86::GR64RegisterClass);
1996         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1997         SDValue Store =
1998           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1999                        MachinePointerInfo::getFixedStack(
2000                          FuncInfo->getRegSaveFrameIndex(), Offset),
2001                        false, false, 0);
2002         MemOps.push_back(Store);
2003         Offset += 8;
2004       }
2005
2006       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2007         // Now store the XMM (fp + vector) parameter registers.
2008         SmallVector<SDValue, 11> SaveXMMOps;
2009         SaveXMMOps.push_back(Chain);
2010
2011         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
2012         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2013         SaveXMMOps.push_back(ALVal);
2014
2015         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2016                                FuncInfo->getRegSaveFrameIndex()));
2017         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2018                                FuncInfo->getVarArgsFPOffset()));
2019
2020         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2021           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2022                                        X86::VR128RegisterClass);
2023           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2024           SaveXMMOps.push_back(Val);
2025         }
2026         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2027                                      MVT::Other,
2028                                      &SaveXMMOps[0], SaveXMMOps.size()));
2029       }
2030
2031       if (!MemOps.empty())
2032         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2033                             &MemOps[0], MemOps.size());
2034     }
2035   }
2036
2037   // Some CCs need callee pop.
2038   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2039                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2040     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2041   } else {
2042     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2043     // If this is an sret function, the return should pop the hidden pointer.
2044     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2045         ArgsAreStructReturn(Ins))
2046       FuncInfo->setBytesToPopOnReturn(4);
2047   }
2048
2049   if (!Is64Bit) {
2050     // RegSaveFrameIndex is X86-64 only.
2051     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2052     if (CallConv == CallingConv::X86_FastCall ||
2053         CallConv == CallingConv::X86_ThisCall)
2054       // fastcc functions can't have varargs.
2055       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2056   }
2057
2058   FuncInfo->setArgumentStackSize(StackSize);
2059
2060   return Chain;
2061 }
2062
2063 SDValue
2064 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2065                                     SDValue StackPtr, SDValue Arg,
2066                                     DebugLoc dl, SelectionDAG &DAG,
2067                                     const CCValAssign &VA,
2068                                     ISD::ArgFlagsTy Flags) const {
2069   unsigned LocMemOffset = VA.getLocMemOffset();
2070   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2071   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2072   if (Flags.isByVal())
2073     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2074
2075   return DAG.getStore(Chain, dl, Arg, PtrOff,
2076                       MachinePointerInfo::getStack(LocMemOffset),
2077                       false, false, 0);
2078 }
2079
2080 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2081 /// optimization is performed and it is required.
2082 SDValue
2083 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2084                                            SDValue &OutRetAddr, SDValue Chain,
2085                                            bool IsTailCall, bool Is64Bit,
2086                                            int FPDiff, DebugLoc dl) const {
2087   // Adjust the Return address stack slot.
2088   EVT VT = getPointerTy();
2089   OutRetAddr = getReturnAddressFrameIndex(DAG);
2090
2091   // Load the "old" Return address.
2092   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2093                            false, false, false, 0);
2094   return SDValue(OutRetAddr.getNode(), 1);
2095 }
2096
2097 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2098 /// optimization is performed and it is required (FPDiff!=0).
2099 static SDValue
2100 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2101                          SDValue Chain, SDValue RetAddrFrIdx,
2102                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2103   // Store the return address to the appropriate stack slot.
2104   if (!FPDiff) return Chain;
2105   // Calculate the new stack slot for the return address.
2106   int SlotSize = Is64Bit ? 8 : 4;
2107   int NewReturnAddrFI =
2108     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2109   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2110   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2111   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2112                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2113                        false, false, 0);
2114   return Chain;
2115 }
2116
2117 SDValue
2118 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2119                              CallingConv::ID CallConv, bool isVarArg,
2120                              bool &isTailCall,
2121                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2122                              const SmallVectorImpl<SDValue> &OutVals,
2123                              const SmallVectorImpl<ISD::InputArg> &Ins,
2124                              DebugLoc dl, SelectionDAG &DAG,
2125                              SmallVectorImpl<SDValue> &InVals) const {
2126   MachineFunction &MF = DAG.getMachineFunction();
2127   bool Is64Bit        = Subtarget->is64Bit();
2128   bool IsWin64        = Subtarget->isTargetWin64();
2129   bool IsWindows      = Subtarget->isTargetWindows();
2130   bool IsStructRet    = CallIsStructReturn(Outs);
2131   bool IsSibcall      = false;
2132
2133   if (MF.getTarget().Options.DisableTailCalls)
2134     isTailCall = false;
2135
2136   if (isTailCall) {
2137     // Check if it's really possible to do a tail call.
2138     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2139                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2140                                                    Outs, OutVals, Ins, DAG);
2141
2142     // Sibcalls are automatically detected tailcalls which do not require
2143     // ABI changes.
2144     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2145       IsSibcall = true;
2146
2147     if (isTailCall)
2148       ++NumTailCalls;
2149   }
2150
2151   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2152          "Var args not supported with calling convention fastcc or ghc");
2153
2154   // Analyze operands of the call, assigning locations to each operand.
2155   SmallVector<CCValAssign, 16> ArgLocs;
2156   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2157                  ArgLocs, *DAG.getContext());
2158
2159   // Allocate shadow area for Win64
2160   if (IsWin64) {
2161     CCInfo.AllocateStack(32, 8);
2162   }
2163
2164   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2165
2166   // Get a count of how many bytes are to be pushed on the stack.
2167   unsigned NumBytes = CCInfo.getNextStackOffset();
2168   if (IsSibcall)
2169     // This is a sibcall. The memory operands are available in caller's
2170     // own caller's stack.
2171     NumBytes = 0;
2172   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2173            IsTailCallConvention(CallConv))
2174     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2175
2176   int FPDiff = 0;
2177   if (isTailCall && !IsSibcall) {
2178     // Lower arguments at fp - stackoffset + fpdiff.
2179     unsigned NumBytesCallerPushed =
2180       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2181     FPDiff = NumBytesCallerPushed - NumBytes;
2182
2183     // Set the delta of movement of the returnaddr stackslot.
2184     // But only set if delta is greater than previous delta.
2185     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2186       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2187   }
2188
2189   if (!IsSibcall)
2190     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2191
2192   SDValue RetAddrFrIdx;
2193   // Load return address for tail calls.
2194   if (isTailCall && FPDiff)
2195     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2196                                     Is64Bit, FPDiff, dl);
2197
2198   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2199   SmallVector<SDValue, 8> MemOpChains;
2200   SDValue StackPtr;
2201
2202   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2203   // of tail call optimization arguments are handle later.
2204   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2205     CCValAssign &VA = ArgLocs[i];
2206     EVT RegVT = VA.getLocVT();
2207     SDValue Arg = OutVals[i];
2208     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2209     bool isByVal = Flags.isByVal();
2210
2211     // Promote the value if needed.
2212     switch (VA.getLocInfo()) {
2213     default: llvm_unreachable("Unknown loc info!");
2214     case CCValAssign::Full: break;
2215     case CCValAssign::SExt:
2216       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2217       break;
2218     case CCValAssign::ZExt:
2219       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2220       break;
2221     case CCValAssign::AExt:
2222       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2223         // Special case: passing MMX values in XMM registers.
2224         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2225         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2226         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2227       } else
2228         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2229       break;
2230     case CCValAssign::BCvt:
2231       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2232       break;
2233     case CCValAssign::Indirect: {
2234       // Store the argument.
2235       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2236       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2237       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2238                            MachinePointerInfo::getFixedStack(FI),
2239                            false, false, 0);
2240       Arg = SpillSlot;
2241       break;
2242     }
2243     }
2244
2245     if (VA.isRegLoc()) {
2246       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2247       if (isVarArg && IsWin64) {
2248         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2249         // shadow reg if callee is a varargs function.
2250         unsigned ShadowReg = 0;
2251         switch (VA.getLocReg()) {
2252         case X86::XMM0: ShadowReg = X86::RCX; break;
2253         case X86::XMM1: ShadowReg = X86::RDX; break;
2254         case X86::XMM2: ShadowReg = X86::R8; break;
2255         case X86::XMM3: ShadowReg = X86::R9; break;
2256         }
2257         if (ShadowReg)
2258           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2259       }
2260     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2261       assert(VA.isMemLoc());
2262       if (StackPtr.getNode() == 0)
2263         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2264       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2265                                              dl, DAG, VA, Flags));
2266     }
2267   }
2268
2269   if (!MemOpChains.empty())
2270     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2271                         &MemOpChains[0], MemOpChains.size());
2272
2273   // Build a sequence of copy-to-reg nodes chained together with token chain
2274   // and flag operands which copy the outgoing args into registers.
2275   SDValue InFlag;
2276   // Tail call byval lowering might overwrite argument registers so in case of
2277   // tail call optimization the copies to registers are lowered later.
2278   if (!isTailCall)
2279     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2280       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2281                                RegsToPass[i].second, InFlag);
2282       InFlag = Chain.getValue(1);
2283     }
2284
2285   if (Subtarget->isPICStyleGOT()) {
2286     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2287     // GOT pointer.
2288     if (!isTailCall) {
2289       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2290                                DAG.getNode(X86ISD::GlobalBaseReg,
2291                                            DebugLoc(), getPointerTy()),
2292                                InFlag);
2293       InFlag = Chain.getValue(1);
2294     } else {
2295       // If we are tail calling and generating PIC/GOT style code load the
2296       // address of the callee into ECX. The value in ecx is used as target of
2297       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2298       // for tail calls on PIC/GOT architectures. Normally we would just put the
2299       // address of GOT into ebx and then call target@PLT. But for tail calls
2300       // ebx would be restored (since ebx is callee saved) before jumping to the
2301       // target@PLT.
2302
2303       // Note: The actual moving to ECX is done further down.
2304       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2305       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2306           !G->getGlobal()->hasProtectedVisibility())
2307         Callee = LowerGlobalAddress(Callee, DAG);
2308       else if (isa<ExternalSymbolSDNode>(Callee))
2309         Callee = LowerExternalSymbol(Callee, DAG);
2310     }
2311   }
2312
2313   if (Is64Bit && isVarArg && !IsWin64) {
2314     // From AMD64 ABI document:
2315     // For calls that may call functions that use varargs or stdargs
2316     // (prototype-less calls or calls to functions containing ellipsis (...) in
2317     // the declaration) %al is used as hidden argument to specify the number
2318     // of SSE registers used. The contents of %al do not need to match exactly
2319     // the number of registers, but must be an ubound on the number of SSE
2320     // registers used and is in the range 0 - 8 inclusive.
2321
2322     // Count the number of XMM registers allocated.
2323     static const unsigned XMMArgRegs[] = {
2324       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2325       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2326     };
2327     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2328     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2329            && "SSE registers cannot be used when SSE is disabled");
2330
2331     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2332                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2333     InFlag = Chain.getValue(1);
2334   }
2335
2336
2337   // For tail calls lower the arguments to the 'real' stack slot.
2338   if (isTailCall) {
2339     // Force all the incoming stack arguments to be loaded from the stack
2340     // before any new outgoing arguments are stored to the stack, because the
2341     // outgoing stack slots may alias the incoming argument stack slots, and
2342     // the alias isn't otherwise explicit. This is slightly more conservative
2343     // than necessary, because it means that each store effectively depends
2344     // on every argument instead of just those arguments it would clobber.
2345     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2346
2347     SmallVector<SDValue, 8> MemOpChains2;
2348     SDValue FIN;
2349     int FI = 0;
2350     // Do not flag preceding copytoreg stuff together with the following stuff.
2351     InFlag = SDValue();
2352     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2353       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2354         CCValAssign &VA = ArgLocs[i];
2355         if (VA.isRegLoc())
2356           continue;
2357         assert(VA.isMemLoc());
2358         SDValue Arg = OutVals[i];
2359         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2360         // Create frame index.
2361         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2362         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2363         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2364         FIN = DAG.getFrameIndex(FI, getPointerTy());
2365
2366         if (Flags.isByVal()) {
2367           // Copy relative to framepointer.
2368           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2369           if (StackPtr.getNode() == 0)
2370             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2371                                           getPointerTy());
2372           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2373
2374           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2375                                                            ArgChain,
2376                                                            Flags, DAG, dl));
2377         } else {
2378           // Store relative to framepointer.
2379           MemOpChains2.push_back(
2380             DAG.getStore(ArgChain, dl, Arg, FIN,
2381                          MachinePointerInfo::getFixedStack(FI),
2382                          false, false, 0));
2383         }
2384       }
2385     }
2386
2387     if (!MemOpChains2.empty())
2388       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2389                           &MemOpChains2[0], MemOpChains2.size());
2390
2391     // Copy arguments to their registers.
2392     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2393       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2394                                RegsToPass[i].second, InFlag);
2395       InFlag = Chain.getValue(1);
2396     }
2397     InFlag =SDValue();
2398
2399     // Store the return address to the appropriate stack slot.
2400     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2401                                      FPDiff, dl);
2402   }
2403
2404   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2405     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2406     // In the 64-bit large code model, we have to make all calls
2407     // through a register, since the call instruction's 32-bit
2408     // pc-relative offset may not be large enough to hold the whole
2409     // address.
2410   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2411     // If the callee is a GlobalAddress node (quite common, every direct call
2412     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2413     // it.
2414
2415     // We should use extra load for direct calls to dllimported functions in
2416     // non-JIT mode.
2417     const GlobalValue *GV = G->getGlobal();
2418     if (!GV->hasDLLImportLinkage()) {
2419       unsigned char OpFlags = 0;
2420       bool ExtraLoad = false;
2421       unsigned WrapperKind = ISD::DELETED_NODE;
2422
2423       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2424       // external symbols most go through the PLT in PIC mode.  If the symbol
2425       // has hidden or protected visibility, or if it is static or local, then
2426       // we don't need to use the PLT - we can directly call it.
2427       if (Subtarget->isTargetELF() &&
2428           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2429           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2430         OpFlags = X86II::MO_PLT;
2431       } else if (Subtarget->isPICStyleStubAny() &&
2432                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2433                  (!Subtarget->getTargetTriple().isMacOSX() ||
2434                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2435         // PC-relative references to external symbols should go through $stub,
2436         // unless we're building with the leopard linker or later, which
2437         // automatically synthesizes these stubs.
2438         OpFlags = X86II::MO_DARWIN_STUB;
2439       } else if (Subtarget->isPICStyleRIPRel() &&
2440                  isa<Function>(GV) &&
2441                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2442         // If the function is marked as non-lazy, generate an indirect call
2443         // which loads from the GOT directly. This avoids runtime overhead
2444         // at the cost of eager binding (and one extra byte of encoding).
2445         OpFlags = X86II::MO_GOTPCREL;
2446         WrapperKind = X86ISD::WrapperRIP;
2447         ExtraLoad = true;
2448       }
2449
2450       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2451                                           G->getOffset(), OpFlags);
2452
2453       // Add a wrapper if needed.
2454       if (WrapperKind != ISD::DELETED_NODE)
2455         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2456       // Add extra indirection if needed.
2457       if (ExtraLoad)
2458         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2459                              MachinePointerInfo::getGOT(),
2460                              false, false, false, 0);
2461     }
2462   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2463     unsigned char OpFlags = 0;
2464
2465     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2466     // external symbols should go through the PLT.
2467     if (Subtarget->isTargetELF() &&
2468         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2469       OpFlags = X86II::MO_PLT;
2470     } else if (Subtarget->isPICStyleStubAny() &&
2471                (!Subtarget->getTargetTriple().isMacOSX() ||
2472                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2473       // PC-relative references to external symbols should go through $stub,
2474       // unless we're building with the leopard linker or later, which
2475       // automatically synthesizes these stubs.
2476       OpFlags = X86II::MO_DARWIN_STUB;
2477     }
2478
2479     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2480                                          OpFlags);
2481   }
2482
2483   // Returns a chain & a flag for retval copy to use.
2484   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2485   SmallVector<SDValue, 8> Ops;
2486
2487   if (!IsSibcall && isTailCall) {
2488     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2489                            DAG.getIntPtrConstant(0, true), InFlag);
2490     InFlag = Chain.getValue(1);
2491   }
2492
2493   Ops.push_back(Chain);
2494   Ops.push_back(Callee);
2495
2496   if (isTailCall)
2497     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2498
2499   // Add argument registers to the end of the list so that they are known live
2500   // into the call.
2501   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2502     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2503                                   RegsToPass[i].second.getValueType()));
2504
2505   // Add an implicit use GOT pointer in EBX.
2506   if (!isTailCall && Subtarget->isPICStyleGOT())
2507     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2508
2509   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2510   if (Is64Bit && isVarArg && !IsWin64)
2511     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2512
2513   // Experimental: Add a register mask operand representing the call-preserved
2514   // registers.
2515   if (UseRegMask) {
2516     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2517     if (const uint32_t *Mask = TRI->getCallPreservedMask(CallConv))
2518       Ops.push_back(DAG.getRegisterMask(Mask));
2519   }
2520
2521   if (InFlag.getNode())
2522     Ops.push_back(InFlag);
2523
2524   if (isTailCall) {
2525     // We used to do:
2526     //// If this is the first return lowered for this function, add the regs
2527     //// to the liveout set for the function.
2528     // This isn't right, although it's probably harmless on x86; liveouts
2529     // should be computed from returns not tail calls.  Consider a void
2530     // function making a tail call to a function returning int.
2531     return DAG.getNode(X86ISD::TC_RETURN, dl,
2532                        NodeTys, &Ops[0], Ops.size());
2533   }
2534
2535   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2536   InFlag = Chain.getValue(1);
2537
2538   // Create the CALLSEQ_END node.
2539   unsigned NumBytesForCalleeToPush;
2540   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2541                        getTargetMachine().Options.GuaranteedTailCallOpt))
2542     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2543   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2544            IsStructRet)
2545     // If this is a call to a struct-return function, the callee
2546     // pops the hidden struct pointer, so we have to push it back.
2547     // This is common for Darwin/X86, Linux & Mingw32 targets.
2548     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2549     NumBytesForCalleeToPush = 4;
2550   else
2551     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2552
2553   // Returns a flag for retval copy to use.
2554   if (!IsSibcall) {
2555     Chain = DAG.getCALLSEQ_END(Chain,
2556                                DAG.getIntPtrConstant(NumBytes, true),
2557                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2558                                                      true),
2559                                InFlag);
2560     InFlag = Chain.getValue(1);
2561   }
2562
2563   // Handle result values, copying them out of physregs into vregs that we
2564   // return.
2565   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2566                          Ins, dl, DAG, InVals);
2567 }
2568
2569
2570 //===----------------------------------------------------------------------===//
2571 //                Fast Calling Convention (tail call) implementation
2572 //===----------------------------------------------------------------------===//
2573
2574 //  Like std call, callee cleans arguments, convention except that ECX is
2575 //  reserved for storing the tail called function address. Only 2 registers are
2576 //  free for argument passing (inreg). Tail call optimization is performed
2577 //  provided:
2578 //                * tailcallopt is enabled
2579 //                * caller/callee are fastcc
2580 //  On X86_64 architecture with GOT-style position independent code only local
2581 //  (within module) calls are supported at the moment.
2582 //  To keep the stack aligned according to platform abi the function
2583 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2584 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2585 //  If a tail called function callee has more arguments than the caller the
2586 //  caller needs to make sure that there is room to move the RETADDR to. This is
2587 //  achieved by reserving an area the size of the argument delta right after the
2588 //  original REtADDR, but before the saved framepointer or the spilled registers
2589 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2590 //  stack layout:
2591 //    arg1
2592 //    arg2
2593 //    RETADDR
2594 //    [ new RETADDR
2595 //      move area ]
2596 //    (possible EBP)
2597 //    ESI
2598 //    EDI
2599 //    local1 ..
2600
2601 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2602 /// for a 16 byte align requirement.
2603 unsigned
2604 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2605                                                SelectionDAG& DAG) const {
2606   MachineFunction &MF = DAG.getMachineFunction();
2607   const TargetMachine &TM = MF.getTarget();
2608   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2609   unsigned StackAlignment = TFI.getStackAlignment();
2610   uint64_t AlignMask = StackAlignment - 1;
2611   int64_t Offset = StackSize;
2612   uint64_t SlotSize = TD->getPointerSize();
2613   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2614     // Number smaller than 12 so just add the difference.
2615     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2616   } else {
2617     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2618     Offset = ((~AlignMask) & Offset) + StackAlignment +
2619       (StackAlignment-SlotSize);
2620   }
2621   return Offset;
2622 }
2623
2624 /// MatchingStackOffset - Return true if the given stack call argument is
2625 /// already available in the same position (relatively) of the caller's
2626 /// incoming argument stack.
2627 static
2628 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2629                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2630                          const X86InstrInfo *TII) {
2631   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2632   int FI = INT_MAX;
2633   if (Arg.getOpcode() == ISD::CopyFromReg) {
2634     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2635     if (!TargetRegisterInfo::isVirtualRegister(VR))
2636       return false;
2637     MachineInstr *Def = MRI->getVRegDef(VR);
2638     if (!Def)
2639       return false;
2640     if (!Flags.isByVal()) {
2641       if (!TII->isLoadFromStackSlot(Def, FI))
2642         return false;
2643     } else {
2644       unsigned Opcode = Def->getOpcode();
2645       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2646           Def->getOperand(1).isFI()) {
2647         FI = Def->getOperand(1).getIndex();
2648         Bytes = Flags.getByValSize();
2649       } else
2650         return false;
2651     }
2652   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2653     if (Flags.isByVal())
2654       // ByVal argument is passed in as a pointer but it's now being
2655       // dereferenced. e.g.
2656       // define @foo(%struct.X* %A) {
2657       //   tail call @bar(%struct.X* byval %A)
2658       // }
2659       return false;
2660     SDValue Ptr = Ld->getBasePtr();
2661     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2662     if (!FINode)
2663       return false;
2664     FI = FINode->getIndex();
2665   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2666     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2667     FI = FINode->getIndex();
2668     Bytes = Flags.getByValSize();
2669   } else
2670     return false;
2671
2672   assert(FI != INT_MAX);
2673   if (!MFI->isFixedObjectIndex(FI))
2674     return false;
2675   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2676 }
2677
2678 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2679 /// for tail call optimization. Targets which want to do tail call
2680 /// optimization should implement this function.
2681 bool
2682 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2683                                                      CallingConv::ID CalleeCC,
2684                                                      bool isVarArg,
2685                                                      bool isCalleeStructRet,
2686                                                      bool isCallerStructRet,
2687                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2688                                     const SmallVectorImpl<SDValue> &OutVals,
2689                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2690                                                      SelectionDAG& DAG) const {
2691   if (!IsTailCallConvention(CalleeCC) &&
2692       CalleeCC != CallingConv::C)
2693     return false;
2694
2695   // If -tailcallopt is specified, make fastcc functions tail-callable.
2696   const MachineFunction &MF = DAG.getMachineFunction();
2697   const Function *CallerF = DAG.getMachineFunction().getFunction();
2698   CallingConv::ID CallerCC = CallerF->getCallingConv();
2699   bool CCMatch = CallerCC == CalleeCC;
2700
2701   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2702     if (IsTailCallConvention(CalleeCC) && CCMatch)
2703       return true;
2704     return false;
2705   }
2706
2707   // Look for obvious safe cases to perform tail call optimization that do not
2708   // require ABI changes. This is what gcc calls sibcall.
2709
2710   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2711   // emit a special epilogue.
2712   if (RegInfo->needsStackRealignment(MF))
2713     return false;
2714
2715   // Also avoid sibcall optimization if either caller or callee uses struct
2716   // return semantics.
2717   if (isCalleeStructRet || isCallerStructRet)
2718     return false;
2719
2720   // An stdcall caller is expected to clean up its arguments; the callee
2721   // isn't going to do that.
2722   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2723     return false;
2724
2725   // Do not sibcall optimize vararg calls unless all arguments are passed via
2726   // registers.
2727   if (isVarArg && !Outs.empty()) {
2728
2729     // Optimizing for varargs on Win64 is unlikely to be safe without
2730     // additional testing.
2731     if (Subtarget->isTargetWin64())
2732       return false;
2733
2734     SmallVector<CCValAssign, 16> ArgLocs;
2735     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2736                    getTargetMachine(), ArgLocs, *DAG.getContext());
2737
2738     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2739     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2740       if (!ArgLocs[i].isRegLoc())
2741         return false;
2742   }
2743
2744   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2745   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2746   // this into a sibcall.
2747   bool Unused = false;
2748   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2749     if (!Ins[i].Used) {
2750       Unused = true;
2751       break;
2752     }
2753   }
2754   if (Unused) {
2755     SmallVector<CCValAssign, 16> RVLocs;
2756     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2757                    getTargetMachine(), RVLocs, *DAG.getContext());
2758     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2759     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2760       CCValAssign &VA = RVLocs[i];
2761       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2762         return false;
2763     }
2764   }
2765
2766   // If the calling conventions do not match, then we'd better make sure the
2767   // results are returned in the same way as what the caller expects.
2768   if (!CCMatch) {
2769     SmallVector<CCValAssign, 16> RVLocs1;
2770     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2771                     getTargetMachine(), RVLocs1, *DAG.getContext());
2772     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2773
2774     SmallVector<CCValAssign, 16> RVLocs2;
2775     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2776                     getTargetMachine(), RVLocs2, *DAG.getContext());
2777     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2778
2779     if (RVLocs1.size() != RVLocs2.size())
2780       return false;
2781     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2782       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2783         return false;
2784       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2785         return false;
2786       if (RVLocs1[i].isRegLoc()) {
2787         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2788           return false;
2789       } else {
2790         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2791           return false;
2792       }
2793     }
2794   }
2795
2796   // If the callee takes no arguments then go on to check the results of the
2797   // call.
2798   if (!Outs.empty()) {
2799     // Check if stack adjustment is needed. For now, do not do this if any
2800     // argument is passed on the stack.
2801     SmallVector<CCValAssign, 16> ArgLocs;
2802     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2803                    getTargetMachine(), ArgLocs, *DAG.getContext());
2804
2805     // Allocate shadow area for Win64
2806     if (Subtarget->isTargetWin64()) {
2807       CCInfo.AllocateStack(32, 8);
2808     }
2809
2810     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2811     if (CCInfo.getNextStackOffset()) {
2812       MachineFunction &MF = DAG.getMachineFunction();
2813       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2814         return false;
2815
2816       // Check if the arguments are already laid out in the right way as
2817       // the caller's fixed stack objects.
2818       MachineFrameInfo *MFI = MF.getFrameInfo();
2819       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2820       const X86InstrInfo *TII =
2821         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2822       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2823         CCValAssign &VA = ArgLocs[i];
2824         SDValue Arg = OutVals[i];
2825         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2826         if (VA.getLocInfo() == CCValAssign::Indirect)
2827           return false;
2828         if (!VA.isRegLoc()) {
2829           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2830                                    MFI, MRI, TII))
2831             return false;
2832         }
2833       }
2834     }
2835
2836     // If the tailcall address may be in a register, then make sure it's
2837     // possible to register allocate for it. In 32-bit, the call address can
2838     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2839     // callee-saved registers are restored. These happen to be the same
2840     // registers used to pass 'inreg' arguments so watch out for those.
2841     if (!Subtarget->is64Bit() &&
2842         !isa<GlobalAddressSDNode>(Callee) &&
2843         !isa<ExternalSymbolSDNode>(Callee)) {
2844       unsigned NumInRegs = 0;
2845       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846         CCValAssign &VA = ArgLocs[i];
2847         if (!VA.isRegLoc())
2848           continue;
2849         unsigned Reg = VA.getLocReg();
2850         switch (Reg) {
2851         default: break;
2852         case X86::EAX: case X86::EDX: case X86::ECX:
2853           if (++NumInRegs == 3)
2854             return false;
2855           break;
2856         }
2857       }
2858     }
2859   }
2860
2861   return true;
2862 }
2863
2864 FastISel *
2865 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2866   return X86::createFastISel(funcInfo);
2867 }
2868
2869
2870 //===----------------------------------------------------------------------===//
2871 //                           Other Lowering Hooks
2872 //===----------------------------------------------------------------------===//
2873
2874 static bool MayFoldLoad(SDValue Op) {
2875   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2876 }
2877
2878 static bool MayFoldIntoStore(SDValue Op) {
2879   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2880 }
2881
2882 static bool isTargetShuffle(unsigned Opcode) {
2883   switch(Opcode) {
2884   default: return false;
2885   case X86ISD::PSHUFD:
2886   case X86ISD::PSHUFHW:
2887   case X86ISD::PSHUFLW:
2888   case X86ISD::SHUFP:
2889   case X86ISD::PALIGN:
2890   case X86ISD::MOVLHPS:
2891   case X86ISD::MOVLHPD:
2892   case X86ISD::MOVHLPS:
2893   case X86ISD::MOVLPS:
2894   case X86ISD::MOVLPD:
2895   case X86ISD::MOVSHDUP:
2896   case X86ISD::MOVSLDUP:
2897   case X86ISD::MOVDDUP:
2898   case X86ISD::MOVSS:
2899   case X86ISD::MOVSD:
2900   case X86ISD::UNPCKL:
2901   case X86ISD::UNPCKH:
2902   case X86ISD::VPERMILP:
2903   case X86ISD::VPERM2X128:
2904     return true;
2905   }
2906 }
2907
2908 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2909                                                SDValue V1, SelectionDAG &DAG) {
2910   switch(Opc) {
2911   default: llvm_unreachable("Unknown x86 shuffle node");
2912   case X86ISD::MOVSHDUP:
2913   case X86ISD::MOVSLDUP:
2914   case X86ISD::MOVDDUP:
2915     return DAG.getNode(Opc, dl, VT, V1);
2916   }
2917 }
2918
2919 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2920                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2921   switch(Opc) {
2922   default: llvm_unreachable("Unknown x86 shuffle node");
2923   case X86ISD::PSHUFD:
2924   case X86ISD::PSHUFHW:
2925   case X86ISD::PSHUFLW:
2926   case X86ISD::VPERMILP:
2927     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2928   }
2929 }
2930
2931 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2932                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2933   switch(Opc) {
2934   default: llvm_unreachable("Unknown x86 shuffle node");
2935   case X86ISD::PALIGN:
2936   case X86ISD::SHUFP:
2937   case X86ISD::VPERM2X128:
2938     return DAG.getNode(Opc, dl, VT, V1, V2,
2939                        DAG.getConstant(TargetMask, MVT::i8));
2940   }
2941 }
2942
2943 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2944                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2945   switch(Opc) {
2946   default: llvm_unreachable("Unknown x86 shuffle node");
2947   case X86ISD::MOVLHPS:
2948   case X86ISD::MOVLHPD:
2949   case X86ISD::MOVHLPS:
2950   case X86ISD::MOVLPS:
2951   case X86ISD::MOVLPD:
2952   case X86ISD::MOVSS:
2953   case X86ISD::MOVSD:
2954   case X86ISD::UNPCKL:
2955   case X86ISD::UNPCKH:
2956     return DAG.getNode(Opc, dl, VT, V1, V2);
2957   }
2958 }
2959
2960 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2961   MachineFunction &MF = DAG.getMachineFunction();
2962   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2963   int ReturnAddrIndex = FuncInfo->getRAIndex();
2964
2965   if (ReturnAddrIndex == 0) {
2966     // Set up a frame object for the return address.
2967     uint64_t SlotSize = TD->getPointerSize();
2968     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2969                                                            false);
2970     FuncInfo->setRAIndex(ReturnAddrIndex);
2971   }
2972
2973   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2974 }
2975
2976
2977 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2978                                        bool hasSymbolicDisplacement) {
2979   // Offset should fit into 32 bit immediate field.
2980   if (!isInt<32>(Offset))
2981     return false;
2982
2983   // If we don't have a symbolic displacement - we don't have any extra
2984   // restrictions.
2985   if (!hasSymbolicDisplacement)
2986     return true;
2987
2988   // FIXME: Some tweaks might be needed for medium code model.
2989   if (M != CodeModel::Small && M != CodeModel::Kernel)
2990     return false;
2991
2992   // For small code model we assume that latest object is 16MB before end of 31
2993   // bits boundary. We may also accept pretty large negative constants knowing
2994   // that all objects are in the positive half of address space.
2995   if (M == CodeModel::Small && Offset < 16*1024*1024)
2996     return true;
2997
2998   // For kernel code model we know that all object resist in the negative half
2999   // of 32bits address space. We may not accept negative offsets, since they may
3000   // be just off and we may accept pretty large positive ones.
3001   if (M == CodeModel::Kernel && Offset > 0)
3002     return true;
3003
3004   return false;
3005 }
3006
3007 /// isCalleePop - Determines whether the callee is required to pop its
3008 /// own arguments. Callee pop is necessary to support tail calls.
3009 bool X86::isCalleePop(CallingConv::ID CallingConv,
3010                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3011   if (IsVarArg)
3012     return false;
3013
3014   switch (CallingConv) {
3015   default:
3016     return false;
3017   case CallingConv::X86_StdCall:
3018     return !is64Bit;
3019   case CallingConv::X86_FastCall:
3020     return !is64Bit;
3021   case CallingConv::X86_ThisCall:
3022     return !is64Bit;
3023   case CallingConv::Fast:
3024     return TailCallOpt;
3025   case CallingConv::GHC:
3026     return TailCallOpt;
3027   }
3028 }
3029
3030 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3031 /// specific condition code, returning the condition code and the LHS/RHS of the
3032 /// comparison to make.
3033 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3034                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3035   if (!isFP) {
3036     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3037       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3038         // X > -1   -> X == 0, jump !sign.
3039         RHS = DAG.getConstant(0, RHS.getValueType());
3040         return X86::COND_NS;
3041       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3042         // X < 0   -> X == 0, jump on sign.
3043         return X86::COND_S;
3044       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3045         // X < 1   -> X <= 0
3046         RHS = DAG.getConstant(0, RHS.getValueType());
3047         return X86::COND_LE;
3048       }
3049     }
3050
3051     switch (SetCCOpcode) {
3052     default: llvm_unreachable("Invalid integer condition!");
3053     case ISD::SETEQ:  return X86::COND_E;
3054     case ISD::SETGT:  return X86::COND_G;
3055     case ISD::SETGE:  return X86::COND_GE;
3056     case ISD::SETLT:  return X86::COND_L;
3057     case ISD::SETLE:  return X86::COND_LE;
3058     case ISD::SETNE:  return X86::COND_NE;
3059     case ISD::SETULT: return X86::COND_B;
3060     case ISD::SETUGT: return X86::COND_A;
3061     case ISD::SETULE: return X86::COND_BE;
3062     case ISD::SETUGE: return X86::COND_AE;
3063     }
3064   }
3065
3066   // First determine if it is required or is profitable to flip the operands.
3067
3068   // If LHS is a foldable load, but RHS is not, flip the condition.
3069   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3070       !ISD::isNON_EXTLoad(RHS.getNode())) {
3071     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3072     std::swap(LHS, RHS);
3073   }
3074
3075   switch (SetCCOpcode) {
3076   default: break;
3077   case ISD::SETOLT:
3078   case ISD::SETOLE:
3079   case ISD::SETUGT:
3080   case ISD::SETUGE:
3081     std::swap(LHS, RHS);
3082     break;
3083   }
3084
3085   // On a floating point condition, the flags are set as follows:
3086   // ZF  PF  CF   op
3087   //  0 | 0 | 0 | X > Y
3088   //  0 | 0 | 1 | X < Y
3089   //  1 | 0 | 0 | X == Y
3090   //  1 | 1 | 1 | unordered
3091   switch (SetCCOpcode) {
3092   default: llvm_unreachable("Condcode should be pre-legalized away");
3093   case ISD::SETUEQ:
3094   case ISD::SETEQ:   return X86::COND_E;
3095   case ISD::SETOLT:              // flipped
3096   case ISD::SETOGT:
3097   case ISD::SETGT:   return X86::COND_A;
3098   case ISD::SETOLE:              // flipped
3099   case ISD::SETOGE:
3100   case ISD::SETGE:   return X86::COND_AE;
3101   case ISD::SETUGT:              // flipped
3102   case ISD::SETULT:
3103   case ISD::SETLT:   return X86::COND_B;
3104   case ISD::SETUGE:              // flipped
3105   case ISD::SETULE:
3106   case ISD::SETLE:   return X86::COND_BE;
3107   case ISD::SETONE:
3108   case ISD::SETNE:   return X86::COND_NE;
3109   case ISD::SETUO:   return X86::COND_P;
3110   case ISD::SETO:    return X86::COND_NP;
3111   case ISD::SETOEQ:
3112   case ISD::SETUNE:  return X86::COND_INVALID;
3113   }
3114 }
3115
3116 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3117 /// code. Current x86 isa includes the following FP cmov instructions:
3118 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3119 static bool hasFPCMov(unsigned X86CC) {
3120   switch (X86CC) {
3121   default:
3122     return false;
3123   case X86::COND_B:
3124   case X86::COND_BE:
3125   case X86::COND_E:
3126   case X86::COND_P:
3127   case X86::COND_A:
3128   case X86::COND_AE:
3129   case X86::COND_NE:
3130   case X86::COND_NP:
3131     return true;
3132   }
3133 }
3134
3135 /// isFPImmLegal - Returns true if the target can instruction select the
3136 /// specified FP immediate natively. If false, the legalizer will
3137 /// materialize the FP immediate as a load from a constant pool.
3138 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3139   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3140     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3141       return true;
3142   }
3143   return false;
3144 }
3145
3146 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3147 /// the specified range (L, H].
3148 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3149   return (Val < 0) || (Val >= Low && Val < Hi);
3150 }
3151
3152 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3153 /// specified value.
3154 static bool isUndefOrEqual(int Val, int CmpVal) {
3155   if (Val < 0 || Val == CmpVal)
3156     return true;
3157   return false;
3158 }
3159
3160 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3161 /// from position Pos and ending in Pos+Size, falls within the specified
3162 /// sequential range (L, L+Pos]. or is undef.
3163 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3164                                        int Pos, int Size, int Low) {
3165   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3166     if (!isUndefOrEqual(Mask[i], Low))
3167       return false;
3168   return true;
3169 }
3170
3171 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3172 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3173 /// the second operand.
3174 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3175   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3176     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3177   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3178     return (Mask[0] < 2 && Mask[1] < 2);
3179   return false;
3180 }
3181
3182 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3183   return ::isPSHUFDMask(N->getMask(), N->getValueType(0));
3184 }
3185
3186 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFHW.
3188 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT) {
3189   if (VT != MVT::v8i16)
3190     return false;
3191
3192   // Lower quadword copied in order or undef.
3193   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3194     return false;
3195
3196   // Upper quadword shuffled.
3197   for (unsigned i = 4; i != 8; ++i)
3198     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3199       return false;
3200
3201   return true;
3202 }
3203
3204 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3205   return ::isPSHUFHWMask(N->getMask(), N->getValueType(0));
3206 }
3207
3208 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3209 /// is suitable for input to PSHUFLW.
3210 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT) {
3211   if (VT != MVT::v8i16)
3212     return false;
3213
3214   // Upper quadword copied in order.
3215   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3216     return false;
3217
3218   // Lower quadword shuffled.
3219   for (unsigned i = 0; i != 4; ++i)
3220     if (Mask[i] >= 4)
3221       return false;
3222
3223   return true;
3224 }
3225
3226 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3227   return ::isPSHUFLWMask(N->getMask(), N->getValueType(0));
3228 }
3229
3230 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3231 /// is suitable for input to PALIGNR.
3232 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3233                           const X86Subtarget *Subtarget) {
3234   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3235       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3236     return false;
3237
3238   unsigned NumElts = VT.getVectorNumElements();
3239   unsigned NumLanes = VT.getSizeInBits()/128;
3240   unsigned NumLaneElts = NumElts/NumLanes;
3241
3242   // Do not handle 64-bit element shuffles with palignr.
3243   if (NumLaneElts == 2)
3244     return false;
3245
3246   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3247     unsigned i;
3248     for (i = 0; i != NumLaneElts; ++i) {
3249       if (Mask[i+l] >= 0)
3250         break;
3251     }
3252
3253     // Lane is all undef, go to next lane
3254     if (i == NumLaneElts)
3255       continue;
3256
3257     int Start = Mask[i+l];
3258
3259     // Make sure its in this lane in one of the sources
3260     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3261         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3262       return false;
3263
3264     // If not lane 0, then we must match lane 0
3265     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3266       return false;
3267
3268     // Correct second source to be contiguous with first source
3269     if (Start >= (int)NumElts)
3270       Start -= NumElts - NumLaneElts;
3271
3272     // Make sure we're shifting in the right direction.
3273     if (Start <= (int)(i+l))
3274       return false;
3275
3276     Start -= i;
3277
3278     // Check the rest of the elements to see if they are consecutive.
3279     for (++i; i != NumLaneElts; ++i) {
3280       int Idx = Mask[i+l];
3281
3282       // Make sure its in this lane
3283       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3284           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3285         return false;
3286
3287       // If not lane 0, then we must match lane 0
3288       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3289         return false;
3290
3291       if (Idx >= (int)NumElts)
3292         Idx -= NumElts - NumLaneElts;
3293
3294       if (!isUndefOrEqual(Idx, Start+i))
3295         return false;
3296
3297     }
3298   }
3299
3300   return true;
3301 }
3302
3303 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3304 /// the two vector operands have swapped position.
3305 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3306                                      unsigned NumElems) {
3307   for (unsigned i = 0; i != NumElems; ++i) {
3308     int idx = Mask[i];
3309     if (idx < 0)
3310       continue;
3311     else if (idx < (int)NumElems)
3312       Mask[i] = idx + NumElems;
3313     else
3314       Mask[i] = idx - NumElems;
3315   }
3316 }
3317
3318 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3319 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3320 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3321 /// reverse of what x86 shuffles want.
3322 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3323                         bool Commuted = false) {
3324   if (!HasAVX && VT.getSizeInBits() == 256)
3325     return false;
3326
3327   unsigned NumElems = VT.getVectorNumElements();
3328   unsigned NumLanes = VT.getSizeInBits()/128;
3329   unsigned NumLaneElems = NumElems/NumLanes;
3330
3331   if (NumLaneElems != 2 && NumLaneElems != 4)
3332     return false;
3333
3334   // VSHUFPSY divides the resulting vector into 4 chunks.
3335   // The sources are also splitted into 4 chunks, and each destination
3336   // chunk must come from a different source chunk.
3337   //
3338   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3339   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3340   //
3341   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3342   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3343   //
3344   // VSHUFPDY divides the resulting vector into 4 chunks.
3345   // The sources are also splitted into 4 chunks, and each destination
3346   // chunk must come from a different source chunk.
3347   //
3348   //  SRC1 =>      X3       X2       X1       X0
3349   //  SRC2 =>      Y3       Y2       Y1       Y0
3350   //
3351   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3352   //
3353   unsigned HalfLaneElems = NumLaneElems/2;
3354   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3355     for (unsigned i = 0; i != NumLaneElems; ++i) {
3356       int Idx = Mask[i+l];
3357       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3358       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3359         return false;
3360       // For VSHUFPSY, the mask of the second half must be the same as the
3361       // first but with the appropriate offsets. This works in the same way as
3362       // VPERMILPS works with masks.
3363       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3364         continue;
3365       if (!isUndefOrEqual(Idx, Mask[i]+l))
3366         return false;
3367     }
3368   }
3369
3370   return true;
3371 }
3372
3373 bool X86::isSHUFPMask(ShuffleVectorSDNode *N, bool HasAVX) {
3374   return ::isSHUFPMask(N->getMask(), N->getValueType(0), HasAVX);
3375 }
3376
3377 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3378 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3379 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3380   EVT VT = N->getValueType(0);
3381   unsigned NumElems = VT.getVectorNumElements();
3382
3383   if (VT.getSizeInBits() != 128)
3384     return false;
3385
3386   if (NumElems != 4)
3387     return false;
3388
3389   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3390   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3391          isUndefOrEqual(N->getMaskElt(1), 7) &&
3392          isUndefOrEqual(N->getMaskElt(2), 2) &&
3393          isUndefOrEqual(N->getMaskElt(3), 3);
3394 }
3395
3396 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3397 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3398 /// <2, 3, 2, 3>
3399 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3400   EVT VT = N->getValueType(0);
3401   unsigned NumElems = VT.getVectorNumElements();
3402
3403   if (VT.getSizeInBits() != 128)
3404     return false;
3405
3406   if (NumElems != 4)
3407     return false;
3408
3409   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3410          isUndefOrEqual(N->getMaskElt(1), 3) &&
3411          isUndefOrEqual(N->getMaskElt(2), 2) &&
3412          isUndefOrEqual(N->getMaskElt(3), 3);
3413 }
3414
3415 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3416 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3417 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3418   EVT VT = N->getValueType(0);
3419
3420   if (VT.getSizeInBits() != 128)
3421     return false;
3422
3423   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3424
3425   if (NumElems != 2 && NumElems != 4)
3426     return false;
3427
3428   for (unsigned i = 0; i < NumElems/2; ++i)
3429     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3430       return false;
3431
3432   for (unsigned i = NumElems/2; i < NumElems; ++i)
3433     if (!isUndefOrEqual(N->getMaskElt(i), i))
3434       return false;
3435
3436   return true;
3437 }
3438
3439 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3440 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3441 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3442   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3443
3444   if ((NumElems != 2 && NumElems != 4)
3445       || N->getValueType(0).getSizeInBits() > 128)
3446     return false;
3447
3448   for (unsigned i = 0; i < NumElems/2; ++i)
3449     if (!isUndefOrEqual(N->getMaskElt(i), i))
3450       return false;
3451
3452   for (unsigned i = 0; i < NumElems/2; ++i)
3453     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3454       return false;
3455
3456   return true;
3457 }
3458
3459 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3460 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3461 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3462                          bool HasAVX2, bool V2IsSplat = false) {
3463   unsigned NumElts = VT.getVectorNumElements();
3464
3465   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3466          "Unsupported vector type for unpckh");
3467
3468   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3469       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3470     return false;
3471
3472   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3473   // independently on 128-bit lanes.
3474   unsigned NumLanes = VT.getSizeInBits()/128;
3475   unsigned NumLaneElts = NumElts/NumLanes;
3476
3477   for (unsigned l = 0; l != NumLanes; ++l) {
3478     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3479          i != (l+1)*NumLaneElts;
3480          i += 2, ++j) {
3481       int BitI  = Mask[i];
3482       int BitI1 = Mask[i+1];
3483       if (!isUndefOrEqual(BitI, j))
3484         return false;
3485       if (V2IsSplat) {
3486         if (!isUndefOrEqual(BitI1, NumElts))
3487           return false;
3488       } else {
3489         if (!isUndefOrEqual(BitI1, j + NumElts))
3490           return false;
3491       }
3492     }
3493   }
3494
3495   return true;
3496 }
3497
3498 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3499   return ::isUNPCKLMask(N->getMask(), N->getValueType(0), HasAVX2, V2IsSplat);
3500 }
3501
3502 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3503 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3504 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3505                          bool HasAVX2, bool V2IsSplat = false) {
3506   unsigned NumElts = VT.getVectorNumElements();
3507
3508   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3509          "Unsupported vector type for unpckh");
3510
3511   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3512       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3513     return false;
3514
3515   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3516   // independently on 128-bit lanes.
3517   unsigned NumLanes = VT.getSizeInBits()/128;
3518   unsigned NumLaneElts = NumElts/NumLanes;
3519
3520   for (unsigned l = 0; l != NumLanes; ++l) {
3521     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3522          i != (l+1)*NumLaneElts; i += 2, ++j) {
3523       int BitI  = Mask[i];
3524       int BitI1 = Mask[i+1];
3525       if (!isUndefOrEqual(BitI, j))
3526         return false;
3527       if (V2IsSplat) {
3528         if (isUndefOrEqual(BitI1, NumElts))
3529           return false;
3530       } else {
3531         if (!isUndefOrEqual(BitI1, j+NumElts))
3532           return false;
3533       }
3534     }
3535   }
3536   return true;
3537 }
3538
3539 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3540   return ::isUNPCKHMask(N->getMask(), N->getValueType(0), HasAVX2, V2IsSplat);
3541 }
3542
3543 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3544 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3545 /// <0, 0, 1, 1>
3546 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3547                                   bool HasAVX2) {
3548   unsigned NumElts = VT.getVectorNumElements();
3549
3550   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3551          "Unsupported vector type for unpckh");
3552
3553   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3554       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3555     return false;
3556
3557   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3558   // FIXME: Need a better way to get rid of this, there's no latency difference
3559   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3560   // the former later. We should also remove the "_undef" special mask.
3561   if (NumElts == 4 && VT.getSizeInBits() == 256)
3562     return false;
3563
3564   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3565   // independently on 128-bit lanes.
3566   unsigned NumLanes = VT.getSizeInBits()/128;
3567   unsigned NumLaneElts = NumElts/NumLanes;
3568
3569   for (unsigned l = 0; l != NumLanes; ++l) {
3570     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3571          i != (l+1)*NumLaneElts;
3572          i += 2, ++j) {
3573       int BitI  = Mask[i];
3574       int BitI1 = Mask[i+1];
3575
3576       if (!isUndefOrEqual(BitI, j))
3577         return false;
3578       if (!isUndefOrEqual(BitI1, j))
3579         return false;
3580     }
3581   }
3582
3583   return true;
3584 }
3585
3586 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3587   return ::isUNPCKL_v_undef_Mask(N->getMask(), N->getValueType(0), HasAVX2);
3588 }
3589
3590 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3591 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3592 /// <2, 2, 3, 3>
3593 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3594   unsigned NumElts = VT.getVectorNumElements();
3595
3596   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3597          "Unsupported vector type for unpckh");
3598
3599   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3600       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3601     return false;
3602
3603   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3604   // independently on 128-bit lanes.
3605   unsigned NumLanes = VT.getSizeInBits()/128;
3606   unsigned NumLaneElts = NumElts/NumLanes;
3607
3608   for (unsigned l = 0; l != NumLanes; ++l) {
3609     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3610          i != (l+1)*NumLaneElts; i += 2, ++j) {
3611       int BitI  = Mask[i];
3612       int BitI1 = Mask[i+1];
3613       if (!isUndefOrEqual(BitI, j))
3614         return false;
3615       if (!isUndefOrEqual(BitI1, j))
3616         return false;
3617     }
3618   }
3619   return true;
3620 }
3621
3622 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3623   return ::isUNPCKH_v_undef_Mask(N->getMask(), N->getValueType(0), HasAVX2);
3624 }
3625
3626 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3627 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3628 /// MOVSD, and MOVD, i.e. setting the lowest element.
3629 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3630   if (VT.getVectorElementType().getSizeInBits() < 32)
3631     return false;
3632   if (VT.getSizeInBits() == 256)
3633     return false;
3634
3635   unsigned NumElts = VT.getVectorNumElements();
3636
3637   if (!isUndefOrEqual(Mask[0], NumElts))
3638     return false;
3639
3640   for (unsigned i = 1; i != NumElts; ++i)
3641     if (!isUndefOrEqual(Mask[i], i))
3642       return false;
3643
3644   return true;
3645 }
3646
3647 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3648   return ::isMOVLMask(N->getMask(), N->getValueType(0));
3649 }
3650
3651 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3652 /// as permutations between 128-bit chunks or halves. As an example: this
3653 /// shuffle bellow:
3654 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3655 /// The first half comes from the second half of V1 and the second half from the
3656 /// the second half of V2.
3657 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3658   if (!HasAVX || VT.getSizeInBits() != 256)
3659     return false;
3660
3661   // The shuffle result is divided into half A and half B. In total the two
3662   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3663   // B must come from C, D, E or F.
3664   unsigned HalfSize = VT.getVectorNumElements()/2;
3665   bool MatchA = false, MatchB = false;
3666
3667   // Check if A comes from one of C, D, E, F.
3668   for (unsigned Half = 0; Half != 4; ++Half) {
3669     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3670       MatchA = true;
3671       break;
3672     }
3673   }
3674
3675   // Check if B comes from one of C, D, E, F.
3676   for (unsigned Half = 0; Half != 4; ++Half) {
3677     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3678       MatchB = true;
3679       break;
3680     }
3681   }
3682
3683   return MatchA && MatchB;
3684 }
3685
3686 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3687 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3688 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3689   EVT VT = SVOp->getValueType(0);
3690
3691   unsigned HalfSize = VT.getVectorNumElements()/2;
3692
3693   unsigned FstHalf = 0, SndHalf = 0;
3694   for (unsigned i = 0; i < HalfSize; ++i) {
3695     if (SVOp->getMaskElt(i) > 0) {
3696       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3697       break;
3698     }
3699   }
3700   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3701     if (SVOp->getMaskElt(i) > 0) {
3702       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3703       break;
3704     }
3705   }
3706
3707   return (FstHalf | (SndHalf << 4));
3708 }
3709
3710 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3711 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3712 /// Note that VPERMIL mask matching is different depending whether theunderlying
3713 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3714 /// to the same elements of the low, but to the higher half of the source.
3715 /// In VPERMILPD the two lanes could be shuffled independently of each other
3716 /// with the same restriction that lanes can't be crossed.
3717 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3718   if (!HasAVX)
3719     return false;
3720
3721   unsigned NumElts = VT.getVectorNumElements();
3722   // Only match 256-bit with 32/64-bit types
3723   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3724     return false;
3725
3726   unsigned NumLanes = VT.getSizeInBits()/128;
3727   unsigned LaneSize = NumElts/NumLanes;
3728   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3729     for (unsigned i = 0; i != LaneSize; ++i) {
3730       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3731         return false;
3732       if (NumElts != 8 || l == 0)
3733         continue;
3734       // VPERMILPS handling
3735       if (Mask[i] < 0)
3736         continue;
3737       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3738         return false;
3739     }
3740   }
3741
3742   return true;
3743 }
3744
3745 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3746 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3747 /// element of vector 2 and the other elements to come from vector 1 in order.
3748 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3749                                bool V2IsSplat = false, bool V2IsUndef = false) {
3750   unsigned NumOps = VT.getVectorNumElements();
3751   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3752     return false;
3753
3754   if (!isUndefOrEqual(Mask[0], 0))
3755     return false;
3756
3757   for (unsigned i = 1; i != NumOps; ++i)
3758     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3759           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3760           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3761       return false;
3762
3763   return true;
3764 }
3765
3766 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3767                            bool V2IsUndef = false) {
3768   return isCommutedMOVLMask(N->getMask(), N->getValueType(0),
3769                             V2IsSplat, V2IsUndef);
3770 }
3771
3772 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3773 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3774 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3775 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3776                          const X86Subtarget *Subtarget) {
3777   if (!Subtarget->hasSSE3())
3778     return false;
3779
3780   // The second vector must be undef
3781   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3782     return false;
3783
3784   EVT VT = N->getValueType(0);
3785   unsigned NumElems = VT.getVectorNumElements();
3786
3787   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3788       (VT.getSizeInBits() == 256 && NumElems != 8))
3789     return false;
3790
3791   // "i+1" is the value the indexed mask element must have
3792   for (unsigned i = 0; i < NumElems; i += 2)
3793     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3794         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3795       return false;
3796
3797   return true;
3798 }
3799
3800 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3801 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3802 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3803 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3804                          const X86Subtarget *Subtarget) {
3805   if (!Subtarget->hasSSE3())
3806     return false;
3807
3808   // The second vector must be undef
3809   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3810     return false;
3811
3812   EVT VT = N->getValueType(0);
3813   unsigned NumElems = VT.getVectorNumElements();
3814
3815   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3816       (VT.getSizeInBits() == 256 && NumElems != 8))
3817     return false;
3818
3819   // "i" is the value the indexed mask element must have
3820   for (unsigned i = 0; i != NumElems; i += 2)
3821     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3822         !isUndefOrEqual(N->getMaskElt(i+1), i))
3823       return false;
3824
3825   return true;
3826 }
3827
3828 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3829 /// specifies a shuffle of elements that is suitable for input to 256-bit
3830 /// version of MOVDDUP.
3831 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3832   unsigned NumElts = VT.getVectorNumElements();
3833
3834   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3835     return false;
3836
3837   for (unsigned i = 0; i != NumElts/2; ++i)
3838     if (!isUndefOrEqual(Mask[i], 0))
3839       return false;
3840   for (unsigned i = NumElts/2; i != NumElts; ++i)
3841     if (!isUndefOrEqual(Mask[i], NumElts/2))
3842       return false;
3843   return true;
3844 }
3845
3846 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to 128-bit
3848 /// version of MOVDDUP.
3849 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3850   EVT VT = N->getValueType(0);
3851
3852   if (VT.getSizeInBits() != 128)
3853     return false;
3854
3855   unsigned e = VT.getVectorNumElements() / 2;
3856   for (unsigned i = 0; i != e; ++i)
3857     if (!isUndefOrEqual(N->getMaskElt(i), i))
3858       return false;
3859   for (unsigned i = 0; i != e; ++i)
3860     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3861       return false;
3862   return true;
3863 }
3864
3865 /// isVEXTRACTF128Index - Return true if the specified
3866 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3867 /// suitable for input to VEXTRACTF128.
3868 bool X86::isVEXTRACTF128Index(SDNode *N) {
3869   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3870     return false;
3871
3872   // The index should be aligned on a 128-bit boundary.
3873   uint64_t Index =
3874     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3875
3876   unsigned VL = N->getValueType(0).getVectorNumElements();
3877   unsigned VBits = N->getValueType(0).getSizeInBits();
3878   unsigned ElSize = VBits / VL;
3879   bool Result = (Index * ElSize) % 128 == 0;
3880
3881   return Result;
3882 }
3883
3884 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3885 /// operand specifies a subvector insert that is suitable for input to
3886 /// VINSERTF128.
3887 bool X86::isVINSERTF128Index(SDNode *N) {
3888   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3889     return false;
3890
3891   // The index should be aligned on a 128-bit boundary.
3892   uint64_t Index =
3893     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3894
3895   unsigned VL = N->getValueType(0).getVectorNumElements();
3896   unsigned VBits = N->getValueType(0).getSizeInBits();
3897   unsigned ElSize = VBits / VL;
3898   bool Result = (Index * ElSize) % 128 == 0;
3899
3900   return Result;
3901 }
3902
3903 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3904 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3905 /// Handles 128-bit and 256-bit.
3906 unsigned X86::getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3907   EVT VT = N->getValueType(0);
3908
3909   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3910          "Unsupported vector type for PSHUF/SHUFP");
3911
3912   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3913   // independently on 128-bit lanes.
3914   unsigned NumElts = VT.getVectorNumElements();
3915   unsigned NumLanes = VT.getSizeInBits()/128;
3916   unsigned NumLaneElts = NumElts/NumLanes;
3917
3918   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3919          "Only supports 2 or 4 elements per lane");
3920
3921   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3922   unsigned Mask = 0;
3923   for (unsigned i = 0; i != NumElts; ++i) {
3924     int Elt = N->getMaskElt(i);
3925     if (Elt < 0) continue;
3926     Elt %= NumLaneElts;
3927     unsigned ShAmt = i << Shift;
3928     if (ShAmt >= 8) ShAmt -= 8;
3929     Mask |= Elt << ShAmt;
3930   }
3931
3932   return Mask;
3933 }
3934
3935 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3936 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3937 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3939   unsigned Mask = 0;
3940   // 8 nodes, but we only care about the last 4.
3941   for (unsigned i = 7; i >= 4; --i) {
3942     int Val = SVOp->getMaskElt(i);
3943     if (Val >= 0)
3944       Mask |= (Val - 4);
3945     if (i != 4)
3946       Mask <<= 2;
3947   }
3948   return Mask;
3949 }
3950
3951 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3952 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3953 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3954   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3955   unsigned Mask = 0;
3956   // 8 nodes, but we only care about the first 4.
3957   for (int i = 3; i >= 0; --i) {
3958     int Val = SVOp->getMaskElt(i);
3959     if (Val >= 0)
3960       Mask |= Val;
3961     if (i != 0)
3962       Mask <<= 2;
3963   }
3964   return Mask;
3965 }
3966
3967 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3968 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3969 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3970   EVT VT = SVOp->getValueType(0);
3971   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3972
3973   unsigned NumElts = VT.getVectorNumElements();
3974   unsigned NumLanes = VT.getSizeInBits()/128;
3975   unsigned NumLaneElts = NumElts/NumLanes;
3976
3977   int Val = 0;
3978   unsigned i;
3979   for (i = 0; i != NumElts; ++i) {
3980     Val = SVOp->getMaskElt(i);
3981     if (Val >= 0)
3982       break;
3983   }
3984   if (Val >= (int)NumElts)
3985     Val -= NumElts - NumLaneElts;
3986
3987   assert(Val - i > 0 && "PALIGNR imm should be positive");
3988   return (Val - i) * EltSize;
3989 }
3990
3991 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3992 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3993 /// instructions.
3994 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3995   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3996     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3997
3998   uint64_t Index =
3999     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4000
4001   EVT VecVT = N->getOperand(0).getValueType();
4002   EVT ElVT = VecVT.getVectorElementType();
4003
4004   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4005   return Index / NumElemsPerChunk;
4006 }
4007
4008 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4009 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4010 /// instructions.
4011 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4012   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4013     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4014
4015   uint64_t Index =
4016     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4017
4018   EVT VecVT = N->getValueType(0);
4019   EVT ElVT = VecVT.getVectorElementType();
4020
4021   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4022   return Index / NumElemsPerChunk;
4023 }
4024
4025 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4026 /// constant +0.0.
4027 bool X86::isZeroNode(SDValue Elt) {
4028   return ((isa<ConstantSDNode>(Elt) &&
4029            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4030           (isa<ConstantFPSDNode>(Elt) &&
4031            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4032 }
4033
4034 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4035 /// their permute mask.
4036 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4037                                     SelectionDAG &DAG) {
4038   EVT VT = SVOp->getValueType(0);
4039   unsigned NumElems = VT.getVectorNumElements();
4040   SmallVector<int, 8> MaskVec;
4041
4042   for (unsigned i = 0; i != NumElems; ++i) {
4043     int idx = SVOp->getMaskElt(i);
4044     if (idx < 0)
4045       MaskVec.push_back(idx);
4046     else if (idx < (int)NumElems)
4047       MaskVec.push_back(idx + NumElems);
4048     else
4049       MaskVec.push_back(idx - NumElems);
4050   }
4051   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4052                               SVOp->getOperand(0), &MaskVec[0]);
4053 }
4054
4055 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4056 /// match movhlps. The lower half elements should come from upper half of
4057 /// V1 (and in order), and the upper half elements should come from the upper
4058 /// half of V2 (and in order).
4059 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4060   EVT VT = Op->getValueType(0);
4061   if (VT.getSizeInBits() != 128)
4062     return false;
4063   if (VT.getVectorNumElements() != 4)
4064     return false;
4065   for (unsigned i = 0, e = 2; i != e; ++i)
4066     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4067       return false;
4068   for (unsigned i = 2; i != 4; ++i)
4069     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4070       return false;
4071   return true;
4072 }
4073
4074 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4075 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4076 /// required.
4077 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4078   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4079     return false;
4080   N = N->getOperand(0).getNode();
4081   if (!ISD::isNON_EXTLoad(N))
4082     return false;
4083   if (LD)
4084     *LD = cast<LoadSDNode>(N);
4085   return true;
4086 }
4087
4088 // Test whether the given value is a vector value which will be legalized
4089 // into a load.
4090 static bool WillBeConstantPoolLoad(SDNode *N) {
4091   if (N->getOpcode() != ISD::BUILD_VECTOR)
4092     return false;
4093
4094   // Check for any non-constant elements.
4095   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4096     switch (N->getOperand(i).getNode()->getOpcode()) {
4097     case ISD::UNDEF:
4098     case ISD::ConstantFP:
4099     case ISD::Constant:
4100       break;
4101     default:
4102       return false;
4103     }
4104
4105   // Vectors of all-zeros and all-ones are materialized with special
4106   // instructions rather than being loaded.
4107   return !ISD::isBuildVectorAllZeros(N) &&
4108          !ISD::isBuildVectorAllOnes(N);
4109 }
4110
4111 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4112 /// match movlp{s|d}. The lower half elements should come from lower half of
4113 /// V1 (and in order), and the upper half elements should come from the upper
4114 /// half of V2 (and in order). And since V1 will become the source of the
4115 /// MOVLP, it must be either a vector load or a scalar load to vector.
4116 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4117                                ShuffleVectorSDNode *Op) {
4118   EVT VT = Op->getValueType(0);
4119   if (VT.getSizeInBits() != 128)
4120     return false;
4121
4122   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4123     return false;
4124   // Is V2 is a vector load, don't do this transformation. We will try to use
4125   // load folding shufps op.
4126   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4127     return false;
4128
4129   unsigned NumElems = VT.getVectorNumElements();
4130
4131   if (NumElems != 2 && NumElems != 4)
4132     return false;
4133   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4134     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4135       return false;
4136   for (unsigned i = NumElems/2; i != NumElems; ++i)
4137     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4138       return false;
4139   return true;
4140 }
4141
4142 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4143 /// all the same.
4144 static bool isSplatVector(SDNode *N) {
4145   if (N->getOpcode() != ISD::BUILD_VECTOR)
4146     return false;
4147
4148   SDValue SplatValue = N->getOperand(0);
4149   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4150     if (N->getOperand(i) != SplatValue)
4151       return false;
4152   return true;
4153 }
4154
4155 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4156 /// to an zero vector.
4157 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4158 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4159   SDValue V1 = N->getOperand(0);
4160   SDValue V2 = N->getOperand(1);
4161   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4162   for (unsigned i = 0; i != NumElems; ++i) {
4163     int Idx = N->getMaskElt(i);
4164     if (Idx >= (int)NumElems) {
4165       unsigned Opc = V2.getOpcode();
4166       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4167         continue;
4168       if (Opc != ISD::BUILD_VECTOR ||
4169           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4170         return false;
4171     } else if (Idx >= 0) {
4172       unsigned Opc = V1.getOpcode();
4173       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4174         continue;
4175       if (Opc != ISD::BUILD_VECTOR ||
4176           !X86::isZeroNode(V1.getOperand(Idx)))
4177         return false;
4178     }
4179   }
4180   return true;
4181 }
4182
4183 /// getZeroVector - Returns a vector of specified type with all zero elements.
4184 ///
4185 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4186                              SelectionDAG &DAG, DebugLoc dl) {
4187   assert(VT.isVector() && "Expected a vector type");
4188
4189   // Always build SSE zero vectors as <4 x i32> bitcasted
4190   // to their dest type. This ensures they get CSE'd.
4191   SDValue Vec;
4192   if (VT.getSizeInBits() == 128) {  // SSE
4193     if (Subtarget->hasSSE2()) {  // SSE2
4194       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4195       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4196     } else { // SSE1
4197       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4198       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4199     }
4200   } else if (VT.getSizeInBits() == 256) { // AVX
4201     if (Subtarget->hasAVX2()) { // AVX2
4202       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4203       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4205     } else {
4206       // 256-bit logic and arithmetic instructions in AVX are all
4207       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4208       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4209       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4210       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4211     }
4212   }
4213   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4214 }
4215
4216 /// getOnesVector - Returns a vector of specified type with all bits set.
4217 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4218 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4219 /// Then bitcast to their original type, ensuring they get CSE'd.
4220 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4221                              DebugLoc dl) {
4222   assert(VT.isVector() && "Expected a vector type");
4223   assert((VT.is128BitVector() || VT.is256BitVector())
4224          && "Expected a 128-bit or 256-bit vector type");
4225
4226   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4227   SDValue Vec;
4228   if (VT.getSizeInBits() == 256) {
4229     if (HasAVX2) { // AVX2
4230       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4232     } else { // AVX
4233       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4234       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4235                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4236       Vec = Insert128BitVector(InsV, Vec,
4237                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4238     }
4239   } else {
4240     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4241   }
4242
4243   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4244 }
4245
4246 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4247 /// that point to V2 points to its first element.
4248 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4249   EVT VT = SVOp->getValueType(0);
4250   unsigned NumElems = VT.getVectorNumElements();
4251
4252   bool Changed = false;
4253   SmallVector<int, 8> MaskVec(SVOp->getMask().begin(), SVOp->getMask().end());
4254
4255   for (unsigned i = 0; i != NumElems; ++i) {
4256     if (MaskVec[i] > (int)NumElems) {
4257       MaskVec[i] = NumElems;
4258       Changed = true;
4259     }
4260   }
4261   if (Changed)
4262     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4263                                 SVOp->getOperand(1), &MaskVec[0]);
4264   return SDValue(SVOp, 0);
4265 }
4266
4267 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4268 /// operation of specified width.
4269 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4270                        SDValue V2) {
4271   unsigned NumElems = VT.getVectorNumElements();
4272   SmallVector<int, 8> Mask;
4273   Mask.push_back(NumElems);
4274   for (unsigned i = 1; i != NumElems; ++i)
4275     Mask.push_back(i);
4276   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4277 }
4278
4279 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4280 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4281                           SDValue V2) {
4282   unsigned NumElems = VT.getVectorNumElements();
4283   SmallVector<int, 8> Mask;
4284   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4285     Mask.push_back(i);
4286     Mask.push_back(i + NumElems);
4287   }
4288   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4289 }
4290
4291 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4292 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4293                           SDValue V2) {
4294   unsigned NumElems = VT.getVectorNumElements();
4295   unsigned Half = NumElems/2;
4296   SmallVector<int, 8> Mask;
4297   for (unsigned i = 0; i != Half; ++i) {
4298     Mask.push_back(i + Half);
4299     Mask.push_back(i + NumElems + Half);
4300   }
4301   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4302 }
4303
4304 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4305 // a generic shuffle instruction because the target has no such instructions.
4306 // Generate shuffles which repeat i16 and i8 several times until they can be
4307 // represented by v4f32 and then be manipulated by target suported shuffles.
4308 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4309   EVT VT = V.getValueType();
4310   int NumElems = VT.getVectorNumElements();
4311   DebugLoc dl = V.getDebugLoc();
4312
4313   while (NumElems > 4) {
4314     if (EltNo < NumElems/2) {
4315       V = getUnpackl(DAG, dl, VT, V, V);
4316     } else {
4317       V = getUnpackh(DAG, dl, VT, V, V);
4318       EltNo -= NumElems/2;
4319     }
4320     NumElems >>= 1;
4321   }
4322   return V;
4323 }
4324
4325 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4326 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4327   EVT VT = V.getValueType();
4328   DebugLoc dl = V.getDebugLoc();
4329   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4330          && "Vector size not supported");
4331
4332   if (VT.getSizeInBits() == 128) {
4333     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4334     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4335     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4336                              &SplatMask[0]);
4337   } else {
4338     // To use VPERMILPS to splat scalars, the second half of indicies must
4339     // refer to the higher part, which is a duplication of the lower one,
4340     // because VPERMILPS can only handle in-lane permutations.
4341     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4342                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4343
4344     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4345     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4346                              &SplatMask[0]);
4347   }
4348
4349   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4350 }
4351
4352 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4353 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4354   EVT SrcVT = SV->getValueType(0);
4355   SDValue V1 = SV->getOperand(0);
4356   DebugLoc dl = SV->getDebugLoc();
4357
4358   int EltNo = SV->getSplatIndex();
4359   int NumElems = SrcVT.getVectorNumElements();
4360   unsigned Size = SrcVT.getSizeInBits();
4361
4362   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4363           "Unknown how to promote splat for type");
4364
4365   // Extract the 128-bit part containing the splat element and update
4366   // the splat element index when it refers to the higher register.
4367   if (Size == 256) {
4368     unsigned Idx = (EltNo >= NumElems/2) ? NumElems/2 : 0;
4369     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4370     if (Idx > 0)
4371       EltNo -= NumElems/2;
4372   }
4373
4374   // All i16 and i8 vector types can't be used directly by a generic shuffle
4375   // instruction because the target has no such instruction. Generate shuffles
4376   // which repeat i16 and i8 several times until they fit in i32, and then can
4377   // be manipulated by target suported shuffles.
4378   EVT EltVT = SrcVT.getVectorElementType();
4379   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4380     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4381
4382   // Recreate the 256-bit vector and place the same 128-bit vector
4383   // into the low and high part. This is necessary because we want
4384   // to use VPERM* to shuffle the vectors
4385   if (Size == 256) {
4386     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4387                          DAG.getConstant(0, MVT::i32), DAG, dl);
4388     V1 = Insert128BitVector(InsV, V1,
4389                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4390   }
4391
4392   return getLegalSplat(DAG, V1, EltNo);
4393 }
4394
4395 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4396 /// vector of zero or undef vector.  This produces a shuffle where the low
4397 /// element of V2 is swizzled into the zero/undef vector, landing at element
4398 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4399 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4400                                            bool IsZero,
4401                                            const X86Subtarget *Subtarget,
4402                                            SelectionDAG &DAG) {
4403   EVT VT = V2.getValueType();
4404   SDValue V1 = IsZero
4405     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4406   unsigned NumElems = VT.getVectorNumElements();
4407   SmallVector<int, 16> MaskVec;
4408   for (unsigned i = 0; i != NumElems; ++i)
4409     // If this is the insertion idx, put the low elt of V2 here.
4410     MaskVec.push_back(i == Idx ? NumElems : i);
4411   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4412 }
4413
4414 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4415 /// element of the result of the vector shuffle.
4416 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4417                                    unsigned Depth) {
4418   if (Depth == 6)
4419     return SDValue();  // Limit search depth.
4420
4421   SDValue V = SDValue(N, 0);
4422   EVT VT = V.getValueType();
4423   unsigned Opcode = V.getOpcode();
4424
4425   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4426   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4427     Index = SV->getMaskElt(Index);
4428
4429     if (Index < 0)
4430       return DAG.getUNDEF(VT.getVectorElementType());
4431
4432     unsigned NumElems = VT.getVectorNumElements();
4433     SDValue NewV = (Index < (int)NumElems) ? SV->getOperand(0)
4434                                            : SV->getOperand(1);
4435     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4436   }
4437
4438   // Recurse into target specific vector shuffles to find scalars.
4439   if (isTargetShuffle(Opcode)) {
4440     unsigned NumElems = VT.getVectorNumElements();
4441     SmallVector<unsigned, 16> ShuffleMask;
4442     SDValue ImmN;
4443
4444     switch(Opcode) {
4445     case X86ISD::SHUFP:
4446       ImmN = N->getOperand(N->getNumOperands()-1);
4447       DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4448                       ShuffleMask);
4449       break;
4450     case X86ISD::UNPCKH:
4451       DecodeUNPCKHMask(VT, ShuffleMask);
4452       break;
4453     case X86ISD::UNPCKL:
4454       DecodeUNPCKLMask(VT, ShuffleMask);
4455       break;
4456     case X86ISD::MOVHLPS:
4457       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4458       break;
4459     case X86ISD::MOVLHPS:
4460       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4461       break;
4462     case X86ISD::PSHUFD:
4463     case X86ISD::VPERMILP:
4464       ImmN = N->getOperand(N->getNumOperands()-1);
4465       DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4466                       ShuffleMask);
4467       break;
4468     case X86ISD::PSHUFHW:
4469       ImmN = N->getOperand(N->getNumOperands()-1);
4470       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4471                         ShuffleMask);
4472       break;
4473     case X86ISD::PSHUFLW:
4474       ImmN = N->getOperand(N->getNumOperands()-1);
4475       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4476                         ShuffleMask);
4477       break;
4478     case X86ISD::MOVSS:
4479     case X86ISD::MOVSD: {
4480       // The index 0 always comes from the first element of the second source,
4481       // this is why MOVSS and MOVSD are used in the first place. The other
4482       // elements come from the other positions of the first source vector.
4483       unsigned OpNum = (Index == 0) ? 1 : 0;
4484       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4485                                  Depth+1);
4486     }
4487     case X86ISD::VPERM2X128:
4488       ImmN = N->getOperand(N->getNumOperands()-1);
4489       DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4490                            ShuffleMask);
4491       break;
4492     case X86ISD::MOVDDUP:
4493     case X86ISD::MOVLHPD:
4494     case X86ISD::MOVLPD:
4495     case X86ISD::MOVLPS:
4496     case X86ISD::MOVSHDUP:
4497     case X86ISD::MOVSLDUP:
4498     case X86ISD::PALIGN:
4499       return SDValue(); // Not yet implemented.
4500     default: llvm_unreachable("unknown target shuffle node");
4501     }
4502
4503     Index = ShuffleMask[Index];
4504     if (Index < 0)
4505       return DAG.getUNDEF(VT.getVectorElementType());
4506
4507     SDValue NewV = (Index < (int)NumElems) ? N->getOperand(0)
4508                                            : N->getOperand(1);
4509     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4510                                Depth+1);
4511   }
4512
4513   // Actual nodes that may contain scalar elements
4514   if (Opcode == ISD::BITCAST) {
4515     V = V.getOperand(0);
4516     EVT SrcVT = V.getValueType();
4517     unsigned NumElems = VT.getVectorNumElements();
4518
4519     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4520       return SDValue();
4521   }
4522
4523   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4524     return (Index == 0) ? V.getOperand(0)
4525                           : DAG.getUNDEF(VT.getVectorElementType());
4526
4527   if (V.getOpcode() == ISD::BUILD_VECTOR)
4528     return V.getOperand(Index);
4529
4530   return SDValue();
4531 }
4532
4533 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4534 /// shuffle operation which come from a consecutively from a zero. The
4535 /// search can start in two different directions, from left or right.
4536 static
4537 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4538                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4539   int i = 0;
4540
4541   while (i < NumElems) {
4542     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4543     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4544     if (!(Elt.getNode() &&
4545          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4546       break;
4547     ++i;
4548   }
4549
4550   return i;
4551 }
4552
4553 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4554 /// MaskE correspond consecutively to elements from one of the vector operands,
4555 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4556 static
4557 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4558                               int OpIdx, int NumElems, unsigned &OpNum) {
4559   bool SeenV1 = false;
4560   bool SeenV2 = false;
4561
4562   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4563     int Idx = SVOp->getMaskElt(i);
4564     // Ignore undef indicies
4565     if (Idx < 0)
4566       continue;
4567
4568     if (Idx < NumElems)
4569       SeenV1 = true;
4570     else
4571       SeenV2 = true;
4572
4573     // Only accept consecutive elements from the same vector
4574     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4575       return false;
4576   }
4577
4578   OpNum = SeenV1 ? 0 : 1;
4579   return true;
4580 }
4581
4582 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4583 /// logical left shift of a vector.
4584 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4585                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4586   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4587   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4588               false /* check zeros from right */, DAG);
4589   unsigned OpSrc;
4590
4591   if (!NumZeros)
4592     return false;
4593
4594   // Considering the elements in the mask that are not consecutive zeros,
4595   // check if they consecutively come from only one of the source vectors.
4596   //
4597   //               V1 = {X, A, B, C}     0
4598   //                         \  \  \    /
4599   //   vector_shuffle V1, V2 <1, 2, 3, X>
4600   //
4601   if (!isShuffleMaskConsecutive(SVOp,
4602             0,                   // Mask Start Index
4603             NumElems-NumZeros-1, // Mask End Index
4604             NumZeros,            // Where to start looking in the src vector
4605             NumElems,            // Number of elements in vector
4606             OpSrc))              // Which source operand ?
4607     return false;
4608
4609   isLeft = false;
4610   ShAmt = NumZeros;
4611   ShVal = SVOp->getOperand(OpSrc);
4612   return true;
4613 }
4614
4615 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4616 /// logical left shift of a vector.
4617 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4618                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4619   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4620   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4621               true /* check zeros from left */, DAG);
4622   unsigned OpSrc;
4623
4624   if (!NumZeros)
4625     return false;
4626
4627   // Considering the elements in the mask that are not consecutive zeros,
4628   // check if they consecutively come from only one of the source vectors.
4629   //
4630   //                           0    { A, B, X, X } = V2
4631   //                          / \    /  /
4632   //   vector_shuffle V1, V2 <X, X, 4, 5>
4633   //
4634   if (!isShuffleMaskConsecutive(SVOp,
4635             NumZeros,     // Mask Start Index
4636             NumElems-1,   // Mask End Index
4637             0,            // Where to start looking in the src vector
4638             NumElems,     // Number of elements in vector
4639             OpSrc))       // Which source operand ?
4640     return false;
4641
4642   isLeft = true;
4643   ShAmt = NumZeros;
4644   ShVal = SVOp->getOperand(OpSrc);
4645   return true;
4646 }
4647
4648 /// isVectorShift - Returns true if the shuffle can be implemented as a
4649 /// logical left or right shift of a vector.
4650 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4651                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4652   // Although the logic below support any bitwidth size, there are no
4653   // shift instructions which handle more than 128-bit vectors.
4654   if (SVOp->getValueType(0).getSizeInBits() > 128)
4655     return false;
4656
4657   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4658       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4659     return true;
4660
4661   return false;
4662 }
4663
4664 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4665 ///
4666 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4667                                        unsigned NumNonZero, unsigned NumZero,
4668                                        SelectionDAG &DAG,
4669                                        const X86Subtarget* Subtarget,
4670                                        const TargetLowering &TLI) {
4671   if (NumNonZero > 8)
4672     return SDValue();
4673
4674   DebugLoc dl = Op.getDebugLoc();
4675   SDValue V(0, 0);
4676   bool First = true;
4677   for (unsigned i = 0; i < 16; ++i) {
4678     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4679     if (ThisIsNonZero && First) {
4680       if (NumZero)
4681         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4682       else
4683         V = DAG.getUNDEF(MVT::v8i16);
4684       First = false;
4685     }
4686
4687     if ((i & 1) != 0) {
4688       SDValue ThisElt(0, 0), LastElt(0, 0);
4689       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4690       if (LastIsNonZero) {
4691         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4692                               MVT::i16, Op.getOperand(i-1));
4693       }
4694       if (ThisIsNonZero) {
4695         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4696         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4697                               ThisElt, DAG.getConstant(8, MVT::i8));
4698         if (LastIsNonZero)
4699           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4700       } else
4701         ThisElt = LastElt;
4702
4703       if (ThisElt.getNode())
4704         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4705                         DAG.getIntPtrConstant(i/2));
4706     }
4707   }
4708
4709   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4710 }
4711
4712 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4713 ///
4714 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4715                                      unsigned NumNonZero, unsigned NumZero,
4716                                      SelectionDAG &DAG,
4717                                      const X86Subtarget* Subtarget,
4718                                      const TargetLowering &TLI) {
4719   if (NumNonZero > 4)
4720     return SDValue();
4721
4722   DebugLoc dl = Op.getDebugLoc();
4723   SDValue V(0, 0);
4724   bool First = true;
4725   for (unsigned i = 0; i < 8; ++i) {
4726     bool isNonZero = (NonZeros & (1 << i)) != 0;
4727     if (isNonZero) {
4728       if (First) {
4729         if (NumZero)
4730           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4731         else
4732           V = DAG.getUNDEF(MVT::v8i16);
4733         First = false;
4734       }
4735       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4736                       MVT::v8i16, V, Op.getOperand(i),
4737                       DAG.getIntPtrConstant(i));
4738     }
4739   }
4740
4741   return V;
4742 }
4743
4744 /// getVShift - Return a vector logical shift node.
4745 ///
4746 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4747                          unsigned NumBits, SelectionDAG &DAG,
4748                          const TargetLowering &TLI, DebugLoc dl) {
4749   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4750   EVT ShVT = MVT::v2i64;
4751   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4752   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4753   return DAG.getNode(ISD::BITCAST, dl, VT,
4754                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4755                              DAG.getConstant(NumBits,
4756                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4757 }
4758
4759 SDValue
4760 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4761                                           SelectionDAG &DAG) const {
4762
4763   // Check if the scalar load can be widened into a vector load. And if
4764   // the address is "base + cst" see if the cst can be "absorbed" into
4765   // the shuffle mask.
4766   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4767     SDValue Ptr = LD->getBasePtr();
4768     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4769       return SDValue();
4770     EVT PVT = LD->getValueType(0);
4771     if (PVT != MVT::i32 && PVT != MVT::f32)
4772       return SDValue();
4773
4774     int FI = -1;
4775     int64_t Offset = 0;
4776     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4777       FI = FINode->getIndex();
4778       Offset = 0;
4779     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4780                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4781       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4782       Offset = Ptr.getConstantOperandVal(1);
4783       Ptr = Ptr.getOperand(0);
4784     } else {
4785       return SDValue();
4786     }
4787
4788     // FIXME: 256-bit vector instructions don't require a strict alignment,
4789     // improve this code to support it better.
4790     unsigned RequiredAlign = VT.getSizeInBits()/8;
4791     SDValue Chain = LD->getChain();
4792     // Make sure the stack object alignment is at least 16 or 32.
4793     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4794     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4795       if (MFI->isFixedObjectIndex(FI)) {
4796         // Can't change the alignment. FIXME: It's possible to compute
4797         // the exact stack offset and reference FI + adjust offset instead.
4798         // If someone *really* cares about this. That's the way to implement it.
4799         return SDValue();
4800       } else {
4801         MFI->setObjectAlignment(FI, RequiredAlign);
4802       }
4803     }
4804
4805     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4806     // Ptr + (Offset & ~15).
4807     if (Offset < 0)
4808       return SDValue();
4809     if ((Offset % RequiredAlign) & 3)
4810       return SDValue();
4811     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4812     if (StartOffset)
4813       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4814                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4815
4816     int EltNo = (Offset - StartOffset) >> 2;
4817     int NumElems = VT.getVectorNumElements();
4818
4819     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4820     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4821                              LD->getPointerInfo().getWithOffset(StartOffset),
4822                              false, false, false, 0);
4823
4824     SmallVector<int, 8> Mask;
4825     for (int i = 0; i < NumElems; ++i)
4826       Mask.push_back(EltNo);
4827
4828     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4829   }
4830
4831   return SDValue();
4832 }
4833
4834 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4835 /// vector of type 'VT', see if the elements can be replaced by a single large
4836 /// load which has the same value as a build_vector whose operands are 'elts'.
4837 ///
4838 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4839 ///
4840 /// FIXME: we'd also like to handle the case where the last elements are zero
4841 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4842 /// There's even a handy isZeroNode for that purpose.
4843 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4844                                         DebugLoc &DL, SelectionDAG &DAG) {
4845   EVT EltVT = VT.getVectorElementType();
4846   unsigned NumElems = Elts.size();
4847
4848   LoadSDNode *LDBase = NULL;
4849   unsigned LastLoadedElt = -1U;
4850
4851   // For each element in the initializer, see if we've found a load or an undef.
4852   // If we don't find an initial load element, or later load elements are
4853   // non-consecutive, bail out.
4854   for (unsigned i = 0; i < NumElems; ++i) {
4855     SDValue Elt = Elts[i];
4856
4857     if (!Elt.getNode() ||
4858         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4859       return SDValue();
4860     if (!LDBase) {
4861       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4862         return SDValue();
4863       LDBase = cast<LoadSDNode>(Elt.getNode());
4864       LastLoadedElt = i;
4865       continue;
4866     }
4867     if (Elt.getOpcode() == ISD::UNDEF)
4868       continue;
4869
4870     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4871     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4872       return SDValue();
4873     LastLoadedElt = i;
4874   }
4875
4876   // If we have found an entire vector of loads and undefs, then return a large
4877   // load of the entire vector width starting at the base pointer.  If we found
4878   // consecutive loads for the low half, generate a vzext_load node.
4879   if (LastLoadedElt == NumElems - 1) {
4880     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4881       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4882                          LDBase->getPointerInfo(),
4883                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4884                          LDBase->isInvariant(), 0);
4885     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4886                        LDBase->getPointerInfo(),
4887                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4888                        LDBase->isInvariant(), LDBase->getAlignment());
4889   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4890              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4891     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4892     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4893     SDValue ResNode =
4894         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4895                                 LDBase->getPointerInfo(),
4896                                 LDBase->getAlignment(),
4897                                 false/*isVolatile*/, true/*ReadMem*/,
4898                                 false/*WriteMem*/);
4899     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4900   }
4901   return SDValue();
4902 }
4903
4904 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4905 /// a vbroadcast node. We support two patterns:
4906 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4907 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4908 /// a scalar load.
4909 /// The scalar load node is returned when a pattern is found,
4910 /// or SDValue() otherwise.
4911 static SDValue isVectorBroadcast(SDValue &Op, const X86Subtarget *Subtarget) {
4912   if (!Subtarget->hasAVX())
4913     return SDValue();
4914
4915   EVT VT = Op.getValueType();
4916   SDValue V = Op;
4917
4918   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4919     V = V.getOperand(0);
4920
4921   //A suspected load to be broadcasted.
4922   SDValue Ld;
4923
4924   switch (V.getOpcode()) {
4925     default:
4926       // Unknown pattern found.
4927       return SDValue();
4928
4929     case ISD::BUILD_VECTOR: {
4930       // The BUILD_VECTOR node must be a splat.
4931       if (!isSplatVector(V.getNode()))
4932         return SDValue();
4933
4934       Ld = V.getOperand(0);
4935
4936       // The suspected load node has several users. Make sure that all
4937       // of its users are from the BUILD_VECTOR node.
4938       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4939         return SDValue();
4940       break;
4941     }
4942
4943     case ISD::VECTOR_SHUFFLE: {
4944       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4945
4946       // Shuffles must have a splat mask where the first element is
4947       // broadcasted.
4948       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4949         return SDValue();
4950
4951       SDValue Sc = Op.getOperand(0);
4952       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4953         return SDValue();
4954
4955       Ld = Sc.getOperand(0);
4956
4957       // The scalar_to_vector node and the suspected
4958       // load node must have exactly one user.
4959       if (!Sc.hasOneUse() || !Ld.hasOneUse())
4960         return SDValue();
4961       break;
4962     }
4963   }
4964
4965   // The scalar source must be a normal load.
4966   if (!ISD::isNormalLoad(Ld.getNode()))
4967     return SDValue();
4968
4969   // Reject loads that have uses of the chain result
4970   if (Ld->hasAnyUseOfValue(1))
4971     return SDValue();
4972
4973   bool Is256 = VT.getSizeInBits() == 256;
4974   bool Is128 = VT.getSizeInBits() == 128;
4975   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4976
4977   // VBroadcast to YMM
4978   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
4979     return Ld;
4980
4981   // VBroadcast to XMM
4982   if (Is128 && (ScalarSize == 32))
4983     return Ld;
4984
4985   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4986   // double since there is vbroadcastsd xmm
4987   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
4988     // VBroadcast to YMM
4989     if (Is256 && (ScalarSize == 8 || ScalarSize == 16))
4990       return Ld;
4991
4992     // VBroadcast to XMM
4993     if (Is128 && (ScalarSize ==  8 || ScalarSize == 16 || ScalarSize == 64))
4994       return Ld;
4995   }
4996
4997   // Unsupported broadcast.
4998   return SDValue();
4999 }
5000
5001 SDValue
5002 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5003   DebugLoc dl = Op.getDebugLoc();
5004
5005   EVT VT = Op.getValueType();
5006   EVT ExtVT = VT.getVectorElementType();
5007   unsigned NumElems = Op.getNumOperands();
5008
5009   // Vectors containing all zeros can be matched by pxor and xorps later
5010   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5011     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5012     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5013     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5014       return Op;
5015
5016     return getZeroVector(VT, Subtarget, DAG, dl);
5017   }
5018
5019   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5020   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5021   // vpcmpeqd on 256-bit vectors.
5022   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5023     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5024       return Op;
5025
5026     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5027   }
5028
5029   SDValue LD = isVectorBroadcast(Op, Subtarget);
5030   if (LD.getNode())
5031     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5032
5033   unsigned EVTBits = ExtVT.getSizeInBits();
5034
5035   unsigned NumZero  = 0;
5036   unsigned NumNonZero = 0;
5037   unsigned NonZeros = 0;
5038   bool IsAllConstants = true;
5039   SmallSet<SDValue, 8> Values;
5040   for (unsigned i = 0; i < NumElems; ++i) {
5041     SDValue Elt = Op.getOperand(i);
5042     if (Elt.getOpcode() == ISD::UNDEF)
5043       continue;
5044     Values.insert(Elt);
5045     if (Elt.getOpcode() != ISD::Constant &&
5046         Elt.getOpcode() != ISD::ConstantFP)
5047       IsAllConstants = false;
5048     if (X86::isZeroNode(Elt))
5049       NumZero++;
5050     else {
5051       NonZeros |= (1 << i);
5052       NumNonZero++;
5053     }
5054   }
5055
5056   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5057   if (NumNonZero == 0)
5058     return DAG.getUNDEF(VT);
5059
5060   // Special case for single non-zero, non-undef, element.
5061   if (NumNonZero == 1) {
5062     unsigned Idx = CountTrailingZeros_32(NonZeros);
5063     SDValue Item = Op.getOperand(Idx);
5064
5065     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5066     // the value are obviously zero, truncate the value to i32 and do the
5067     // insertion that way.  Only do this if the value is non-constant or if the
5068     // value is a constant being inserted into element 0.  It is cheaper to do
5069     // a constant pool load than it is to do a movd + shuffle.
5070     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5071         (!IsAllConstants || Idx == 0)) {
5072       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5073         // Handle SSE only.
5074         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5075         EVT VecVT = MVT::v4i32;
5076         unsigned VecElts = 4;
5077
5078         // Truncate the value (which may itself be a constant) to i32, and
5079         // convert it to a vector with movd (S2V+shuffle to zero extend).
5080         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5081         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5082         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5083
5084         // Now we have our 32-bit value zero extended in the low element of
5085         // a vector.  If Idx != 0, swizzle it into place.
5086         if (Idx != 0) {
5087           SmallVector<int, 4> Mask;
5088           Mask.push_back(Idx);
5089           for (unsigned i = 1; i != VecElts; ++i)
5090             Mask.push_back(i);
5091           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5092                                       DAG.getUNDEF(Item.getValueType()),
5093                                       &Mask[0]);
5094         }
5095         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5096       }
5097     }
5098
5099     // If we have a constant or non-constant insertion into the low element of
5100     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5101     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5102     // depending on what the source datatype is.
5103     if (Idx == 0) {
5104       if (NumZero == 0)
5105         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5106
5107       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5108           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5109         if (VT.getSizeInBits() == 256) {
5110           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5111           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5112                              Item, DAG.getIntPtrConstant(0));
5113         }
5114         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5115         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5116         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5117         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5118       }
5119
5120       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5121         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5122         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5123         if (VT.getSizeInBits() == 256) {
5124           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5125           Item = Insert128BitVector(ZeroVec, Item, DAG.getConstant(0, MVT::i32),
5126                                     DAG, dl);
5127         } else {
5128           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5129           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5130         }
5131         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5132       }
5133     }
5134
5135     // Is it a vector logical left shift?
5136     if (NumElems == 2 && Idx == 1 &&
5137         X86::isZeroNode(Op.getOperand(0)) &&
5138         !X86::isZeroNode(Op.getOperand(1))) {
5139       unsigned NumBits = VT.getSizeInBits();
5140       return getVShift(true, VT,
5141                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5142                                    VT, Op.getOperand(1)),
5143                        NumBits/2, DAG, *this, dl);
5144     }
5145
5146     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5147       return SDValue();
5148
5149     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5150     // is a non-constant being inserted into an element other than the low one,
5151     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5152     // movd/movss) to move this into the low element, then shuffle it into
5153     // place.
5154     if (EVTBits == 32) {
5155       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5156
5157       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5158       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5159       SmallVector<int, 8> MaskVec;
5160       for (unsigned i = 0; i < NumElems; i++)
5161         MaskVec.push_back(i == Idx ? 0 : 1);
5162       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5163     }
5164   }
5165
5166   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5167   if (Values.size() == 1) {
5168     if (EVTBits == 32) {
5169       // Instead of a shuffle like this:
5170       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5171       // Check if it's possible to issue this instead.
5172       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5173       unsigned Idx = CountTrailingZeros_32(NonZeros);
5174       SDValue Item = Op.getOperand(Idx);
5175       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5176         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5177     }
5178     return SDValue();
5179   }
5180
5181   // A vector full of immediates; various special cases are already
5182   // handled, so this is best done with a single constant-pool load.
5183   if (IsAllConstants)
5184     return SDValue();
5185
5186   // For AVX-length vectors, build the individual 128-bit pieces and use
5187   // shuffles to put them in place.
5188   if (VT.getSizeInBits() == 256) {
5189     SmallVector<SDValue, 32> V;
5190     for (unsigned i = 0; i != NumElems; ++i)
5191       V.push_back(Op.getOperand(i));
5192
5193     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5194
5195     // Build both the lower and upper subvector.
5196     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5197     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5198                                 NumElems/2);
5199
5200     // Recreate the wider vector with the lower and upper part.
5201     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5202                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5203     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5204                               DAG, dl);
5205   }
5206
5207   // Let legalizer expand 2-wide build_vectors.
5208   if (EVTBits == 64) {
5209     if (NumNonZero == 1) {
5210       // One half is zero or undef.
5211       unsigned Idx = CountTrailingZeros_32(NonZeros);
5212       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5213                                  Op.getOperand(Idx));
5214       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5215     }
5216     return SDValue();
5217   }
5218
5219   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5220   if (EVTBits == 8 && NumElems == 16) {
5221     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5222                                         Subtarget, *this);
5223     if (V.getNode()) return V;
5224   }
5225
5226   if (EVTBits == 16 && NumElems == 8) {
5227     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5228                                       Subtarget, *this);
5229     if (V.getNode()) return V;
5230   }
5231
5232   // If element VT is == 32 bits, turn it into a number of shuffles.
5233   SmallVector<SDValue, 8> V(NumElems);
5234   if (NumElems == 4 && NumZero > 0) {
5235     for (unsigned i = 0; i < 4; ++i) {
5236       bool isZero = !(NonZeros & (1 << i));
5237       if (isZero)
5238         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5239       else
5240         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5241     }
5242
5243     for (unsigned i = 0; i < 2; ++i) {
5244       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5245         default: break;
5246         case 0:
5247           V[i] = V[i*2];  // Must be a zero vector.
5248           break;
5249         case 1:
5250           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5251           break;
5252         case 2:
5253           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5254           break;
5255         case 3:
5256           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5257           break;
5258       }
5259     }
5260
5261     bool Reverse1 = (NonZeros & 0x3) == 2;
5262     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5263     int MaskVec[] = {
5264       Reverse1 ? 1 : 0,
5265       Reverse1 ? 0 : 1,
5266       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5267       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5268     };
5269     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5270   }
5271
5272   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5273     // Check for a build vector of consecutive loads.
5274     for (unsigned i = 0; i < NumElems; ++i)
5275       V[i] = Op.getOperand(i);
5276
5277     // Check for elements which are consecutive loads.
5278     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5279     if (LD.getNode())
5280       return LD;
5281
5282     // For SSE 4.1, use insertps to put the high elements into the low element.
5283     if (getSubtarget()->hasSSE41()) {
5284       SDValue Result;
5285       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5286         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5287       else
5288         Result = DAG.getUNDEF(VT);
5289
5290       for (unsigned i = 1; i < NumElems; ++i) {
5291         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5292         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5293                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5294       }
5295       return Result;
5296     }
5297
5298     // Otherwise, expand into a number of unpckl*, start by extending each of
5299     // our (non-undef) elements to the full vector width with the element in the
5300     // bottom slot of the vector (which generates no code for SSE).
5301     for (unsigned i = 0; i < NumElems; ++i) {
5302       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5303         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5304       else
5305         V[i] = DAG.getUNDEF(VT);
5306     }
5307
5308     // Next, we iteratively mix elements, e.g. for v4f32:
5309     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5310     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5311     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5312     unsigned EltStride = NumElems >> 1;
5313     while (EltStride != 0) {
5314       for (unsigned i = 0; i < EltStride; ++i) {
5315         // If V[i+EltStride] is undef and this is the first round of mixing,
5316         // then it is safe to just drop this shuffle: V[i] is already in the
5317         // right place, the one element (since it's the first round) being
5318         // inserted as undef can be dropped.  This isn't safe for successive
5319         // rounds because they will permute elements within both vectors.
5320         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5321             EltStride == NumElems/2)
5322           continue;
5323
5324         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5325       }
5326       EltStride >>= 1;
5327     }
5328     return V[0];
5329   }
5330   return SDValue();
5331 }
5332
5333 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5334 // them in a MMX register.  This is better than doing a stack convert.
5335 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5336   DebugLoc dl = Op.getDebugLoc();
5337   EVT ResVT = Op.getValueType();
5338
5339   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5340          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5341   int Mask[2];
5342   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5343   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5344   InVec = Op.getOperand(1);
5345   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5346     unsigned NumElts = ResVT.getVectorNumElements();
5347     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5348     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5349                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5350   } else {
5351     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5352     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5353     Mask[0] = 0; Mask[1] = 2;
5354     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5355   }
5356   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5357 }
5358
5359 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5360 // to create 256-bit vectors from two other 128-bit ones.
5361 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5362   DebugLoc dl = Op.getDebugLoc();
5363   EVT ResVT = Op.getValueType();
5364
5365   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5366
5367   SDValue V1 = Op.getOperand(0);
5368   SDValue V2 = Op.getOperand(1);
5369   unsigned NumElems = ResVT.getVectorNumElements();
5370
5371   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5372                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5373   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5374                             DAG, dl);
5375 }
5376
5377 SDValue
5378 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5379   EVT ResVT = Op.getValueType();
5380
5381   assert(Op.getNumOperands() == 2);
5382   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5383          "Unsupported CONCAT_VECTORS for value type");
5384
5385   // We support concatenate two MMX registers and place them in a MMX register.
5386   // This is better than doing a stack convert.
5387   if (ResVT.is128BitVector())
5388     return LowerMMXCONCAT_VECTORS(Op, DAG);
5389
5390   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5391   // from two other 128-bit ones.
5392   return LowerAVXCONCAT_VECTORS(Op, DAG);
5393 }
5394
5395 // v8i16 shuffles - Prefer shuffles in the following order:
5396 // 1. [all]   pshuflw, pshufhw, optional move
5397 // 2. [ssse3] 1 x pshufb
5398 // 3. [ssse3] 2 x pshufb + 1 x por
5399 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5400 SDValue
5401 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5402                                             SelectionDAG &DAG) const {
5403   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5404   SDValue V1 = SVOp->getOperand(0);
5405   SDValue V2 = SVOp->getOperand(1);
5406   DebugLoc dl = SVOp->getDebugLoc();
5407   SmallVector<int, 8> MaskVals;
5408
5409   // Determine if more than 1 of the words in each of the low and high quadwords
5410   // of the result come from the same quadword of one of the two inputs.  Undef
5411   // mask values count as coming from any quadword, for better codegen.
5412   unsigned LoQuad[] = { 0, 0, 0, 0 };
5413   unsigned HiQuad[] = { 0, 0, 0, 0 };
5414   std::bitset<4> InputQuads;
5415   for (unsigned i = 0; i < 8; ++i) {
5416     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5417     int EltIdx = SVOp->getMaskElt(i);
5418     MaskVals.push_back(EltIdx);
5419     if (EltIdx < 0) {
5420       ++Quad[0];
5421       ++Quad[1];
5422       ++Quad[2];
5423       ++Quad[3];
5424       continue;
5425     }
5426     ++Quad[EltIdx / 4];
5427     InputQuads.set(EltIdx / 4);
5428   }
5429
5430   int BestLoQuad = -1;
5431   unsigned MaxQuad = 1;
5432   for (unsigned i = 0; i < 4; ++i) {
5433     if (LoQuad[i] > MaxQuad) {
5434       BestLoQuad = i;
5435       MaxQuad = LoQuad[i];
5436     }
5437   }
5438
5439   int BestHiQuad = -1;
5440   MaxQuad = 1;
5441   for (unsigned i = 0; i < 4; ++i) {
5442     if (HiQuad[i] > MaxQuad) {
5443       BestHiQuad = i;
5444       MaxQuad = HiQuad[i];
5445     }
5446   }
5447
5448   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5449   // of the two input vectors, shuffle them into one input vector so only a
5450   // single pshufb instruction is necessary. If There are more than 2 input
5451   // quads, disable the next transformation since it does not help SSSE3.
5452   bool V1Used = InputQuads[0] || InputQuads[1];
5453   bool V2Used = InputQuads[2] || InputQuads[3];
5454   if (Subtarget->hasSSSE3()) {
5455     if (InputQuads.count() == 2 && V1Used && V2Used) {
5456       BestLoQuad = InputQuads[0] ? 0 : 1;
5457       BestHiQuad = InputQuads[2] ? 2 : 3;
5458     }
5459     if (InputQuads.count() > 2) {
5460       BestLoQuad = -1;
5461       BestHiQuad = -1;
5462     }
5463   }
5464
5465   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5466   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5467   // words from all 4 input quadwords.
5468   SDValue NewV;
5469   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5470     int MaskV[] = {
5471       BestLoQuad < 0 ? 0 : BestLoQuad,
5472       BestHiQuad < 0 ? 1 : BestHiQuad
5473     };
5474     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5475                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5476                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5477     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5478
5479     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5480     // source words for the shuffle, to aid later transformations.
5481     bool AllWordsInNewV = true;
5482     bool InOrder[2] = { true, true };
5483     for (unsigned i = 0; i != 8; ++i) {
5484       int idx = MaskVals[i];
5485       if (idx != (int)i)
5486         InOrder[i/4] = false;
5487       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5488         continue;
5489       AllWordsInNewV = false;
5490       break;
5491     }
5492
5493     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5494     if (AllWordsInNewV) {
5495       for (int i = 0; i != 8; ++i) {
5496         int idx = MaskVals[i];
5497         if (idx < 0)
5498           continue;
5499         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5500         if ((idx != i) && idx < 4)
5501           pshufhw = false;
5502         if ((idx != i) && idx > 3)
5503           pshuflw = false;
5504       }
5505       V1 = NewV;
5506       V2Used = false;
5507       BestLoQuad = 0;
5508       BestHiQuad = 1;
5509     }
5510
5511     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5512     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5513     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5514       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5515       unsigned TargetMask = 0;
5516       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5517                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5518       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5519                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5520       V1 = NewV.getOperand(0);
5521       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5522     }
5523   }
5524
5525   // If we have SSSE3, and all words of the result are from 1 input vector,
5526   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5527   // is present, fall back to case 4.
5528   if (Subtarget->hasSSSE3()) {
5529     SmallVector<SDValue,16> pshufbMask;
5530
5531     // If we have elements from both input vectors, set the high bit of the
5532     // shuffle mask element to zero out elements that come from V2 in the V1
5533     // mask, and elements that come from V1 in the V2 mask, so that the two
5534     // results can be OR'd together.
5535     bool TwoInputs = V1Used && V2Used;
5536     for (unsigned i = 0; i != 8; ++i) {
5537       int EltIdx = MaskVals[i] * 2;
5538       if (TwoInputs && (EltIdx >= 16)) {
5539         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5540         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5541         continue;
5542       }
5543       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5544       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5545     }
5546     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5547     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5548                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5549                                  MVT::v16i8, &pshufbMask[0], 16));
5550     if (!TwoInputs)
5551       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5552
5553     // Calculate the shuffle mask for the second input, shuffle it, and
5554     // OR it with the first shuffled input.
5555     pshufbMask.clear();
5556     for (unsigned i = 0; i != 8; ++i) {
5557       int EltIdx = MaskVals[i] * 2;
5558       if (EltIdx < 16) {
5559         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5560         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5561         continue;
5562       }
5563       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5564       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5565     }
5566     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5567     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5568                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5569                                  MVT::v16i8, &pshufbMask[0], 16));
5570     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5571     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5572   }
5573
5574   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5575   // and update MaskVals with new element order.
5576   std::bitset<8> InOrder;
5577   if (BestLoQuad >= 0) {
5578     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5579     for (int i = 0; i != 4; ++i) {
5580       int idx = MaskVals[i];
5581       if (idx < 0) {
5582         InOrder.set(i);
5583       } else if ((idx / 4) == BestLoQuad) {
5584         MaskV[i] = idx & 3;
5585         InOrder.set(i);
5586       }
5587     }
5588     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5589                                 &MaskV[0]);
5590
5591     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5592       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5593                                NewV.getOperand(0),
5594                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5595                                DAG);
5596   }
5597
5598   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5599   // and update MaskVals with the new element order.
5600   if (BestHiQuad >= 0) {
5601     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5602     for (unsigned i = 4; i != 8; ++i) {
5603       int idx = MaskVals[i];
5604       if (idx < 0) {
5605         InOrder.set(i);
5606       } else if ((idx / 4) == BestHiQuad) {
5607         MaskV[i] = (idx & 3) + 4;
5608         InOrder.set(i);
5609       }
5610     }
5611     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5612                                 &MaskV[0]);
5613
5614     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5615       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5616                               NewV.getOperand(0),
5617                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5618                               DAG);
5619   }
5620
5621   // In case BestHi & BestLo were both -1, which means each quadword has a word
5622   // from each of the four input quadwords, calculate the InOrder bitvector now
5623   // before falling through to the insert/extract cleanup.
5624   if (BestLoQuad == -1 && BestHiQuad == -1) {
5625     NewV = V1;
5626     for (int i = 0; i != 8; ++i)
5627       if (MaskVals[i] < 0 || MaskVals[i] == i)
5628         InOrder.set(i);
5629   }
5630
5631   // The other elements are put in the right place using pextrw and pinsrw.
5632   for (unsigned i = 0; i != 8; ++i) {
5633     if (InOrder[i])
5634       continue;
5635     int EltIdx = MaskVals[i];
5636     if (EltIdx < 0)
5637       continue;
5638     SDValue ExtOp = (EltIdx < 8)
5639     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5640                   DAG.getIntPtrConstant(EltIdx))
5641     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5642                   DAG.getIntPtrConstant(EltIdx - 8));
5643     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5644                        DAG.getIntPtrConstant(i));
5645   }
5646   return NewV;
5647 }
5648
5649 // v16i8 shuffles - Prefer shuffles in the following order:
5650 // 1. [ssse3] 1 x pshufb
5651 // 2. [ssse3] 2 x pshufb + 1 x por
5652 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5653 static
5654 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5655                                  SelectionDAG &DAG,
5656                                  const X86TargetLowering &TLI) {
5657   SDValue V1 = SVOp->getOperand(0);
5658   SDValue V2 = SVOp->getOperand(1);
5659   DebugLoc dl = SVOp->getDebugLoc();
5660   ArrayRef<int> MaskVals = SVOp->getMask();
5661
5662   // If we have SSSE3, case 1 is generated when all result bytes come from
5663   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5664   // present, fall back to case 3.
5665   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5666   bool V1Only = true;
5667   bool V2Only = true;
5668   for (unsigned i = 0; i < 16; ++i) {
5669     int EltIdx = MaskVals[i];
5670     if (EltIdx < 0)
5671       continue;
5672     if (EltIdx < 16)
5673       V2Only = false;
5674     else
5675       V1Only = false;
5676   }
5677
5678   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5679   if (TLI.getSubtarget()->hasSSSE3()) {
5680     SmallVector<SDValue,16> pshufbMask;
5681
5682     // If all result elements are from one input vector, then only translate
5683     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5684     //
5685     // Otherwise, we have elements from both input vectors, and must zero out
5686     // elements that come from V2 in the first mask, and V1 in the second mask
5687     // so that we can OR them together.
5688     bool TwoInputs = !(V1Only || V2Only);
5689     for (unsigned i = 0; i != 16; ++i) {
5690       int EltIdx = MaskVals[i];
5691       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5692         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5693         continue;
5694       }
5695       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5696     }
5697     // If all the elements are from V2, assign it to V1 and return after
5698     // building the first pshufb.
5699     if (V2Only)
5700       V1 = V2;
5701     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5702                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5703                                  MVT::v16i8, &pshufbMask[0], 16));
5704     if (!TwoInputs)
5705       return V1;
5706
5707     // Calculate the shuffle mask for the second input, shuffle it, and
5708     // OR it with the first shuffled input.
5709     pshufbMask.clear();
5710     for (unsigned i = 0; i != 16; ++i) {
5711       int EltIdx = MaskVals[i];
5712       if (EltIdx < 16) {
5713         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5714         continue;
5715       }
5716       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5717     }
5718     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5719                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5720                                  MVT::v16i8, &pshufbMask[0], 16));
5721     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5722   }
5723
5724   // No SSSE3 - Calculate in place words and then fix all out of place words
5725   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5726   // the 16 different words that comprise the two doublequadword input vectors.
5727   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5728   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5729   SDValue NewV = V2Only ? V2 : V1;
5730   for (int i = 0; i != 8; ++i) {
5731     int Elt0 = MaskVals[i*2];
5732     int Elt1 = MaskVals[i*2+1];
5733
5734     // This word of the result is all undef, skip it.
5735     if (Elt0 < 0 && Elt1 < 0)
5736       continue;
5737
5738     // This word of the result is already in the correct place, skip it.
5739     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5740       continue;
5741     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5742       continue;
5743
5744     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5745     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5746     SDValue InsElt;
5747
5748     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5749     // using a single extract together, load it and store it.
5750     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5751       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5752                            DAG.getIntPtrConstant(Elt1 / 2));
5753       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5754                         DAG.getIntPtrConstant(i));
5755       continue;
5756     }
5757
5758     // If Elt1 is defined, extract it from the appropriate source.  If the
5759     // source byte is not also odd, shift the extracted word left 8 bits
5760     // otherwise clear the bottom 8 bits if we need to do an or.
5761     if (Elt1 >= 0) {
5762       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5763                            DAG.getIntPtrConstant(Elt1 / 2));
5764       if ((Elt1 & 1) == 0)
5765         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5766                              DAG.getConstant(8,
5767                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5768       else if (Elt0 >= 0)
5769         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5770                              DAG.getConstant(0xFF00, MVT::i16));
5771     }
5772     // If Elt0 is defined, extract it from the appropriate source.  If the
5773     // source byte is not also even, shift the extracted word right 8 bits. If
5774     // Elt1 was also defined, OR the extracted values together before
5775     // inserting them in the result.
5776     if (Elt0 >= 0) {
5777       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5778                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5779       if ((Elt0 & 1) != 0)
5780         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5781                               DAG.getConstant(8,
5782                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5783       else if (Elt1 >= 0)
5784         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5785                              DAG.getConstant(0x00FF, MVT::i16));
5786       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5787                          : InsElt0;
5788     }
5789     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5790                        DAG.getIntPtrConstant(i));
5791   }
5792   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5793 }
5794
5795 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5796 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5797 /// done when every pair / quad of shuffle mask elements point to elements in
5798 /// the right sequence. e.g.
5799 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5800 static
5801 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5802                                  SelectionDAG &DAG, DebugLoc dl) {
5803   EVT VT = SVOp->getValueType(0);
5804   SDValue V1 = SVOp->getOperand(0);
5805   SDValue V2 = SVOp->getOperand(1);
5806   unsigned NumElems = VT.getVectorNumElements();
5807   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5808   EVT NewVT;
5809   switch (VT.getSimpleVT().SimpleTy) {
5810   default: llvm_unreachable("Unexpected!");
5811   case MVT::v4f32: NewVT = MVT::v2f64; break;
5812   case MVT::v4i32: NewVT = MVT::v2i64; break;
5813   case MVT::v8i16: NewVT = MVT::v4i32; break;
5814   case MVT::v16i8: NewVT = MVT::v4i32; break;
5815   }
5816
5817   int Scale = NumElems / NewWidth;
5818   SmallVector<int, 8> MaskVec;
5819   for (unsigned i = 0; i < NumElems; i += Scale) {
5820     int StartIdx = -1;
5821     for (int j = 0; j < Scale; ++j) {
5822       int EltIdx = SVOp->getMaskElt(i+j);
5823       if (EltIdx < 0)
5824         continue;
5825       if (StartIdx == -1)
5826         StartIdx = EltIdx - (EltIdx % Scale);
5827       if (EltIdx != StartIdx + j)
5828         return SDValue();
5829     }
5830     if (StartIdx == -1)
5831       MaskVec.push_back(-1);
5832     else
5833       MaskVec.push_back(StartIdx / Scale);
5834   }
5835
5836   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5837   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5838   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5839 }
5840
5841 /// getVZextMovL - Return a zero-extending vector move low node.
5842 ///
5843 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5844                             SDValue SrcOp, SelectionDAG &DAG,
5845                             const X86Subtarget *Subtarget, DebugLoc dl) {
5846   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5847     LoadSDNode *LD = NULL;
5848     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5849       LD = dyn_cast<LoadSDNode>(SrcOp);
5850     if (!LD) {
5851       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5852       // instead.
5853       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5854       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5855           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5856           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5857           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5858         // PR2108
5859         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5860         return DAG.getNode(ISD::BITCAST, dl, VT,
5861                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5862                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5863                                                    OpVT,
5864                                                    SrcOp.getOperand(0)
5865                                                           .getOperand(0))));
5866       }
5867     }
5868   }
5869
5870   return DAG.getNode(ISD::BITCAST, dl, VT,
5871                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5872                                  DAG.getNode(ISD::BITCAST, dl,
5873                                              OpVT, SrcOp)));
5874 }
5875
5876 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5877 /// which could not be matched by any known target speficic shuffle
5878 static SDValue
5879 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5880   EVT VT = SVOp->getValueType(0);
5881
5882   unsigned NumElems = VT.getVectorNumElements();
5883   unsigned NumLaneElems = NumElems / 2;
5884
5885   int MinRange[2][2] = { { static_cast<int>(NumElems),
5886                            static_cast<int>(NumElems) },
5887                          { static_cast<int>(NumElems),
5888                            static_cast<int>(NumElems) } };
5889   int MaxRange[2][2] = { { -1, -1 }, { -1, -1 } };
5890
5891   // Collect used ranges for each source in each lane
5892   for (unsigned l = 0; l < 2; ++l) {
5893     unsigned LaneStart = l*NumLaneElems;
5894     for (unsigned i = 0; i != NumLaneElems; ++i) {
5895       int Idx = SVOp->getMaskElt(i+LaneStart);
5896       if (Idx < 0)
5897         continue;
5898
5899       int Input = 0;
5900       if (Idx >= (int)NumElems) {
5901         Idx -= NumElems;
5902         Input = 1;
5903       }
5904
5905       if (Idx > MaxRange[l][Input])
5906         MaxRange[l][Input] = Idx;
5907       if (Idx < MinRange[l][Input])
5908         MinRange[l][Input] = Idx;
5909     }
5910   }
5911
5912   // Make sure each range is 128-bits
5913   int ExtractIdx[2][2] = { { -1, -1 }, { -1, -1 } };
5914   for (unsigned l = 0; l < 2; ++l) {
5915     for (unsigned Input = 0; Input < 2; ++Input) {
5916       if (MinRange[l][Input] == (int)NumElems && MaxRange[l][Input] < 0)
5917         continue;
5918
5919       if (MinRange[l][Input] >= 0 && MaxRange[l][Input] < (int)NumLaneElems)
5920         ExtractIdx[l][Input] = 0;
5921       else if (MinRange[l][Input] >= (int)NumLaneElems &&
5922                MaxRange[l][Input] < (int)NumElems)
5923         ExtractIdx[l][Input] = NumLaneElems;
5924       else
5925         return SDValue();
5926     }
5927   }
5928
5929   DebugLoc dl = SVOp->getDebugLoc();
5930   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5931   EVT NVT = MVT::getVectorVT(EltVT, NumElems/2);
5932
5933   SDValue Ops[2][2];
5934   for (unsigned l = 0; l < 2; ++l) {
5935     for (unsigned Input = 0; Input < 2; ++Input) {
5936       if (ExtractIdx[l][Input] >= 0)
5937         Ops[l][Input] = Extract128BitVector(SVOp->getOperand(Input),
5938                                 DAG.getConstant(ExtractIdx[l][Input], MVT::i32),
5939                                                 DAG, dl);
5940       else
5941         Ops[l][Input] = DAG.getUNDEF(NVT);
5942     }
5943   }
5944
5945   // Generate 128-bit shuffles
5946   SmallVector<int, 16> Mask1, Mask2;
5947   for (unsigned i = 0; i != NumLaneElems; ++i) {
5948     int Elt = SVOp->getMaskElt(i);
5949     if (Elt >= (int)NumElems) {
5950       Elt %= NumLaneElems;
5951       Elt += NumLaneElems;
5952     } else if (Elt >= 0) {
5953       Elt %= NumLaneElems;
5954     }
5955     Mask1.push_back(Elt);
5956   }
5957   for (unsigned i = NumLaneElems; i != NumElems; ++i) {
5958     int Elt = SVOp->getMaskElt(i);
5959     if (Elt >= (int)NumElems) {
5960       Elt %= NumLaneElems;
5961       Elt += NumLaneElems;
5962     } else if (Elt >= 0) {
5963       Elt %= NumLaneElems;
5964     }
5965     Mask2.push_back(Elt);
5966   }
5967
5968   SDValue Shuf1 = DAG.getVectorShuffle(NVT, dl, Ops[0][0], Ops[0][1], &Mask1[0]);
5969   SDValue Shuf2 = DAG.getVectorShuffle(NVT, dl, Ops[1][0], Ops[1][1], &Mask2[0]);
5970
5971   // Concatenate the result back
5972   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Shuf1,
5973                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5974   return Insert128BitVector(V, Shuf2, DAG.getConstant(NumElems/2, MVT::i32),
5975                             DAG, dl);
5976 }
5977
5978 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5979 /// 4 elements, and match them with several different shuffle types.
5980 static SDValue
5981 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5982   SDValue V1 = SVOp->getOperand(0);
5983   SDValue V2 = SVOp->getOperand(1);
5984   DebugLoc dl = SVOp->getDebugLoc();
5985   EVT VT = SVOp->getValueType(0);
5986
5987   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5988
5989   std::pair<int, int> Locs[4];
5990   int Mask1[] = { -1, -1, -1, -1 };
5991   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
5992
5993   unsigned NumHi = 0;
5994   unsigned NumLo = 0;
5995   for (unsigned i = 0; i != 4; ++i) {
5996     int Idx = PermMask[i];
5997     if (Idx < 0) {
5998       Locs[i] = std::make_pair(-1, -1);
5999     } else {
6000       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6001       if (Idx < 4) {
6002         Locs[i] = std::make_pair(0, NumLo);
6003         Mask1[NumLo] = Idx;
6004         NumLo++;
6005       } else {
6006         Locs[i] = std::make_pair(1, NumHi);
6007         if (2+NumHi < 4)
6008           Mask1[2+NumHi] = Idx;
6009         NumHi++;
6010       }
6011     }
6012   }
6013
6014   if (NumLo <= 2 && NumHi <= 2) {
6015     // If no more than two elements come from either vector. This can be
6016     // implemented with two shuffles. First shuffle gather the elements.
6017     // The second shuffle, which takes the first shuffle as both of its
6018     // vector operands, put the elements into the right order.
6019     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6020
6021     int Mask2[] = { -1, -1, -1, -1 };
6022
6023     for (unsigned i = 0; i != 4; ++i)
6024       if (Locs[i].first != -1) {
6025         unsigned Idx = (i < 2) ? 0 : 4;
6026         Idx += Locs[i].first * 2 + Locs[i].second;
6027         Mask2[i] = Idx;
6028       }
6029
6030     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6031   } else if (NumLo == 3 || NumHi == 3) {
6032     // Otherwise, we must have three elements from one vector, call it X, and
6033     // one element from the other, call it Y.  First, use a shufps to build an
6034     // intermediate vector with the one element from Y and the element from X
6035     // that will be in the same half in the final destination (the indexes don't
6036     // matter). Then, use a shufps to build the final vector, taking the half
6037     // containing the element from Y from the intermediate, and the other half
6038     // from X.
6039     if (NumHi == 3) {
6040       // Normalize it so the 3 elements come from V1.
6041       CommuteVectorShuffleMask(PermMask, 4);
6042       std::swap(V1, V2);
6043     }
6044
6045     // Find the element from V2.
6046     unsigned HiIndex;
6047     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6048       int Val = PermMask[HiIndex];
6049       if (Val < 0)
6050         continue;
6051       if (Val >= 4)
6052         break;
6053     }
6054
6055     Mask1[0] = PermMask[HiIndex];
6056     Mask1[1] = -1;
6057     Mask1[2] = PermMask[HiIndex^1];
6058     Mask1[3] = -1;
6059     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6060
6061     if (HiIndex >= 2) {
6062       Mask1[0] = PermMask[0];
6063       Mask1[1] = PermMask[1];
6064       Mask1[2] = HiIndex & 1 ? 6 : 4;
6065       Mask1[3] = HiIndex & 1 ? 4 : 6;
6066       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6067     } else {
6068       Mask1[0] = HiIndex & 1 ? 2 : 0;
6069       Mask1[1] = HiIndex & 1 ? 0 : 2;
6070       Mask1[2] = PermMask[2];
6071       Mask1[3] = PermMask[3];
6072       if (Mask1[2] >= 0)
6073         Mask1[2] += 4;
6074       if (Mask1[3] >= 0)
6075         Mask1[3] += 4;
6076       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6077     }
6078   }
6079
6080   // Break it into (shuffle shuffle_hi, shuffle_lo).
6081   int LoMask[] = { -1, -1, -1, -1 };
6082   int HiMask[] = { -1, -1, -1, -1 };
6083
6084   int *MaskPtr = LoMask;
6085   unsigned MaskIdx = 0;
6086   unsigned LoIdx = 0;
6087   unsigned HiIdx = 2;
6088   for (unsigned i = 0; i != 4; ++i) {
6089     if (i == 2) {
6090       MaskPtr = HiMask;
6091       MaskIdx = 1;
6092       LoIdx = 0;
6093       HiIdx = 2;
6094     }
6095     int Idx = PermMask[i];
6096     if (Idx < 0) {
6097       Locs[i] = std::make_pair(-1, -1);
6098     } else if (Idx < 4) {
6099       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6100       MaskPtr[LoIdx] = Idx;
6101       LoIdx++;
6102     } else {
6103       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6104       MaskPtr[HiIdx] = Idx;
6105       HiIdx++;
6106     }
6107   }
6108
6109   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6110   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6111   int MaskOps[] = { -1, -1, -1, -1 };
6112   for (unsigned i = 0; i != 4; ++i)
6113     if (Locs[i].first != -1)
6114       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6115   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6116 }
6117
6118 static bool MayFoldVectorLoad(SDValue V) {
6119   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6120     V = V.getOperand(0);
6121   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6122     V = V.getOperand(0);
6123   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6124       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6125     // BUILD_VECTOR (load), undef
6126     V = V.getOperand(0);
6127   if (MayFoldLoad(V))
6128     return true;
6129   return false;
6130 }
6131
6132 // FIXME: the version above should always be used. Since there's
6133 // a bug where several vector shuffles can't be folded because the
6134 // DAG is not updated during lowering and a node claims to have two
6135 // uses while it only has one, use this version, and let isel match
6136 // another instruction if the load really happens to have more than
6137 // one use. Remove this version after this bug get fixed.
6138 // rdar://8434668, PR8156
6139 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6140   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6141     V = V.getOperand(0);
6142   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6143     V = V.getOperand(0);
6144   if (ISD::isNormalLoad(V.getNode()))
6145     return true;
6146   return false;
6147 }
6148
6149 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6150 /// a vector extract, and if both can be later optimized into a single load.
6151 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6152 /// here because otherwise a target specific shuffle node is going to be
6153 /// emitted for this shuffle, and the optimization not done.
6154 /// FIXME: This is probably not the best approach, but fix the problem
6155 /// until the right path is decided.
6156 static
6157 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6158                                          const TargetLowering &TLI) {
6159   EVT VT = V.getValueType();
6160   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6161
6162   // Be sure that the vector shuffle is present in a pattern like this:
6163   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6164   if (!V.hasOneUse())
6165     return false;
6166
6167   SDNode *N = *V.getNode()->use_begin();
6168   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6169     return false;
6170
6171   SDValue EltNo = N->getOperand(1);
6172   if (!isa<ConstantSDNode>(EltNo))
6173     return false;
6174
6175   // If the bit convert changed the number of elements, it is unsafe
6176   // to examine the mask.
6177   bool HasShuffleIntoBitcast = false;
6178   if (V.getOpcode() == ISD::BITCAST) {
6179     EVT SrcVT = V.getOperand(0).getValueType();
6180     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6181       return false;
6182     V = V.getOperand(0);
6183     HasShuffleIntoBitcast = true;
6184   }
6185
6186   // Select the input vector, guarding against out of range extract vector.
6187   unsigned NumElems = VT.getVectorNumElements();
6188   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6189   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6190   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6191
6192   // If we are accessing the upper part of a YMM register
6193   // then the EXTRACT_VECTOR_ELT is likely to be legalized to a sequence of
6194   // EXTRACT_SUBVECTOR + EXTRACT_VECTOR_ELT, which are not detected at this point
6195   // because the legalization of N did not happen yet.
6196   if (Idx >= (int)NumElems/2 && VT.getSizeInBits() == 256)
6197     return false;
6198
6199   // Skip one more bit_convert if necessary
6200   if (V.getOpcode() == ISD::BITCAST)
6201     V = V.getOperand(0);
6202
6203   if (!ISD::isNormalLoad(V.getNode()))
6204     return false;
6205
6206   // Is the original load suitable?
6207   LoadSDNode *LN0 = cast<LoadSDNode>(V);
6208
6209   if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
6210     return false;
6211
6212   if (!HasShuffleIntoBitcast)
6213     return true;
6214
6215   // If there's a bitcast before the shuffle, check if the load type and
6216   // alignment is valid.
6217   unsigned Align = LN0->getAlignment();
6218   unsigned NewAlign =
6219     TLI.getTargetData()->getABITypeAlignment(
6220                                   VT.getTypeForEVT(*DAG.getContext()));
6221
6222   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6223     return false;
6224
6225   return true;
6226 }
6227
6228 static
6229 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6230   EVT VT = Op.getValueType();
6231
6232   // Canonizalize to v2f64.
6233   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6234   return DAG.getNode(ISD::BITCAST, dl, VT,
6235                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6236                                           V1, DAG));
6237 }
6238
6239 static
6240 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6241                         bool HasSSE2) {
6242   SDValue V1 = Op.getOperand(0);
6243   SDValue V2 = Op.getOperand(1);
6244   EVT VT = Op.getValueType();
6245
6246   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6247
6248   if (HasSSE2 && VT == MVT::v2f64)
6249     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6250
6251   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6252   return DAG.getNode(ISD::BITCAST, dl, VT,
6253                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6254                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6255                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6256 }
6257
6258 static
6259 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6260   SDValue V1 = Op.getOperand(0);
6261   SDValue V2 = Op.getOperand(1);
6262   EVT VT = Op.getValueType();
6263
6264   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6265          "unsupported shuffle type");
6266
6267   if (V2.getOpcode() == ISD::UNDEF)
6268     V2 = V1;
6269
6270   // v4i32 or v4f32
6271   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6272 }
6273
6274 static
6275 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6276   SDValue V1 = Op.getOperand(0);
6277   SDValue V2 = Op.getOperand(1);
6278   EVT VT = Op.getValueType();
6279   unsigned NumElems = VT.getVectorNumElements();
6280
6281   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6282   // operand of these instructions is only memory, so check if there's a
6283   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6284   // same masks.
6285   bool CanFoldLoad = false;
6286
6287   // Trivial case, when V2 comes from a load.
6288   if (MayFoldVectorLoad(V2))
6289     CanFoldLoad = true;
6290
6291   // When V1 is a load, it can be folded later into a store in isel, example:
6292   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6293   //    turns into:
6294   //  (MOVLPSmr addr:$src1, VR128:$src2)
6295   // So, recognize this potential and also use MOVLPS or MOVLPD
6296   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6297     CanFoldLoad = true;
6298
6299   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6300   if (CanFoldLoad) {
6301     if (HasSSE2 && NumElems == 2)
6302       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6303
6304     if (NumElems == 4)
6305       // If we don't care about the second element, procede to use movss.
6306       if (SVOp->getMaskElt(1) != -1)
6307         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6308   }
6309
6310   // movl and movlp will both match v2i64, but v2i64 is never matched by
6311   // movl earlier because we make it strict to avoid messing with the movlp load
6312   // folding logic (see the code above getMOVLP call). Match it here then,
6313   // this is horrible, but will stay like this until we move all shuffle
6314   // matching to x86 specific nodes. Note that for the 1st condition all
6315   // types are matched with movsd.
6316   if (HasSSE2) {
6317     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6318     // as to remove this logic from here, as much as possible
6319     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6320       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6321     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6322   }
6323
6324   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6325
6326   // Invert the operand order and use SHUFPS to match it.
6327   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6328                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6329 }
6330
6331 static
6332 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6333                                const TargetLowering &TLI,
6334                                const X86Subtarget *Subtarget) {
6335   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6336   EVT VT = Op.getValueType();
6337   DebugLoc dl = Op.getDebugLoc();
6338   SDValue V1 = Op.getOperand(0);
6339   SDValue V2 = Op.getOperand(1);
6340
6341   if (isZeroShuffle(SVOp))
6342     return getZeroVector(VT, Subtarget, DAG, dl);
6343
6344   // Handle splat operations
6345   if (SVOp->isSplat()) {
6346     unsigned NumElem = VT.getVectorNumElements();
6347     int Size = VT.getSizeInBits();
6348     // Special case, this is the only place now where it's allowed to return
6349     // a vector_shuffle operation without using a target specific node, because
6350     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6351     // this be moved to DAGCombine instead?
6352     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6353       return Op;
6354
6355     // Use vbroadcast whenever the splat comes from a foldable load
6356     SDValue LD = isVectorBroadcast(Op, Subtarget);
6357     if (LD.getNode())
6358       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6359
6360     // Handle splats by matching through known shuffle masks
6361     if ((Size == 128 && NumElem <= 4) ||
6362         (Size == 256 && NumElem < 8))
6363       return SDValue();
6364
6365     // All remaning splats are promoted to target supported vector shuffles.
6366     return PromoteSplat(SVOp, DAG);
6367   }
6368
6369   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6370   // do it!
6371   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6372     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6373     if (NewOp.getNode())
6374       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6375   } else if ((VT == MVT::v4i32 ||
6376              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6377     // FIXME: Figure out a cleaner way to do this.
6378     // Try to make use of movq to zero out the top part.
6379     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6380       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6381       if (NewOp.getNode()) {
6382         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6383           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6384                               DAG, Subtarget, dl);
6385       }
6386     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6387       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6388       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6389         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6390                             DAG, Subtarget, dl);
6391     }
6392   }
6393   return SDValue();
6394 }
6395
6396 SDValue
6397 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6398   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6399   SDValue V1 = Op.getOperand(0);
6400   SDValue V2 = Op.getOperand(1);
6401   EVT VT = Op.getValueType();
6402   DebugLoc dl = Op.getDebugLoc();
6403   unsigned NumElems = VT.getVectorNumElements();
6404   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6405   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6406   bool V1IsSplat = false;
6407   bool V2IsSplat = false;
6408   bool HasSSE2 = Subtarget->hasSSE2();
6409   bool HasAVX    = Subtarget->hasAVX();
6410   bool HasAVX2   = Subtarget->hasAVX2();
6411   MachineFunction &MF = DAG.getMachineFunction();
6412   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6413
6414   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6415
6416   if (V1IsUndef && V2IsUndef)
6417     return DAG.getUNDEF(VT);
6418
6419   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6420
6421   // Vector shuffle lowering takes 3 steps:
6422   //
6423   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6424   //    narrowing and commutation of operands should be handled.
6425   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6426   //    shuffle nodes.
6427   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6428   //    so the shuffle can be broken into other shuffles and the legalizer can
6429   //    try the lowering again.
6430   //
6431   // The general idea is that no vector_shuffle operation should be left to
6432   // be matched during isel, all of them must be converted to a target specific
6433   // node here.
6434
6435   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6436   // narrowing and commutation of operands should be handled. The actual code
6437   // doesn't include all of those, work in progress...
6438   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6439   if (NewOp.getNode())
6440     return NewOp;
6441
6442   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6443   // unpckh_undef). Only use pshufd if speed is more important than size.
6444   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6445     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6446   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6447     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6448
6449   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3() &&
6450       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6451     return getMOVDDup(Op, dl, V1, DAG);
6452
6453   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6454     return getMOVHighToLow(Op, dl, DAG);
6455
6456   // Use to match splats
6457   if (HasSSE2 && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6458       (VT == MVT::v2f64 || VT == MVT::v2i64))
6459     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6460
6461   if (X86::isPSHUFDMask(SVOp)) {
6462     // The actual implementation will match the mask in the if above and then
6463     // during isel it can match several different instructions, not only pshufd
6464     // as its name says, sad but true, emulate the behavior for now...
6465     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6466         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6467
6468     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6469
6470     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6471       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6472
6473     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6474                                 TargetMask, DAG);
6475   }
6476
6477   // Check if this can be converted into a logical shift.
6478   bool isLeft = false;
6479   unsigned ShAmt = 0;
6480   SDValue ShVal;
6481   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6482   if (isShift && ShVal.hasOneUse()) {
6483     // If the shifted value has multiple uses, it may be cheaper to use
6484     // v_set0 + movlhps or movhlps, etc.
6485     EVT EltVT = VT.getVectorElementType();
6486     ShAmt *= EltVT.getSizeInBits();
6487     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6488   }
6489
6490   if (X86::isMOVLMask(SVOp)) {
6491     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6492       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6493     if (!X86::isMOVLPMask(SVOp)) {
6494       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6495         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6496
6497       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6498         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6499     }
6500   }
6501
6502   // FIXME: fold these into legal mask.
6503   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6504     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6505
6506   if (X86::isMOVHLPSMask(SVOp))
6507     return getMOVHighToLow(Op, dl, DAG);
6508
6509   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6510     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6511
6512   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6513     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6514
6515   if (X86::isMOVLPMask(SVOp))
6516     return getMOVLP(Op, dl, DAG, HasSSE2);
6517
6518   if (ShouldXformToMOVHLPS(SVOp) ||
6519       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6520     return CommuteVectorShuffle(SVOp, DAG);
6521
6522   if (isShift) {
6523     // No better options. Use a vshldq / vsrldq.
6524     EVT EltVT = VT.getVectorElementType();
6525     ShAmt *= EltVT.getSizeInBits();
6526     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6527   }
6528
6529   bool Commuted = false;
6530   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6531   // 1,1,1,1 -> v8i16 though.
6532   V1IsSplat = isSplatVector(V1.getNode());
6533   V2IsSplat = isSplatVector(V2.getNode());
6534
6535   // Canonicalize the splat or undef, if present, to be on the RHS.
6536   if (V1IsSplat && !V2IsSplat) {
6537     Op = CommuteVectorShuffle(SVOp, DAG);
6538     SVOp = cast<ShuffleVectorSDNode>(Op);
6539     V1 = SVOp->getOperand(0);
6540     V2 = SVOp->getOperand(1);
6541     std::swap(V1IsSplat, V2IsSplat);
6542     Commuted = true;
6543   }
6544
6545   ArrayRef<int> M = SVOp->getMask();
6546
6547   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6548     // Shuffling low element of v1 into undef, just return v1.
6549     if (V2IsUndef)
6550       return V1;
6551     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6552     // the instruction selector will not match, so get a canonical MOVL with
6553     // swapped operands to undo the commute.
6554     return getMOVL(DAG, dl, VT, V2, V1);
6555   }
6556
6557   if (isUNPCKLMask(M, VT, HasAVX2))
6558     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6559
6560   if (isUNPCKHMask(M, VT, HasAVX2))
6561     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6562
6563   if (V2IsSplat) {
6564     // Normalize mask so all entries that point to V2 points to its first
6565     // element then try to match unpck{h|l} again. If match, return a
6566     // new vector_shuffle with the corrected mask.
6567     SDValue NewMask = NormalizeMask(SVOp, DAG);
6568     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6569     if (NSVOp != SVOp) {
6570       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6571         return NewMask;
6572       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6573         return NewMask;
6574       }
6575     }
6576   }
6577
6578   if (Commuted) {
6579     // Commute is back and try unpck* again.
6580     // FIXME: this seems wrong.
6581     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6582     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6583
6584     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6585       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6586
6587     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6588       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6589   }
6590
6591   // Normalize the node to match x86 shuffle ops if needed
6592   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6593     return CommuteVectorShuffle(SVOp, DAG);
6594
6595   // The checks below are all present in isShuffleMaskLegal, but they are
6596   // inlined here right now to enable us to directly emit target specific
6597   // nodes, and remove one by one until they don't return Op anymore.
6598
6599   if (isPALIGNRMask(M, VT, Subtarget))
6600     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6601                                 getShufflePALIGNRImmediate(SVOp),
6602                                 DAG);
6603
6604   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6605       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6606     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6607       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6608   }
6609
6610   if (isPSHUFHWMask(M, VT))
6611     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6612                                 X86::getShufflePSHUFHWImmediate(SVOp),
6613                                 DAG);
6614
6615   if (isPSHUFLWMask(M, VT))
6616     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6617                                 X86::getShufflePSHUFLWImmediate(SVOp),
6618                                 DAG);
6619
6620   if (isSHUFPMask(M, VT, HasAVX))
6621     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6622                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6623
6624   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6625     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6626   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6627     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6628
6629   //===--------------------------------------------------------------------===//
6630   // Generate target specific nodes for 128 or 256-bit shuffles only
6631   // supported in the AVX instruction set.
6632   //
6633
6634   // Handle VMOVDDUPY permutations
6635   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6636     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6637
6638   // Handle VPERMILPS/D* permutations
6639   if (isVPERMILPMask(M, VT, HasAVX))
6640     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6641                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6642
6643   // Handle VPERM2F128/VPERM2I128 permutations
6644   if (isVPERM2X128Mask(M, VT, HasAVX))
6645     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6646                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6647
6648   //===--------------------------------------------------------------------===//
6649   // Since no target specific shuffle was selected for this generic one,
6650   // lower it into other known shuffles. FIXME: this isn't true yet, but
6651   // this is the plan.
6652   //
6653
6654   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6655   if (VT == MVT::v8i16) {
6656     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6657     if (NewOp.getNode())
6658       return NewOp;
6659   }
6660
6661   if (VT == MVT::v16i8) {
6662     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6663     if (NewOp.getNode())
6664       return NewOp;
6665   }
6666
6667   // Handle all 128-bit wide vectors with 4 elements, and match them with
6668   // several different shuffle types.
6669   if (NumElems == 4 && VT.getSizeInBits() == 128)
6670     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6671
6672   // Handle general 256-bit shuffles
6673   if (VT.is256BitVector())
6674     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6675
6676   return SDValue();
6677 }
6678
6679 SDValue
6680 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6681                                                 SelectionDAG &DAG) const {
6682   EVT VT = Op.getValueType();
6683   DebugLoc dl = Op.getDebugLoc();
6684
6685   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6686     return SDValue();
6687
6688   if (VT.getSizeInBits() == 8) {
6689     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6690                                     Op.getOperand(0), Op.getOperand(1));
6691     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6692                                     DAG.getValueType(VT));
6693     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6694   } else if (VT.getSizeInBits() == 16) {
6695     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6696     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6697     if (Idx == 0)
6698       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6699                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6700                                      DAG.getNode(ISD::BITCAST, dl,
6701                                                  MVT::v4i32,
6702                                                  Op.getOperand(0)),
6703                                      Op.getOperand(1)));
6704     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6705                                     Op.getOperand(0), Op.getOperand(1));
6706     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6707                                     DAG.getValueType(VT));
6708     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6709   } else if (VT == MVT::f32) {
6710     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6711     // the result back to FR32 register. It's only worth matching if the
6712     // result has a single use which is a store or a bitcast to i32.  And in
6713     // the case of a store, it's not worth it if the index is a constant 0,
6714     // because a MOVSSmr can be used instead, which is smaller and faster.
6715     if (!Op.hasOneUse())
6716       return SDValue();
6717     SDNode *User = *Op.getNode()->use_begin();
6718     if ((User->getOpcode() != ISD::STORE ||
6719          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6720           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6721         (User->getOpcode() != ISD::BITCAST ||
6722          User->getValueType(0) != MVT::i32))
6723       return SDValue();
6724     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6725                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6726                                               Op.getOperand(0)),
6727                                               Op.getOperand(1));
6728     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6729   } else if (VT == MVT::i32 || VT == MVT::i64) {
6730     // ExtractPS/pextrq works with constant index.
6731     if (isa<ConstantSDNode>(Op.getOperand(1)))
6732       return Op;
6733   }
6734   return SDValue();
6735 }
6736
6737
6738 SDValue
6739 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6740                                            SelectionDAG &DAG) const {
6741   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6742     return SDValue();
6743
6744   SDValue Vec = Op.getOperand(0);
6745   EVT VecVT = Vec.getValueType();
6746
6747   // If this is a 256-bit vector result, first extract the 128-bit vector and
6748   // then extract the element from the 128-bit vector.
6749   if (VecVT.getSizeInBits() == 256) {
6750     DebugLoc dl = Op.getNode()->getDebugLoc();
6751     unsigned NumElems = VecVT.getVectorNumElements();
6752     SDValue Idx = Op.getOperand(1);
6753     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6754
6755     // Get the 128-bit vector.
6756     bool Upper = IdxVal >= NumElems/2;
6757     Vec = Extract128BitVector(Vec,
6758                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6759
6760     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6761                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6762   }
6763
6764   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6765
6766   if (Subtarget->hasSSE41()) {
6767     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6768     if (Res.getNode())
6769       return Res;
6770   }
6771
6772   EVT VT = Op.getValueType();
6773   DebugLoc dl = Op.getDebugLoc();
6774   // TODO: handle v16i8.
6775   if (VT.getSizeInBits() == 16) {
6776     SDValue Vec = Op.getOperand(0);
6777     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6778     if (Idx == 0)
6779       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6780                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6781                                      DAG.getNode(ISD::BITCAST, dl,
6782                                                  MVT::v4i32, Vec),
6783                                      Op.getOperand(1)));
6784     // Transform it so it match pextrw which produces a 32-bit result.
6785     EVT EltVT = MVT::i32;
6786     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6787                                     Op.getOperand(0), Op.getOperand(1));
6788     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6789                                     DAG.getValueType(VT));
6790     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6791   } else if (VT.getSizeInBits() == 32) {
6792     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6793     if (Idx == 0)
6794       return Op;
6795
6796     // SHUFPS the element to the lowest double word, then movss.
6797     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6798     EVT VVT = Op.getOperand(0).getValueType();
6799     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6800                                        DAG.getUNDEF(VVT), Mask);
6801     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6802                        DAG.getIntPtrConstant(0));
6803   } else if (VT.getSizeInBits() == 64) {
6804     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6805     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6806     //        to match extract_elt for f64.
6807     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6808     if (Idx == 0)
6809       return Op;
6810
6811     // UNPCKHPD the element to the lowest double word, then movsd.
6812     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6813     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6814     int Mask[2] = { 1, -1 };
6815     EVT VVT = Op.getOperand(0).getValueType();
6816     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6817                                        DAG.getUNDEF(VVT), Mask);
6818     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6819                        DAG.getIntPtrConstant(0));
6820   }
6821
6822   return SDValue();
6823 }
6824
6825 SDValue
6826 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6827                                                SelectionDAG &DAG) const {
6828   EVT VT = Op.getValueType();
6829   EVT EltVT = VT.getVectorElementType();
6830   DebugLoc dl = Op.getDebugLoc();
6831
6832   SDValue N0 = Op.getOperand(0);
6833   SDValue N1 = Op.getOperand(1);
6834   SDValue N2 = Op.getOperand(2);
6835
6836   if (VT.getSizeInBits() == 256)
6837     return SDValue();
6838
6839   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6840       isa<ConstantSDNode>(N2)) {
6841     unsigned Opc;
6842     if (VT == MVT::v8i16)
6843       Opc = X86ISD::PINSRW;
6844     else if (VT == MVT::v16i8)
6845       Opc = X86ISD::PINSRB;
6846     else
6847       Opc = X86ISD::PINSRB;
6848
6849     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6850     // argument.
6851     if (N1.getValueType() != MVT::i32)
6852       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6853     if (N2.getValueType() != MVT::i32)
6854       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6855     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6856   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6857     // Bits [7:6] of the constant are the source select.  This will always be
6858     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6859     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6860     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6861     // Bits [5:4] of the constant are the destination select.  This is the
6862     //  value of the incoming immediate.
6863     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6864     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6865     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6866     // Create this as a scalar to vector..
6867     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6868     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6869   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6870              isa<ConstantSDNode>(N2)) {
6871     // PINSR* works with constant index.
6872     return Op;
6873   }
6874   return SDValue();
6875 }
6876
6877 SDValue
6878 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6879   EVT VT = Op.getValueType();
6880   EVT EltVT = VT.getVectorElementType();
6881
6882   DebugLoc dl = Op.getDebugLoc();
6883   SDValue N0 = Op.getOperand(0);
6884   SDValue N1 = Op.getOperand(1);
6885   SDValue N2 = Op.getOperand(2);
6886
6887   // If this is a 256-bit vector result, first extract the 128-bit vector,
6888   // insert the element into the extracted half and then place it back.
6889   if (VT.getSizeInBits() == 256) {
6890     if (!isa<ConstantSDNode>(N2))
6891       return SDValue();
6892
6893     // Get the desired 128-bit vector half.
6894     unsigned NumElems = VT.getVectorNumElements();
6895     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6896     bool Upper = IdxVal >= NumElems/2;
6897     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6898     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6899
6900     // Insert the element into the desired half.
6901     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6902                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6903
6904     // Insert the changed part back to the 256-bit vector
6905     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6906   }
6907
6908   if (Subtarget->hasSSE41())
6909     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6910
6911   if (EltVT == MVT::i8)
6912     return SDValue();
6913
6914   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6915     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6916     // as its second argument.
6917     if (N1.getValueType() != MVT::i32)
6918       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6919     if (N2.getValueType() != MVT::i32)
6920       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6921     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6922   }
6923   return SDValue();
6924 }
6925
6926 SDValue
6927 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6928   LLVMContext *Context = DAG.getContext();
6929   DebugLoc dl = Op.getDebugLoc();
6930   EVT OpVT = Op.getValueType();
6931
6932   // If this is a 256-bit vector result, first insert into a 128-bit
6933   // vector and then insert into the 256-bit vector.
6934   if (OpVT.getSizeInBits() > 128) {
6935     // Insert into a 128-bit vector.
6936     EVT VT128 = EVT::getVectorVT(*Context,
6937                                  OpVT.getVectorElementType(),
6938                                  OpVT.getVectorNumElements() / 2);
6939
6940     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6941
6942     // Insert the 128-bit vector.
6943     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6944                               DAG.getConstant(0, MVT::i32),
6945                               DAG, dl);
6946   }
6947
6948   if (Op.getValueType() == MVT::v1i64 &&
6949       Op.getOperand(0).getValueType() == MVT::i64)
6950     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6951
6952   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6953   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6954          "Expected an SSE type!");
6955   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6956                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6957 }
6958
6959 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6960 // a simple subregister reference or explicit instructions to grab
6961 // upper bits of a vector.
6962 SDValue
6963 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6964   if (Subtarget->hasAVX()) {
6965     DebugLoc dl = Op.getNode()->getDebugLoc();
6966     SDValue Vec = Op.getNode()->getOperand(0);
6967     SDValue Idx = Op.getNode()->getOperand(1);
6968
6969     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6970         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6971         return Extract128BitVector(Vec, Idx, DAG, dl);
6972     }
6973   }
6974   return SDValue();
6975 }
6976
6977 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6978 // simple superregister reference or explicit instructions to insert
6979 // the upper bits of a vector.
6980 SDValue
6981 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6982   if (Subtarget->hasAVX()) {
6983     DebugLoc dl = Op.getNode()->getDebugLoc();
6984     SDValue Vec = Op.getNode()->getOperand(0);
6985     SDValue SubVec = Op.getNode()->getOperand(1);
6986     SDValue Idx = Op.getNode()->getOperand(2);
6987
6988     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6989         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6990       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6991     }
6992   }
6993   return SDValue();
6994 }
6995
6996 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6997 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6998 // one of the above mentioned nodes. It has to be wrapped because otherwise
6999 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7000 // be used to form addressing mode. These wrapped nodes will be selected
7001 // into MOV32ri.
7002 SDValue
7003 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7004   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7005
7006   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7007   // global base reg.
7008   unsigned char OpFlag = 0;
7009   unsigned WrapperKind = X86ISD::Wrapper;
7010   CodeModel::Model M = getTargetMachine().getCodeModel();
7011
7012   if (Subtarget->isPICStyleRIPRel() &&
7013       (M == CodeModel::Small || M == CodeModel::Kernel))
7014     WrapperKind = X86ISD::WrapperRIP;
7015   else if (Subtarget->isPICStyleGOT())
7016     OpFlag = X86II::MO_GOTOFF;
7017   else if (Subtarget->isPICStyleStubPIC())
7018     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7019
7020   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7021                                              CP->getAlignment(),
7022                                              CP->getOffset(), OpFlag);
7023   DebugLoc DL = CP->getDebugLoc();
7024   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7025   // With PIC, the address is actually $g + Offset.
7026   if (OpFlag) {
7027     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7028                          DAG.getNode(X86ISD::GlobalBaseReg,
7029                                      DebugLoc(), getPointerTy()),
7030                          Result);
7031   }
7032
7033   return Result;
7034 }
7035
7036 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7037   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7038
7039   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7040   // global base reg.
7041   unsigned char OpFlag = 0;
7042   unsigned WrapperKind = X86ISD::Wrapper;
7043   CodeModel::Model M = getTargetMachine().getCodeModel();
7044
7045   if (Subtarget->isPICStyleRIPRel() &&
7046       (M == CodeModel::Small || M == CodeModel::Kernel))
7047     WrapperKind = X86ISD::WrapperRIP;
7048   else if (Subtarget->isPICStyleGOT())
7049     OpFlag = X86II::MO_GOTOFF;
7050   else if (Subtarget->isPICStyleStubPIC())
7051     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7052
7053   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7054                                           OpFlag);
7055   DebugLoc DL = JT->getDebugLoc();
7056   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7057
7058   // With PIC, the address is actually $g + Offset.
7059   if (OpFlag)
7060     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7061                          DAG.getNode(X86ISD::GlobalBaseReg,
7062                                      DebugLoc(), getPointerTy()),
7063                          Result);
7064
7065   return Result;
7066 }
7067
7068 SDValue
7069 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7070   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7071
7072   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7073   // global base reg.
7074   unsigned char OpFlag = 0;
7075   unsigned WrapperKind = X86ISD::Wrapper;
7076   CodeModel::Model M = getTargetMachine().getCodeModel();
7077
7078   if (Subtarget->isPICStyleRIPRel() &&
7079       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7080     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7081       OpFlag = X86II::MO_GOTPCREL;
7082     WrapperKind = X86ISD::WrapperRIP;
7083   } else if (Subtarget->isPICStyleGOT()) {
7084     OpFlag = X86II::MO_GOT;
7085   } else if (Subtarget->isPICStyleStubPIC()) {
7086     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7087   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7088     OpFlag = X86II::MO_DARWIN_NONLAZY;
7089   }
7090
7091   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7092
7093   DebugLoc DL = Op.getDebugLoc();
7094   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7095
7096
7097   // With PIC, the address is actually $g + Offset.
7098   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7099       !Subtarget->is64Bit()) {
7100     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7101                          DAG.getNode(X86ISD::GlobalBaseReg,
7102                                      DebugLoc(), getPointerTy()),
7103                          Result);
7104   }
7105
7106   // For symbols that require a load from a stub to get the address, emit the
7107   // load.
7108   if (isGlobalStubReference(OpFlag))
7109     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7110                          MachinePointerInfo::getGOT(), false, false, false, 0);
7111
7112   return Result;
7113 }
7114
7115 SDValue
7116 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7117   // Create the TargetBlockAddressAddress node.
7118   unsigned char OpFlags =
7119     Subtarget->ClassifyBlockAddressReference();
7120   CodeModel::Model M = getTargetMachine().getCodeModel();
7121   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7122   DebugLoc dl = Op.getDebugLoc();
7123   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7124                                        /*isTarget=*/true, OpFlags);
7125
7126   if (Subtarget->isPICStyleRIPRel() &&
7127       (M == CodeModel::Small || M == CodeModel::Kernel))
7128     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7129   else
7130     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7131
7132   // With PIC, the address is actually $g + Offset.
7133   if (isGlobalRelativeToPICBase(OpFlags)) {
7134     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7135                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7136                          Result);
7137   }
7138
7139   return Result;
7140 }
7141
7142 SDValue
7143 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7144                                       int64_t Offset,
7145                                       SelectionDAG &DAG) const {
7146   // Create the TargetGlobalAddress node, folding in the constant
7147   // offset if it is legal.
7148   unsigned char OpFlags =
7149     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7150   CodeModel::Model M = getTargetMachine().getCodeModel();
7151   SDValue Result;
7152   if (OpFlags == X86II::MO_NO_FLAG &&
7153       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7154     // A direct static reference to a global.
7155     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7156     Offset = 0;
7157   } else {
7158     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7159   }
7160
7161   if (Subtarget->isPICStyleRIPRel() &&
7162       (M == CodeModel::Small || M == CodeModel::Kernel))
7163     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7164   else
7165     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7166
7167   // With PIC, the address is actually $g + Offset.
7168   if (isGlobalRelativeToPICBase(OpFlags)) {
7169     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7170                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7171                          Result);
7172   }
7173
7174   // For globals that require a load from a stub to get the address, emit the
7175   // load.
7176   if (isGlobalStubReference(OpFlags))
7177     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7178                          MachinePointerInfo::getGOT(), false, false, false, 0);
7179
7180   // If there was a non-zero offset that we didn't fold, create an explicit
7181   // addition for it.
7182   if (Offset != 0)
7183     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7184                          DAG.getConstant(Offset, getPointerTy()));
7185
7186   return Result;
7187 }
7188
7189 SDValue
7190 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7191   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7192   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7193   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7194 }
7195
7196 static SDValue
7197 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7198            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7199            unsigned char OperandFlags) {
7200   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7201   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7202   DebugLoc dl = GA->getDebugLoc();
7203   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7204                                            GA->getValueType(0),
7205                                            GA->getOffset(),
7206                                            OperandFlags);
7207   if (InFlag) {
7208     SDValue Ops[] = { Chain,  TGA, *InFlag };
7209     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7210   } else {
7211     SDValue Ops[]  = { Chain, TGA };
7212     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7213   }
7214
7215   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7216   MFI->setAdjustsStack(true);
7217
7218   SDValue Flag = Chain.getValue(1);
7219   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7220 }
7221
7222 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7223 static SDValue
7224 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7225                                 const EVT PtrVT) {
7226   SDValue InFlag;
7227   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7228   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7229                                      DAG.getNode(X86ISD::GlobalBaseReg,
7230                                                  DebugLoc(), PtrVT), InFlag);
7231   InFlag = Chain.getValue(1);
7232
7233   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7234 }
7235
7236 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7237 static SDValue
7238 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7239                                 const EVT PtrVT) {
7240   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7241                     X86::RAX, X86II::MO_TLSGD);
7242 }
7243
7244 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7245 // "local exec" model.
7246 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7247                                    const EVT PtrVT, TLSModel::Model model,
7248                                    bool is64Bit) {
7249   DebugLoc dl = GA->getDebugLoc();
7250
7251   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7252   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7253                                                          is64Bit ? 257 : 256));
7254
7255   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7256                                       DAG.getIntPtrConstant(0),
7257                                       MachinePointerInfo(Ptr),
7258                                       false, false, false, 0);
7259
7260   unsigned char OperandFlags = 0;
7261   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7262   // initialexec.
7263   unsigned WrapperKind = X86ISD::Wrapper;
7264   if (model == TLSModel::LocalExec) {
7265     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7266   } else if (is64Bit) {
7267     assert(model == TLSModel::InitialExec);
7268     OperandFlags = X86II::MO_GOTTPOFF;
7269     WrapperKind = X86ISD::WrapperRIP;
7270   } else {
7271     assert(model == TLSModel::InitialExec);
7272     OperandFlags = X86II::MO_INDNTPOFF;
7273   }
7274
7275   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7276   // exec)
7277   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7278                                            GA->getValueType(0),
7279                                            GA->getOffset(), OperandFlags);
7280   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7281
7282   if (model == TLSModel::InitialExec)
7283     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7284                          MachinePointerInfo::getGOT(), false, false, false, 0);
7285
7286   // The address of the thread local variable is the add of the thread
7287   // pointer with the offset of the variable.
7288   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7289 }
7290
7291 SDValue
7292 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7293
7294   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7295   const GlobalValue *GV = GA->getGlobal();
7296
7297   if (Subtarget->isTargetELF()) {
7298     // TODO: implement the "local dynamic" model
7299     // TODO: implement the "initial exec"model for pic executables
7300
7301     // If GV is an alias then use the aliasee for determining
7302     // thread-localness.
7303     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7304       GV = GA->resolveAliasedGlobal(false);
7305
7306     TLSModel::Model model
7307       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7308
7309     switch (model) {
7310       case TLSModel::GeneralDynamic:
7311       case TLSModel::LocalDynamic: // not implemented
7312         if (Subtarget->is64Bit())
7313           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7314         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7315
7316       case TLSModel::InitialExec:
7317       case TLSModel::LocalExec:
7318         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7319                                    Subtarget->is64Bit());
7320     }
7321   } else if (Subtarget->isTargetDarwin()) {
7322     // Darwin only has one model of TLS.  Lower to that.
7323     unsigned char OpFlag = 0;
7324     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7325                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7326
7327     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7328     // global base reg.
7329     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7330                   !Subtarget->is64Bit();
7331     if (PIC32)
7332       OpFlag = X86II::MO_TLVP_PIC_BASE;
7333     else
7334       OpFlag = X86II::MO_TLVP;
7335     DebugLoc DL = Op.getDebugLoc();
7336     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7337                                                 GA->getValueType(0),
7338                                                 GA->getOffset(), OpFlag);
7339     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7340
7341     // With PIC32, the address is actually $g + Offset.
7342     if (PIC32)
7343       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7344                            DAG.getNode(X86ISD::GlobalBaseReg,
7345                                        DebugLoc(), getPointerTy()),
7346                            Offset);
7347
7348     // Lowering the machine isd will make sure everything is in the right
7349     // location.
7350     SDValue Chain = DAG.getEntryNode();
7351     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7352     SDValue Args[] = { Chain, Offset };
7353     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7354
7355     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7356     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7357     MFI->setAdjustsStack(true);
7358
7359     // And our return value (tls address) is in the standard call return value
7360     // location.
7361     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7362     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7363                               Chain.getValue(1));
7364   }
7365
7366   llvm_unreachable("TLS not implemented for this target.");
7367 }
7368
7369
7370 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7371 /// and take a 2 x i32 value to shift plus a shift amount.
7372 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7373   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7374   EVT VT = Op.getValueType();
7375   unsigned VTBits = VT.getSizeInBits();
7376   DebugLoc dl = Op.getDebugLoc();
7377   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7378   SDValue ShOpLo = Op.getOperand(0);
7379   SDValue ShOpHi = Op.getOperand(1);
7380   SDValue ShAmt  = Op.getOperand(2);
7381   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7382                                      DAG.getConstant(VTBits - 1, MVT::i8))
7383                        : DAG.getConstant(0, VT);
7384
7385   SDValue Tmp2, Tmp3;
7386   if (Op.getOpcode() == ISD::SHL_PARTS) {
7387     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7388     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7389   } else {
7390     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7391     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7392   }
7393
7394   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7395                                 DAG.getConstant(VTBits, MVT::i8));
7396   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7397                              AndNode, DAG.getConstant(0, MVT::i8));
7398
7399   SDValue Hi, Lo;
7400   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7401   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7402   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7403
7404   if (Op.getOpcode() == ISD::SHL_PARTS) {
7405     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7406     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7407   } else {
7408     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7409     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7410   }
7411
7412   SDValue Ops[2] = { Lo, Hi };
7413   return DAG.getMergeValues(Ops, 2, dl);
7414 }
7415
7416 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7417                                            SelectionDAG &DAG) const {
7418   EVT SrcVT = Op.getOperand(0).getValueType();
7419
7420   if (SrcVT.isVector())
7421     return SDValue();
7422
7423   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7424          "Unknown SINT_TO_FP to lower!");
7425
7426   // These are really Legal; return the operand so the caller accepts it as
7427   // Legal.
7428   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7429     return Op;
7430   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7431       Subtarget->is64Bit()) {
7432     return Op;
7433   }
7434
7435   DebugLoc dl = Op.getDebugLoc();
7436   unsigned Size = SrcVT.getSizeInBits()/8;
7437   MachineFunction &MF = DAG.getMachineFunction();
7438   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7439   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7440   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7441                                StackSlot,
7442                                MachinePointerInfo::getFixedStack(SSFI),
7443                                false, false, 0);
7444   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7445 }
7446
7447 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7448                                      SDValue StackSlot,
7449                                      SelectionDAG &DAG) const {
7450   // Build the FILD
7451   DebugLoc DL = Op.getDebugLoc();
7452   SDVTList Tys;
7453   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7454   if (useSSE)
7455     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7456   else
7457     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7458
7459   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7460
7461   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7462   MachineMemOperand *MMO;
7463   if (FI) {
7464     int SSFI = FI->getIndex();
7465     MMO =
7466       DAG.getMachineFunction()
7467       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7468                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7469   } else {
7470     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7471     StackSlot = StackSlot.getOperand(1);
7472   }
7473   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7474   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7475                                            X86ISD::FILD, DL,
7476                                            Tys, Ops, array_lengthof(Ops),
7477                                            SrcVT, MMO);
7478
7479   if (useSSE) {
7480     Chain = Result.getValue(1);
7481     SDValue InFlag = Result.getValue(2);
7482
7483     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7484     // shouldn't be necessary except that RFP cannot be live across
7485     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7486     MachineFunction &MF = DAG.getMachineFunction();
7487     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7488     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7489     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7490     Tys = DAG.getVTList(MVT::Other);
7491     SDValue Ops[] = {
7492       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7493     };
7494     MachineMemOperand *MMO =
7495       DAG.getMachineFunction()
7496       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7497                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7498
7499     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7500                                     Ops, array_lengthof(Ops),
7501                                     Op.getValueType(), MMO);
7502     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7503                          MachinePointerInfo::getFixedStack(SSFI),
7504                          false, false, false, 0);
7505   }
7506
7507   return Result;
7508 }
7509
7510 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7511 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7512                                                SelectionDAG &DAG) const {
7513   // This algorithm is not obvious. Here it is what we're trying to output:
7514   /*
7515      movq       %rax,  %xmm0
7516      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7517      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7518      #ifdef __SSE3__
7519        haddpd   %xmm0, %xmm0          
7520      #else
7521        pshufd   $0x4e, %xmm0, %xmm1 
7522        addpd    %xmm1, %xmm0
7523      #endif
7524   */
7525
7526   DebugLoc dl = Op.getDebugLoc();
7527   LLVMContext *Context = DAG.getContext();
7528
7529   // Build some magic constants.
7530   SmallVector<Constant*,4> CV0;
7531   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7532   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7533   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7534   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7535   Constant *C0 = ConstantVector::get(CV0);
7536   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7537
7538   SmallVector<Constant*,2> CV1;
7539   CV1.push_back(
7540         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7541   CV1.push_back(
7542         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7543   Constant *C1 = ConstantVector::get(CV1);
7544   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7545
7546   // Load the 64-bit value into an XMM register.
7547   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7548                             Op.getOperand(0));
7549   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7550                               MachinePointerInfo::getConstantPool(),
7551                               false, false, false, 16);
7552   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7553                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7554                               CLod0);
7555
7556   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7557                               MachinePointerInfo::getConstantPool(),
7558                               false, false, false, 16);
7559   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7560   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7561   SDValue Result;
7562
7563   if (Subtarget->hasSSE3()) {
7564     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7565     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7566   } else {
7567     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7568     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7569                                            S2F, 0x4E, DAG);
7570     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7571                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7572                          Sub);
7573   }
7574
7575   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7576                      DAG.getIntPtrConstant(0));
7577 }
7578
7579 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7580 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7581                                                SelectionDAG &DAG) const {
7582   DebugLoc dl = Op.getDebugLoc();
7583   // FP constant to bias correct the final result.
7584   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7585                                    MVT::f64);
7586
7587   // Load the 32-bit value into an XMM register.
7588   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7589                              Op.getOperand(0));
7590
7591   // Zero out the upper parts of the register.
7592   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7593
7594   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7595                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7596                      DAG.getIntPtrConstant(0));
7597
7598   // Or the load with the bias.
7599   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7600                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7601                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7602                                                    MVT::v2f64, Load)),
7603                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7604                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7605                                                    MVT::v2f64, Bias)));
7606   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7607                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7608                    DAG.getIntPtrConstant(0));
7609
7610   // Subtract the bias.
7611   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7612
7613   // Handle final rounding.
7614   EVT DestVT = Op.getValueType();
7615
7616   if (DestVT.bitsLT(MVT::f64)) {
7617     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7618                        DAG.getIntPtrConstant(0));
7619   } else if (DestVT.bitsGT(MVT::f64)) {
7620     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7621   }
7622
7623   // Handle final rounding.
7624   return Sub;
7625 }
7626
7627 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7628                                            SelectionDAG &DAG) const {
7629   SDValue N0 = Op.getOperand(0);
7630   DebugLoc dl = Op.getDebugLoc();
7631
7632   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7633   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7634   // the optimization here.
7635   if (DAG.SignBitIsZero(N0))
7636     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7637
7638   EVT SrcVT = N0.getValueType();
7639   EVT DstVT = Op.getValueType();
7640   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7641     return LowerUINT_TO_FP_i64(Op, DAG);
7642   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7643     return LowerUINT_TO_FP_i32(Op, DAG);
7644   else if (Subtarget->is64Bit() &&
7645            SrcVT == MVT::i64 && DstVT == MVT::f32)
7646     return SDValue();
7647
7648   // Make a 64-bit buffer, and use it to build an FILD.
7649   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7650   if (SrcVT == MVT::i32) {
7651     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7652     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7653                                      getPointerTy(), StackSlot, WordOff);
7654     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7655                                   StackSlot, MachinePointerInfo(),
7656                                   false, false, 0);
7657     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7658                                   OffsetSlot, MachinePointerInfo(),
7659                                   false, false, 0);
7660     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7661     return Fild;
7662   }
7663
7664   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7665   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7666                                StackSlot, MachinePointerInfo(),
7667                                false, false, 0);
7668   // For i64 source, we need to add the appropriate power of 2 if the input
7669   // was negative.  This is the same as the optimization in
7670   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7671   // we must be careful to do the computation in x87 extended precision, not
7672   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7673   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7674   MachineMemOperand *MMO =
7675     DAG.getMachineFunction()
7676     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7677                           MachineMemOperand::MOLoad, 8, 8);
7678
7679   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7680   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7681   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7682                                          MVT::i64, MMO);
7683
7684   APInt FF(32, 0x5F800000ULL);
7685
7686   // Check whether the sign bit is set.
7687   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7688                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7689                                  ISD::SETLT);
7690
7691   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7692   SDValue FudgePtr = DAG.getConstantPool(
7693                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7694                                          getPointerTy());
7695
7696   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7697   SDValue Zero = DAG.getIntPtrConstant(0);
7698   SDValue Four = DAG.getIntPtrConstant(4);
7699   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7700                                Zero, Four);
7701   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7702
7703   // Load the value out, extending it from f32 to f80.
7704   // FIXME: Avoid the extend by constructing the right constant pool?
7705   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7706                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7707                                  MVT::f32, false, false, 4);
7708   // Extend everything to 80 bits to force it to be done on x87.
7709   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7710   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7711 }
7712
7713 std::pair<SDValue,SDValue> X86TargetLowering::
7714 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7715   DebugLoc DL = Op.getDebugLoc();
7716
7717   EVT DstTy = Op.getValueType();
7718
7719   if (!IsSigned) {
7720     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7721     DstTy = MVT::i64;
7722   }
7723
7724   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7725          DstTy.getSimpleVT() >= MVT::i16 &&
7726          "Unknown FP_TO_SINT to lower!");
7727
7728   // These are really Legal.
7729   if (DstTy == MVT::i32 &&
7730       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7731     return std::make_pair(SDValue(), SDValue());
7732   if (Subtarget->is64Bit() &&
7733       DstTy == MVT::i64 &&
7734       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7735     return std::make_pair(SDValue(), SDValue());
7736
7737   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7738   // stack slot.
7739   MachineFunction &MF = DAG.getMachineFunction();
7740   unsigned MemSize = DstTy.getSizeInBits()/8;
7741   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7742   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7743
7744
7745
7746   unsigned Opc;
7747   switch (DstTy.getSimpleVT().SimpleTy) {
7748   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7749   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7750   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7751   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7752   }
7753
7754   SDValue Chain = DAG.getEntryNode();
7755   SDValue Value = Op.getOperand(0);
7756   EVT TheVT = Op.getOperand(0).getValueType();
7757   if (isScalarFPTypeInSSEReg(TheVT)) {
7758     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7759     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7760                          MachinePointerInfo::getFixedStack(SSFI),
7761                          false, false, 0);
7762     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7763     SDValue Ops[] = {
7764       Chain, StackSlot, DAG.getValueType(TheVT)
7765     };
7766
7767     MachineMemOperand *MMO =
7768       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7769                               MachineMemOperand::MOLoad, MemSize, MemSize);
7770     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7771                                     DstTy, MMO);
7772     Chain = Value.getValue(1);
7773     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7774     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7775   }
7776
7777   MachineMemOperand *MMO =
7778     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7779                             MachineMemOperand::MOStore, MemSize, MemSize);
7780
7781   // Build the FP_TO_INT*_IN_MEM
7782   SDValue Ops[] = { Chain, Value, StackSlot };
7783   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7784                                          Ops, 3, DstTy, MMO);
7785
7786   return std::make_pair(FIST, StackSlot);
7787 }
7788
7789 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7790                                            SelectionDAG &DAG) const {
7791   if (Op.getValueType().isVector())
7792     return SDValue();
7793
7794   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7795   SDValue FIST = Vals.first, StackSlot = Vals.second;
7796   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7797   if (FIST.getNode() == 0) return Op;
7798
7799   // Load the result.
7800   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7801                      FIST, StackSlot, MachinePointerInfo(),
7802                      false, false, false, 0);
7803 }
7804
7805 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7806                                            SelectionDAG &DAG) const {
7807   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7808   SDValue FIST = Vals.first, StackSlot = Vals.second;
7809   assert(FIST.getNode() && "Unexpected failure");
7810
7811   // Load the result.
7812   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7813                      FIST, StackSlot, MachinePointerInfo(),
7814                      false, false, false, 0);
7815 }
7816
7817 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7818                                      SelectionDAG &DAG) const {
7819   LLVMContext *Context = DAG.getContext();
7820   DebugLoc dl = Op.getDebugLoc();
7821   EVT VT = Op.getValueType();
7822   EVT EltVT = VT;
7823   if (VT.isVector())
7824     EltVT = VT.getVectorElementType();
7825   Constant *C;
7826   if (EltVT == MVT::f64) {
7827     C = ConstantVector::getSplat(2, 
7828                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7829   } else {
7830     C = ConstantVector::getSplat(4,
7831                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7832   }
7833   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7834   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7835                              MachinePointerInfo::getConstantPool(),
7836                              false, false, false, 16);
7837   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7838 }
7839
7840 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7841   LLVMContext *Context = DAG.getContext();
7842   DebugLoc dl = Op.getDebugLoc();
7843   EVT VT = Op.getValueType();
7844   EVT EltVT = VT;
7845   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7846   if (VT.isVector()) {
7847     EltVT = VT.getVectorElementType();
7848     NumElts = VT.getVectorNumElements();
7849   }
7850   Constant *C;
7851   if (EltVT == MVT::f64)
7852     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7853   else
7854     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7855   C = ConstantVector::getSplat(NumElts, C);
7856   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7857   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7858                              MachinePointerInfo::getConstantPool(),
7859                              false, false, false, 16);
7860   if (VT.isVector()) {
7861     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7862     return DAG.getNode(ISD::BITCAST, dl, VT,
7863                        DAG.getNode(ISD::XOR, dl, XORVT,
7864                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7865                                 Op.getOperand(0)),
7866                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7867   } else {
7868     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7869   }
7870 }
7871
7872 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7873   LLVMContext *Context = DAG.getContext();
7874   SDValue Op0 = Op.getOperand(0);
7875   SDValue Op1 = Op.getOperand(1);
7876   DebugLoc dl = Op.getDebugLoc();
7877   EVT VT = Op.getValueType();
7878   EVT SrcVT = Op1.getValueType();
7879
7880   // If second operand is smaller, extend it first.
7881   if (SrcVT.bitsLT(VT)) {
7882     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7883     SrcVT = VT;
7884   }
7885   // And if it is bigger, shrink it first.
7886   if (SrcVT.bitsGT(VT)) {
7887     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7888     SrcVT = VT;
7889   }
7890
7891   // At this point the operands and the result should have the same
7892   // type, and that won't be f80 since that is not custom lowered.
7893
7894   // First get the sign bit of second operand.
7895   SmallVector<Constant*,4> CV;
7896   if (SrcVT == MVT::f64) {
7897     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7898     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7899   } else {
7900     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7901     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7902     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7903     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7904   }
7905   Constant *C = ConstantVector::get(CV);
7906   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7907   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7908                               MachinePointerInfo::getConstantPool(),
7909                               false, false, false, 16);
7910   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7911
7912   // Shift sign bit right or left if the two operands have different types.
7913   if (SrcVT.bitsGT(VT)) {
7914     // Op0 is MVT::f32, Op1 is MVT::f64.
7915     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7916     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7917                           DAG.getConstant(32, MVT::i32));
7918     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7919     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7920                           DAG.getIntPtrConstant(0));
7921   }
7922
7923   // Clear first operand sign bit.
7924   CV.clear();
7925   if (VT == MVT::f64) {
7926     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7927     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7928   } else {
7929     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7930     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7931     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7932     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7933   }
7934   C = ConstantVector::get(CV);
7935   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7936   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7937                               MachinePointerInfo::getConstantPool(),
7938                               false, false, false, 16);
7939   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7940
7941   // Or the value with the sign bit.
7942   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7943 }
7944
7945 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7946   SDValue N0 = Op.getOperand(0);
7947   DebugLoc dl = Op.getDebugLoc();
7948   EVT VT = Op.getValueType();
7949
7950   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7951   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7952                                   DAG.getConstant(1, VT));
7953   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7954 }
7955
7956 /// Emit nodes that will be selected as "test Op0,Op0", or something
7957 /// equivalent.
7958 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7959                                     SelectionDAG &DAG) const {
7960   DebugLoc dl = Op.getDebugLoc();
7961
7962   // CF and OF aren't always set the way we want. Determine which
7963   // of these we need.
7964   bool NeedCF = false;
7965   bool NeedOF = false;
7966   switch (X86CC) {
7967   default: break;
7968   case X86::COND_A: case X86::COND_AE:
7969   case X86::COND_B: case X86::COND_BE:
7970     NeedCF = true;
7971     break;
7972   case X86::COND_G: case X86::COND_GE:
7973   case X86::COND_L: case X86::COND_LE:
7974   case X86::COND_O: case X86::COND_NO:
7975     NeedOF = true;
7976     break;
7977   }
7978
7979   // See if we can use the EFLAGS value from the operand instead of
7980   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7981   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7982   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7983     // Emit a CMP with 0, which is the TEST pattern.
7984     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7985                        DAG.getConstant(0, Op.getValueType()));
7986
7987   unsigned Opcode = 0;
7988   unsigned NumOperands = 0;
7989   switch (Op.getNode()->getOpcode()) {
7990   case ISD::ADD:
7991     // Due to an isel shortcoming, be conservative if this add is likely to be
7992     // selected as part of a load-modify-store instruction. When the root node
7993     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7994     // uses of other nodes in the match, such as the ADD in this case. This
7995     // leads to the ADD being left around and reselected, with the result being
7996     // two adds in the output.  Alas, even if none our users are stores, that
7997     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7998     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7999     // climbing the DAG back to the root, and it doesn't seem to be worth the
8000     // effort.
8001     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8002          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8003       if (UI->getOpcode() != ISD::CopyToReg &&
8004           UI->getOpcode() != ISD::SETCC &&
8005           UI->getOpcode() != ISD::STORE)
8006         goto default_case;
8007
8008     if (ConstantSDNode *C =
8009         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8010       // An add of one will be selected as an INC.
8011       if (C->getAPIntValue() == 1) {
8012         Opcode = X86ISD::INC;
8013         NumOperands = 1;
8014         break;
8015       }
8016
8017       // An add of negative one (subtract of one) will be selected as a DEC.
8018       if (C->getAPIntValue().isAllOnesValue()) {
8019         Opcode = X86ISD::DEC;
8020         NumOperands = 1;
8021         break;
8022       }
8023     }
8024
8025     // Otherwise use a regular EFLAGS-setting add.
8026     Opcode = X86ISD::ADD;
8027     NumOperands = 2;
8028     break;
8029   case ISD::AND: {
8030     // If the primary and result isn't used, don't bother using X86ISD::AND,
8031     // because a TEST instruction will be better.
8032     bool NonFlagUse = false;
8033     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8034            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8035       SDNode *User = *UI;
8036       unsigned UOpNo = UI.getOperandNo();
8037       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8038         // Look pass truncate.
8039         UOpNo = User->use_begin().getOperandNo();
8040         User = *User->use_begin();
8041       }
8042
8043       if (User->getOpcode() != ISD::BRCOND &&
8044           User->getOpcode() != ISD::SETCC &&
8045           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8046         NonFlagUse = true;
8047         break;
8048       }
8049     }
8050
8051     if (!NonFlagUse)
8052       break;
8053   }
8054     // FALL THROUGH
8055   case ISD::SUB:
8056   case ISD::OR:
8057   case ISD::XOR:
8058     // Due to the ISEL shortcoming noted above, be conservative if this op is
8059     // likely to be selected as part of a load-modify-store instruction.
8060     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8061            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8062       if (UI->getOpcode() == ISD::STORE)
8063         goto default_case;
8064
8065     // Otherwise use a regular EFLAGS-setting instruction.
8066     switch (Op.getNode()->getOpcode()) {
8067     default: llvm_unreachable("unexpected operator!");
8068     case ISD::SUB: Opcode = X86ISD::SUB; break;
8069     case ISD::OR:  Opcode = X86ISD::OR;  break;
8070     case ISD::XOR: Opcode = X86ISD::XOR; break;
8071     case ISD::AND: Opcode = X86ISD::AND; break;
8072     }
8073
8074     NumOperands = 2;
8075     break;
8076   case X86ISD::ADD:
8077   case X86ISD::SUB:
8078   case X86ISD::INC:
8079   case X86ISD::DEC:
8080   case X86ISD::OR:
8081   case X86ISD::XOR:
8082   case X86ISD::AND:
8083     return SDValue(Op.getNode(), 1);
8084   default:
8085   default_case:
8086     break;
8087   }
8088
8089   if (Opcode == 0)
8090     // Emit a CMP with 0, which is the TEST pattern.
8091     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8092                        DAG.getConstant(0, Op.getValueType()));
8093
8094   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8095   SmallVector<SDValue, 4> Ops;
8096   for (unsigned i = 0; i != NumOperands; ++i)
8097     Ops.push_back(Op.getOperand(i));
8098
8099   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8100   DAG.ReplaceAllUsesWith(Op, New);
8101   return SDValue(New.getNode(), 1);
8102 }
8103
8104 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8105 /// equivalent.
8106 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8107                                    SelectionDAG &DAG) const {
8108   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8109     if (C->getAPIntValue() == 0)
8110       return EmitTest(Op0, X86CC, DAG);
8111
8112   DebugLoc dl = Op0.getDebugLoc();
8113   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8114 }
8115
8116 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8117 /// if it's possible.
8118 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8119                                      DebugLoc dl, SelectionDAG &DAG) const {
8120   SDValue Op0 = And.getOperand(0);
8121   SDValue Op1 = And.getOperand(1);
8122   if (Op0.getOpcode() == ISD::TRUNCATE)
8123     Op0 = Op0.getOperand(0);
8124   if (Op1.getOpcode() == ISD::TRUNCATE)
8125     Op1 = Op1.getOperand(0);
8126
8127   SDValue LHS, RHS;
8128   if (Op1.getOpcode() == ISD::SHL)
8129     std::swap(Op0, Op1);
8130   if (Op0.getOpcode() == ISD::SHL) {
8131     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8132       if (And00C->getZExtValue() == 1) {
8133         // If we looked past a truncate, check that it's only truncating away
8134         // known zeros.
8135         unsigned BitWidth = Op0.getValueSizeInBits();
8136         unsigned AndBitWidth = And.getValueSizeInBits();
8137         if (BitWidth > AndBitWidth) {
8138           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8139           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8140           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8141             return SDValue();
8142         }
8143         LHS = Op1;
8144         RHS = Op0.getOperand(1);
8145       }
8146   } else if (Op1.getOpcode() == ISD::Constant) {
8147     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8148     uint64_t AndRHSVal = AndRHS->getZExtValue();
8149     SDValue AndLHS = Op0;
8150
8151     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8152       LHS = AndLHS.getOperand(0);
8153       RHS = AndLHS.getOperand(1);
8154     }
8155
8156     // Use BT if the immediate can't be encoded in a TEST instruction.
8157     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8158       LHS = AndLHS;
8159       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8160     }
8161   }
8162
8163   if (LHS.getNode()) {
8164     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8165     // instruction.  Since the shift amount is in-range-or-undefined, we know
8166     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8167     // the encoding for the i16 version is larger than the i32 version.
8168     // Also promote i16 to i32 for performance / code size reason.
8169     if (LHS.getValueType() == MVT::i8 ||
8170         LHS.getValueType() == MVT::i16)
8171       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8172
8173     // If the operand types disagree, extend the shift amount to match.  Since
8174     // BT ignores high bits (like shifts) we can use anyextend.
8175     if (LHS.getValueType() != RHS.getValueType())
8176       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8177
8178     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8179     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8180     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8181                        DAG.getConstant(Cond, MVT::i8), BT);
8182   }
8183
8184   return SDValue();
8185 }
8186
8187 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8188
8189   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8190
8191   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8192   SDValue Op0 = Op.getOperand(0);
8193   SDValue Op1 = Op.getOperand(1);
8194   DebugLoc dl = Op.getDebugLoc();
8195   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8196
8197   // Optimize to BT if possible.
8198   // Lower (X & (1 << N)) == 0 to BT(X, N).
8199   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8200   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8201   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8202       Op1.getOpcode() == ISD::Constant &&
8203       cast<ConstantSDNode>(Op1)->isNullValue() &&
8204       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8205     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8206     if (NewSetCC.getNode())
8207       return NewSetCC;
8208   }
8209
8210   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8211   // these.
8212   if (Op1.getOpcode() == ISD::Constant &&
8213       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8214        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8215       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8216
8217     // If the input is a setcc, then reuse the input setcc or use a new one with
8218     // the inverted condition.
8219     if (Op0.getOpcode() == X86ISD::SETCC) {
8220       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8221       bool Invert = (CC == ISD::SETNE) ^
8222         cast<ConstantSDNode>(Op1)->isNullValue();
8223       if (!Invert) return Op0;
8224
8225       CCode = X86::GetOppositeBranchCondition(CCode);
8226       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8227                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8228     }
8229   }
8230
8231   bool isFP = Op1.getValueType().isFloatingPoint();
8232   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8233   if (X86CC == X86::COND_INVALID)
8234     return SDValue();
8235
8236   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8237   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8238                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8239 }
8240
8241 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8242 // ones, and then concatenate the result back.
8243 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8244   EVT VT = Op.getValueType();
8245
8246   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8247          "Unsupported value type for operation");
8248
8249   int NumElems = VT.getVectorNumElements();
8250   DebugLoc dl = Op.getDebugLoc();
8251   SDValue CC = Op.getOperand(2);
8252   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8253   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8254
8255   // Extract the LHS vectors
8256   SDValue LHS = Op.getOperand(0);
8257   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8258   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8259
8260   // Extract the RHS vectors
8261   SDValue RHS = Op.getOperand(1);
8262   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8263   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8264
8265   // Issue the operation on the smaller types and concatenate the result back
8266   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8267   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8268   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8269                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8270                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8271 }
8272
8273
8274 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8275   SDValue Cond;
8276   SDValue Op0 = Op.getOperand(0);
8277   SDValue Op1 = Op.getOperand(1);
8278   SDValue CC = Op.getOperand(2);
8279   EVT VT = Op.getValueType();
8280   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8281   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8282   DebugLoc dl = Op.getDebugLoc();
8283
8284   if (isFP) {
8285     unsigned SSECC = 8;
8286     EVT EltVT = Op0.getValueType().getVectorElementType();
8287     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8288
8289     bool Swap = false;
8290
8291     // SSE Condition code mapping:
8292     //  0 - EQ
8293     //  1 - LT
8294     //  2 - LE
8295     //  3 - UNORD
8296     //  4 - NEQ
8297     //  5 - NLT
8298     //  6 - NLE
8299     //  7 - ORD
8300     switch (SetCCOpcode) {
8301     default: break;
8302     case ISD::SETOEQ:
8303     case ISD::SETEQ:  SSECC = 0; break;
8304     case ISD::SETOGT:
8305     case ISD::SETGT: Swap = true; // Fallthrough
8306     case ISD::SETLT:
8307     case ISD::SETOLT: SSECC = 1; break;
8308     case ISD::SETOGE:
8309     case ISD::SETGE: Swap = true; // Fallthrough
8310     case ISD::SETLE:
8311     case ISD::SETOLE: SSECC = 2; break;
8312     case ISD::SETUO:  SSECC = 3; break;
8313     case ISD::SETUNE:
8314     case ISD::SETNE:  SSECC = 4; break;
8315     case ISD::SETULE: Swap = true;
8316     case ISD::SETUGE: SSECC = 5; break;
8317     case ISD::SETULT: Swap = true;
8318     case ISD::SETUGT: SSECC = 6; break;
8319     case ISD::SETO:   SSECC = 7; break;
8320     }
8321     if (Swap)
8322       std::swap(Op0, Op1);
8323
8324     // In the two special cases we can't handle, emit two comparisons.
8325     if (SSECC == 8) {
8326       if (SetCCOpcode == ISD::SETUEQ) {
8327         SDValue UNORD, EQ;
8328         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8329                             DAG.getConstant(3, MVT::i8));
8330         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8331                          DAG.getConstant(0, MVT::i8));
8332         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8333       } else if (SetCCOpcode == ISD::SETONE) {
8334         SDValue ORD, NEQ;
8335         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8336                           DAG.getConstant(7, MVT::i8));
8337         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8338                           DAG.getConstant(4, MVT::i8));
8339         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8340       }
8341       llvm_unreachable("Illegal FP comparison");
8342     }
8343     // Handle all other FP comparisons here.
8344     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8345                        DAG.getConstant(SSECC, MVT::i8));
8346   }
8347
8348   // Break 256-bit integer vector compare into smaller ones.
8349   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8350     return Lower256IntVSETCC(Op, DAG);
8351
8352   // We are handling one of the integer comparisons here.  Since SSE only has
8353   // GT and EQ comparisons for integer, swapping operands and multiple
8354   // operations may be required for some comparisons.
8355   unsigned Opc = 0;
8356   bool Swap = false, Invert = false, FlipSigns = false;
8357
8358   switch (SetCCOpcode) {
8359   default: break;
8360   case ISD::SETNE:  Invert = true;
8361   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8362   case ISD::SETLT:  Swap = true;
8363   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8364   case ISD::SETGE:  Swap = true;
8365   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8366   case ISD::SETULT: Swap = true;
8367   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8368   case ISD::SETUGE: Swap = true;
8369   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8370   }
8371   if (Swap)
8372     std::swap(Op0, Op1);
8373
8374   // Check that the operation in question is available (most are plain SSE2,
8375   // but PCMPGTQ and PCMPEQQ have different requirements).
8376   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8377     return SDValue();
8378   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8379     return SDValue();
8380
8381   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8382   // bits of the inputs before performing those operations.
8383   if (FlipSigns) {
8384     EVT EltVT = VT.getVectorElementType();
8385     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8386                                       EltVT);
8387     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8388     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8389                                     SignBits.size());
8390     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8391     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8392   }
8393
8394   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8395
8396   // If the logical-not of the result is required, perform that now.
8397   if (Invert)
8398     Result = DAG.getNOT(dl, Result, VT);
8399
8400   return Result;
8401 }
8402
8403 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8404 static bool isX86LogicalCmp(SDValue Op) {
8405   unsigned Opc = Op.getNode()->getOpcode();
8406   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8407     return true;
8408   if (Op.getResNo() == 1 &&
8409       (Opc == X86ISD::ADD ||
8410        Opc == X86ISD::SUB ||
8411        Opc == X86ISD::ADC ||
8412        Opc == X86ISD::SBB ||
8413        Opc == X86ISD::SMUL ||
8414        Opc == X86ISD::UMUL ||
8415        Opc == X86ISD::INC ||
8416        Opc == X86ISD::DEC ||
8417        Opc == X86ISD::OR ||
8418        Opc == X86ISD::XOR ||
8419        Opc == X86ISD::AND))
8420     return true;
8421
8422   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8423     return true;
8424
8425   return false;
8426 }
8427
8428 static bool isZero(SDValue V) {
8429   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8430   return C && C->isNullValue();
8431 }
8432
8433 static bool isAllOnes(SDValue V) {
8434   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8435   return C && C->isAllOnesValue();
8436 }
8437
8438 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8439   bool addTest = true;
8440   SDValue Cond  = Op.getOperand(0);
8441   SDValue Op1 = Op.getOperand(1);
8442   SDValue Op2 = Op.getOperand(2);
8443   DebugLoc DL = Op.getDebugLoc();
8444   SDValue CC;
8445
8446   if (Cond.getOpcode() == ISD::SETCC) {
8447     SDValue NewCond = LowerSETCC(Cond, DAG);
8448     if (NewCond.getNode())
8449       Cond = NewCond;
8450   }
8451
8452   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8453   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8454   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8455   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8456   if (Cond.getOpcode() == X86ISD::SETCC &&
8457       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8458       isZero(Cond.getOperand(1).getOperand(1))) {
8459     SDValue Cmp = Cond.getOperand(1);
8460
8461     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8462
8463     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8464         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8465       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8466
8467       SDValue CmpOp0 = Cmp.getOperand(0);
8468       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8469                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8470
8471       SDValue Res =   // Res = 0 or -1.
8472         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8473                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8474
8475       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8476         Res = DAG.getNOT(DL, Res, Res.getValueType());
8477
8478       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8479       if (N2C == 0 || !N2C->isNullValue())
8480         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8481       return Res;
8482     }
8483   }
8484
8485   // Look past (and (setcc_carry (cmp ...)), 1).
8486   if (Cond.getOpcode() == ISD::AND &&
8487       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8488     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8489     if (C && C->getAPIntValue() == 1)
8490       Cond = Cond.getOperand(0);
8491   }
8492
8493   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8494   // setting operand in place of the X86ISD::SETCC.
8495   unsigned CondOpcode = Cond.getOpcode();
8496   if (CondOpcode == X86ISD::SETCC ||
8497       CondOpcode == X86ISD::SETCC_CARRY) {
8498     CC = Cond.getOperand(0);
8499
8500     SDValue Cmp = Cond.getOperand(1);
8501     unsigned Opc = Cmp.getOpcode();
8502     EVT VT = Op.getValueType();
8503
8504     bool IllegalFPCMov = false;
8505     if (VT.isFloatingPoint() && !VT.isVector() &&
8506         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8507       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8508
8509     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8510         Opc == X86ISD::BT) { // FIXME
8511       Cond = Cmp;
8512       addTest = false;
8513     }
8514   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8515              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8516              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8517               Cond.getOperand(0).getValueType() != MVT::i8)) {
8518     SDValue LHS = Cond.getOperand(0);
8519     SDValue RHS = Cond.getOperand(1);
8520     unsigned X86Opcode;
8521     unsigned X86Cond;
8522     SDVTList VTs;
8523     switch (CondOpcode) {
8524     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8525     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8526     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8527     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8528     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8529     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8530     default: llvm_unreachable("unexpected overflowing operator");
8531     }
8532     if (CondOpcode == ISD::UMULO)
8533       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8534                           MVT::i32);
8535     else
8536       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8537
8538     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8539
8540     if (CondOpcode == ISD::UMULO)
8541       Cond = X86Op.getValue(2);
8542     else
8543       Cond = X86Op.getValue(1);
8544
8545     CC = DAG.getConstant(X86Cond, MVT::i8);
8546     addTest = false;
8547   }
8548
8549   if (addTest) {
8550     // Look pass the truncate.
8551     if (Cond.getOpcode() == ISD::TRUNCATE)
8552       Cond = Cond.getOperand(0);
8553
8554     // We know the result of AND is compared against zero. Try to match
8555     // it to BT.
8556     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8557       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8558       if (NewSetCC.getNode()) {
8559         CC = NewSetCC.getOperand(0);
8560         Cond = NewSetCC.getOperand(1);
8561         addTest = false;
8562       }
8563     }
8564   }
8565
8566   if (addTest) {
8567     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8568     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8569   }
8570
8571   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8572   // a <  b ?  0 : -1 -> RES = setcc_carry
8573   // a >= b ? -1 :  0 -> RES = setcc_carry
8574   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8575   if (Cond.getOpcode() == X86ISD::CMP) {
8576     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8577
8578     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8579         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8580       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8581                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8582       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8583         return DAG.getNOT(DL, Res, Res.getValueType());
8584       return Res;
8585     }
8586   }
8587
8588   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8589   // condition is true.
8590   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8591   SDValue Ops[] = { Op2, Op1, CC, Cond };
8592   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8593 }
8594
8595 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8596 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8597 // from the AND / OR.
8598 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8599   Opc = Op.getOpcode();
8600   if (Opc != ISD::OR && Opc != ISD::AND)
8601     return false;
8602   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8603           Op.getOperand(0).hasOneUse() &&
8604           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8605           Op.getOperand(1).hasOneUse());
8606 }
8607
8608 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8609 // 1 and that the SETCC node has a single use.
8610 static bool isXor1OfSetCC(SDValue Op) {
8611   if (Op.getOpcode() != ISD::XOR)
8612     return false;
8613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8614   if (N1C && N1C->getAPIntValue() == 1) {
8615     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8616       Op.getOperand(0).hasOneUse();
8617   }
8618   return false;
8619 }
8620
8621 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8622   bool addTest = true;
8623   SDValue Chain = Op.getOperand(0);
8624   SDValue Cond  = Op.getOperand(1);
8625   SDValue Dest  = Op.getOperand(2);
8626   DebugLoc dl = Op.getDebugLoc();
8627   SDValue CC;
8628   bool Inverted = false;
8629
8630   if (Cond.getOpcode() == ISD::SETCC) {
8631     // Check for setcc([su]{add,sub,mul}o == 0).
8632     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8633         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8634         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8635         Cond.getOperand(0).getResNo() == 1 &&
8636         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8637          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8638          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8639          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8640          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8641          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8642       Inverted = true;
8643       Cond = Cond.getOperand(0);
8644     } else {
8645       SDValue NewCond = LowerSETCC(Cond, DAG);
8646       if (NewCond.getNode())
8647         Cond = NewCond;
8648     }
8649   }
8650 #if 0
8651   // FIXME: LowerXALUO doesn't handle these!!
8652   else if (Cond.getOpcode() == X86ISD::ADD  ||
8653            Cond.getOpcode() == X86ISD::SUB  ||
8654            Cond.getOpcode() == X86ISD::SMUL ||
8655            Cond.getOpcode() == X86ISD::UMUL)
8656     Cond = LowerXALUO(Cond, DAG);
8657 #endif
8658
8659   // Look pass (and (setcc_carry (cmp ...)), 1).
8660   if (Cond.getOpcode() == ISD::AND &&
8661       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8662     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8663     if (C && C->getAPIntValue() == 1)
8664       Cond = Cond.getOperand(0);
8665   }
8666
8667   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8668   // setting operand in place of the X86ISD::SETCC.
8669   unsigned CondOpcode = Cond.getOpcode();
8670   if (CondOpcode == X86ISD::SETCC ||
8671       CondOpcode == X86ISD::SETCC_CARRY) {
8672     CC = Cond.getOperand(0);
8673
8674     SDValue Cmp = Cond.getOperand(1);
8675     unsigned Opc = Cmp.getOpcode();
8676     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8677     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8678       Cond = Cmp;
8679       addTest = false;
8680     } else {
8681       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8682       default: break;
8683       case X86::COND_O:
8684       case X86::COND_B:
8685         // These can only come from an arithmetic instruction with overflow,
8686         // e.g. SADDO, UADDO.
8687         Cond = Cond.getNode()->getOperand(1);
8688         addTest = false;
8689         break;
8690       }
8691     }
8692   }
8693   CondOpcode = Cond.getOpcode();
8694   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8695       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8696       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8697        Cond.getOperand(0).getValueType() != MVT::i8)) {
8698     SDValue LHS = Cond.getOperand(0);
8699     SDValue RHS = Cond.getOperand(1);
8700     unsigned X86Opcode;
8701     unsigned X86Cond;
8702     SDVTList VTs;
8703     switch (CondOpcode) {
8704     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8705     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8706     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8707     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8708     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8709     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8710     default: llvm_unreachable("unexpected overflowing operator");
8711     }
8712     if (Inverted)
8713       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8714     if (CondOpcode == ISD::UMULO)
8715       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8716                           MVT::i32);
8717     else
8718       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8719
8720     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8721
8722     if (CondOpcode == ISD::UMULO)
8723       Cond = X86Op.getValue(2);
8724     else
8725       Cond = X86Op.getValue(1);
8726
8727     CC = DAG.getConstant(X86Cond, MVT::i8);
8728     addTest = false;
8729   } else {
8730     unsigned CondOpc;
8731     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8732       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8733       if (CondOpc == ISD::OR) {
8734         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8735         // two branches instead of an explicit OR instruction with a
8736         // separate test.
8737         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8738             isX86LogicalCmp(Cmp)) {
8739           CC = Cond.getOperand(0).getOperand(0);
8740           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8741                               Chain, Dest, CC, Cmp);
8742           CC = Cond.getOperand(1).getOperand(0);
8743           Cond = Cmp;
8744           addTest = false;
8745         }
8746       } else { // ISD::AND
8747         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8748         // two branches instead of an explicit AND instruction with a
8749         // separate test. However, we only do this if this block doesn't
8750         // have a fall-through edge, because this requires an explicit
8751         // jmp when the condition is false.
8752         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8753             isX86LogicalCmp(Cmp) &&
8754             Op.getNode()->hasOneUse()) {
8755           X86::CondCode CCode =
8756             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8757           CCode = X86::GetOppositeBranchCondition(CCode);
8758           CC = DAG.getConstant(CCode, MVT::i8);
8759           SDNode *User = *Op.getNode()->use_begin();
8760           // Look for an unconditional branch following this conditional branch.
8761           // We need this because we need to reverse the successors in order
8762           // to implement FCMP_OEQ.
8763           if (User->getOpcode() == ISD::BR) {
8764             SDValue FalseBB = User->getOperand(1);
8765             SDNode *NewBR =
8766               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8767             assert(NewBR == User);
8768             (void)NewBR;
8769             Dest = FalseBB;
8770
8771             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8772                                 Chain, Dest, CC, Cmp);
8773             X86::CondCode CCode =
8774               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8775             CCode = X86::GetOppositeBranchCondition(CCode);
8776             CC = DAG.getConstant(CCode, MVT::i8);
8777             Cond = Cmp;
8778             addTest = false;
8779           }
8780         }
8781       }
8782     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8783       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8784       // It should be transformed during dag combiner except when the condition
8785       // is set by a arithmetics with overflow node.
8786       X86::CondCode CCode =
8787         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8788       CCode = X86::GetOppositeBranchCondition(CCode);
8789       CC = DAG.getConstant(CCode, MVT::i8);
8790       Cond = Cond.getOperand(0).getOperand(1);
8791       addTest = false;
8792     } else if (Cond.getOpcode() == ISD::SETCC &&
8793                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8794       // For FCMP_OEQ, we can emit
8795       // two branches instead of an explicit AND instruction with a
8796       // separate test. However, we only do this if this block doesn't
8797       // have a fall-through edge, because this requires an explicit
8798       // jmp when the condition is false.
8799       if (Op.getNode()->hasOneUse()) {
8800         SDNode *User = *Op.getNode()->use_begin();
8801         // Look for an unconditional branch following this conditional branch.
8802         // We need this because we need to reverse the successors in order
8803         // to implement FCMP_OEQ.
8804         if (User->getOpcode() == ISD::BR) {
8805           SDValue FalseBB = User->getOperand(1);
8806           SDNode *NewBR =
8807             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8808           assert(NewBR == User);
8809           (void)NewBR;
8810           Dest = FalseBB;
8811
8812           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8813                                     Cond.getOperand(0), Cond.getOperand(1));
8814           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8815           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8816                               Chain, Dest, CC, Cmp);
8817           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8818           Cond = Cmp;
8819           addTest = false;
8820         }
8821       }
8822     } else if (Cond.getOpcode() == ISD::SETCC &&
8823                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8824       // For FCMP_UNE, we can emit
8825       // two branches instead of an explicit AND instruction with a
8826       // separate test. However, we only do this if this block doesn't
8827       // have a fall-through edge, because this requires an explicit
8828       // jmp when the condition is false.
8829       if (Op.getNode()->hasOneUse()) {
8830         SDNode *User = *Op.getNode()->use_begin();
8831         // Look for an unconditional branch following this conditional branch.
8832         // We need this because we need to reverse the successors in order
8833         // to implement FCMP_UNE.
8834         if (User->getOpcode() == ISD::BR) {
8835           SDValue FalseBB = User->getOperand(1);
8836           SDNode *NewBR =
8837             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8838           assert(NewBR == User);
8839           (void)NewBR;
8840
8841           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8842                                     Cond.getOperand(0), Cond.getOperand(1));
8843           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8844           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8845                               Chain, Dest, CC, Cmp);
8846           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8847           Cond = Cmp;
8848           addTest = false;
8849           Dest = FalseBB;
8850         }
8851       }
8852     }
8853   }
8854
8855   if (addTest) {
8856     // Look pass the truncate.
8857     if (Cond.getOpcode() == ISD::TRUNCATE)
8858       Cond = Cond.getOperand(0);
8859
8860     // We know the result of AND is compared against zero. Try to match
8861     // it to BT.
8862     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8863       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8864       if (NewSetCC.getNode()) {
8865         CC = NewSetCC.getOperand(0);
8866         Cond = NewSetCC.getOperand(1);
8867         addTest = false;
8868       }
8869     }
8870   }
8871
8872   if (addTest) {
8873     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8874     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8875   }
8876   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8877                      Chain, Dest, CC, Cond);
8878 }
8879
8880
8881 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8882 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8883 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8884 // that the guard pages used by the OS virtual memory manager are allocated in
8885 // correct sequence.
8886 SDValue
8887 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8888                                            SelectionDAG &DAG) const {
8889   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8890           getTargetMachine().Options.EnableSegmentedStacks) &&
8891          "This should be used only on Windows targets or when segmented stacks "
8892          "are being used");
8893   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8894   DebugLoc dl = Op.getDebugLoc();
8895
8896   // Get the inputs.
8897   SDValue Chain = Op.getOperand(0);
8898   SDValue Size  = Op.getOperand(1);
8899   // FIXME: Ensure alignment here
8900
8901   bool Is64Bit = Subtarget->is64Bit();
8902   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8903
8904   if (getTargetMachine().Options.EnableSegmentedStacks) {
8905     MachineFunction &MF = DAG.getMachineFunction();
8906     MachineRegisterInfo &MRI = MF.getRegInfo();
8907
8908     if (Is64Bit) {
8909       // The 64 bit implementation of segmented stacks needs to clobber both r10
8910       // r11. This makes it impossible to use it along with nested parameters.
8911       const Function *F = MF.getFunction();
8912
8913       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8914            I != E; I++)
8915         if (I->hasNestAttr())
8916           report_fatal_error("Cannot use segmented stacks with functions that "
8917                              "have nested arguments.");
8918     }
8919
8920     const TargetRegisterClass *AddrRegClass =
8921       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8922     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8923     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8924     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8925                                 DAG.getRegister(Vreg, SPTy));
8926     SDValue Ops1[2] = { Value, Chain };
8927     return DAG.getMergeValues(Ops1, 2, dl);
8928   } else {
8929     SDValue Flag;
8930     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8931
8932     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8933     Flag = Chain.getValue(1);
8934     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8935
8936     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8937     Flag = Chain.getValue(1);
8938
8939     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8940
8941     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8942     return DAG.getMergeValues(Ops1, 2, dl);
8943   }
8944 }
8945
8946 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8947   MachineFunction &MF = DAG.getMachineFunction();
8948   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8949
8950   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8951   DebugLoc DL = Op.getDebugLoc();
8952
8953   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8954     // vastart just stores the address of the VarArgsFrameIndex slot into the
8955     // memory location argument.
8956     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8957                                    getPointerTy());
8958     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8959                         MachinePointerInfo(SV), false, false, 0);
8960   }
8961
8962   // __va_list_tag:
8963   //   gp_offset         (0 - 6 * 8)
8964   //   fp_offset         (48 - 48 + 8 * 16)
8965   //   overflow_arg_area (point to parameters coming in memory).
8966   //   reg_save_area
8967   SmallVector<SDValue, 8> MemOps;
8968   SDValue FIN = Op.getOperand(1);
8969   // Store gp_offset
8970   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8971                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8972                                                MVT::i32),
8973                                FIN, MachinePointerInfo(SV), false, false, 0);
8974   MemOps.push_back(Store);
8975
8976   // Store fp_offset
8977   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8978                     FIN, DAG.getIntPtrConstant(4));
8979   Store = DAG.getStore(Op.getOperand(0), DL,
8980                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8981                                        MVT::i32),
8982                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8983   MemOps.push_back(Store);
8984
8985   // Store ptr to overflow_arg_area
8986   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8987                     FIN, DAG.getIntPtrConstant(4));
8988   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8989                                     getPointerTy());
8990   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8991                        MachinePointerInfo(SV, 8),
8992                        false, false, 0);
8993   MemOps.push_back(Store);
8994
8995   // Store ptr to reg_save_area.
8996   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8997                     FIN, DAG.getIntPtrConstant(8));
8998   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8999                                     getPointerTy());
9000   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9001                        MachinePointerInfo(SV, 16), false, false, 0);
9002   MemOps.push_back(Store);
9003   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9004                      &MemOps[0], MemOps.size());
9005 }
9006
9007 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9008   assert(Subtarget->is64Bit() &&
9009          "LowerVAARG only handles 64-bit va_arg!");
9010   assert((Subtarget->isTargetLinux() ||
9011           Subtarget->isTargetDarwin()) &&
9012           "Unhandled target in LowerVAARG");
9013   assert(Op.getNode()->getNumOperands() == 4);
9014   SDValue Chain = Op.getOperand(0);
9015   SDValue SrcPtr = Op.getOperand(1);
9016   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9017   unsigned Align = Op.getConstantOperandVal(3);
9018   DebugLoc dl = Op.getDebugLoc();
9019
9020   EVT ArgVT = Op.getNode()->getValueType(0);
9021   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9022   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9023   uint8_t ArgMode;
9024
9025   // Decide which area this value should be read from.
9026   // TODO: Implement the AMD64 ABI in its entirety. This simple
9027   // selection mechanism works only for the basic types.
9028   if (ArgVT == MVT::f80) {
9029     llvm_unreachable("va_arg for f80 not yet implemented");
9030   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9031     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9032   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9033     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9034   } else {
9035     llvm_unreachable("Unhandled argument type in LowerVAARG");
9036   }
9037
9038   if (ArgMode == 2) {
9039     // Sanity Check: Make sure using fp_offset makes sense.
9040     assert(!getTargetMachine().Options.UseSoftFloat &&
9041            !(DAG.getMachineFunction()
9042                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9043            Subtarget->hasSSE1());
9044   }
9045
9046   // Insert VAARG_64 node into the DAG
9047   // VAARG_64 returns two values: Variable Argument Address, Chain
9048   SmallVector<SDValue, 11> InstOps;
9049   InstOps.push_back(Chain);
9050   InstOps.push_back(SrcPtr);
9051   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9052   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9053   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9054   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9055   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9056                                           VTs, &InstOps[0], InstOps.size(),
9057                                           MVT::i64,
9058                                           MachinePointerInfo(SV),
9059                                           /*Align=*/0,
9060                                           /*Volatile=*/false,
9061                                           /*ReadMem=*/true,
9062                                           /*WriteMem=*/true);
9063   Chain = VAARG.getValue(1);
9064
9065   // Load the next argument and return it
9066   return DAG.getLoad(ArgVT, dl,
9067                      Chain,
9068                      VAARG,
9069                      MachinePointerInfo(),
9070                      false, false, false, 0);
9071 }
9072
9073 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9074   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9075   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9076   SDValue Chain = Op.getOperand(0);
9077   SDValue DstPtr = Op.getOperand(1);
9078   SDValue SrcPtr = Op.getOperand(2);
9079   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9080   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9081   DebugLoc DL = Op.getDebugLoc();
9082
9083   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9084                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9085                        false,
9086                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9087 }
9088
9089 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9090 // may or may not be a constant. Takes immediate version of shift as input.
9091 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9092                                    SDValue SrcOp, SDValue ShAmt,
9093                                    SelectionDAG &DAG) {
9094   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9095
9096   if (isa<ConstantSDNode>(ShAmt)) {
9097     switch (Opc) {
9098       default: llvm_unreachable("Unknown target vector shift node");
9099       case X86ISD::VSHLI:
9100       case X86ISD::VSRLI:
9101       case X86ISD::VSRAI:
9102         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9103     }
9104   }
9105
9106   // Change opcode to non-immediate version
9107   switch (Opc) {
9108     default: llvm_unreachable("Unknown target vector shift node");
9109     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9110     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9111     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9112   }
9113
9114   // Need to build a vector containing shift amount
9115   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9116   SDValue ShOps[4];
9117   ShOps[0] = ShAmt;
9118   ShOps[1] = DAG.getConstant(0, MVT::i32);
9119   ShOps[2] = DAG.getUNDEF(MVT::i32);
9120   ShOps[3] = DAG.getUNDEF(MVT::i32);
9121   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9122   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9123   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9124 }
9125
9126 SDValue
9127 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9128   DebugLoc dl = Op.getDebugLoc();
9129   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9130   switch (IntNo) {
9131   default: return SDValue();    // Don't custom lower most intrinsics.
9132   // Comparison intrinsics.
9133   case Intrinsic::x86_sse_comieq_ss:
9134   case Intrinsic::x86_sse_comilt_ss:
9135   case Intrinsic::x86_sse_comile_ss:
9136   case Intrinsic::x86_sse_comigt_ss:
9137   case Intrinsic::x86_sse_comige_ss:
9138   case Intrinsic::x86_sse_comineq_ss:
9139   case Intrinsic::x86_sse_ucomieq_ss:
9140   case Intrinsic::x86_sse_ucomilt_ss:
9141   case Intrinsic::x86_sse_ucomile_ss:
9142   case Intrinsic::x86_sse_ucomigt_ss:
9143   case Intrinsic::x86_sse_ucomige_ss:
9144   case Intrinsic::x86_sse_ucomineq_ss:
9145   case Intrinsic::x86_sse2_comieq_sd:
9146   case Intrinsic::x86_sse2_comilt_sd:
9147   case Intrinsic::x86_sse2_comile_sd:
9148   case Intrinsic::x86_sse2_comigt_sd:
9149   case Intrinsic::x86_sse2_comige_sd:
9150   case Intrinsic::x86_sse2_comineq_sd:
9151   case Intrinsic::x86_sse2_ucomieq_sd:
9152   case Intrinsic::x86_sse2_ucomilt_sd:
9153   case Intrinsic::x86_sse2_ucomile_sd:
9154   case Intrinsic::x86_sse2_ucomigt_sd:
9155   case Intrinsic::x86_sse2_ucomige_sd:
9156   case Intrinsic::x86_sse2_ucomineq_sd: {
9157     unsigned Opc = 0;
9158     ISD::CondCode CC = ISD::SETCC_INVALID;
9159     switch (IntNo) {
9160     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9161     case Intrinsic::x86_sse_comieq_ss:
9162     case Intrinsic::x86_sse2_comieq_sd:
9163       Opc = X86ISD::COMI;
9164       CC = ISD::SETEQ;
9165       break;
9166     case Intrinsic::x86_sse_comilt_ss:
9167     case Intrinsic::x86_sse2_comilt_sd:
9168       Opc = X86ISD::COMI;
9169       CC = ISD::SETLT;
9170       break;
9171     case Intrinsic::x86_sse_comile_ss:
9172     case Intrinsic::x86_sse2_comile_sd:
9173       Opc = X86ISD::COMI;
9174       CC = ISD::SETLE;
9175       break;
9176     case Intrinsic::x86_sse_comigt_ss:
9177     case Intrinsic::x86_sse2_comigt_sd:
9178       Opc = X86ISD::COMI;
9179       CC = ISD::SETGT;
9180       break;
9181     case Intrinsic::x86_sse_comige_ss:
9182     case Intrinsic::x86_sse2_comige_sd:
9183       Opc = X86ISD::COMI;
9184       CC = ISD::SETGE;
9185       break;
9186     case Intrinsic::x86_sse_comineq_ss:
9187     case Intrinsic::x86_sse2_comineq_sd:
9188       Opc = X86ISD::COMI;
9189       CC = ISD::SETNE;
9190       break;
9191     case Intrinsic::x86_sse_ucomieq_ss:
9192     case Intrinsic::x86_sse2_ucomieq_sd:
9193       Opc = X86ISD::UCOMI;
9194       CC = ISD::SETEQ;
9195       break;
9196     case Intrinsic::x86_sse_ucomilt_ss:
9197     case Intrinsic::x86_sse2_ucomilt_sd:
9198       Opc = X86ISD::UCOMI;
9199       CC = ISD::SETLT;
9200       break;
9201     case Intrinsic::x86_sse_ucomile_ss:
9202     case Intrinsic::x86_sse2_ucomile_sd:
9203       Opc = X86ISD::UCOMI;
9204       CC = ISD::SETLE;
9205       break;
9206     case Intrinsic::x86_sse_ucomigt_ss:
9207     case Intrinsic::x86_sse2_ucomigt_sd:
9208       Opc = X86ISD::UCOMI;
9209       CC = ISD::SETGT;
9210       break;
9211     case Intrinsic::x86_sse_ucomige_ss:
9212     case Intrinsic::x86_sse2_ucomige_sd:
9213       Opc = X86ISD::UCOMI;
9214       CC = ISD::SETGE;
9215       break;
9216     case Intrinsic::x86_sse_ucomineq_ss:
9217     case Intrinsic::x86_sse2_ucomineq_sd:
9218       Opc = X86ISD::UCOMI;
9219       CC = ISD::SETNE;
9220       break;
9221     }
9222
9223     SDValue LHS = Op.getOperand(1);
9224     SDValue RHS = Op.getOperand(2);
9225     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9226     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9227     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9228     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9229                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9230     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9231   }
9232   // XOP comparison intrinsics
9233   case Intrinsic::x86_xop_vpcomltb:
9234   case Intrinsic::x86_xop_vpcomltw:
9235   case Intrinsic::x86_xop_vpcomltd:
9236   case Intrinsic::x86_xop_vpcomltq:
9237   case Intrinsic::x86_xop_vpcomltub:
9238   case Intrinsic::x86_xop_vpcomltuw:
9239   case Intrinsic::x86_xop_vpcomltud:
9240   case Intrinsic::x86_xop_vpcomltuq:
9241   case Intrinsic::x86_xop_vpcomleb:
9242   case Intrinsic::x86_xop_vpcomlew:
9243   case Intrinsic::x86_xop_vpcomled:
9244   case Intrinsic::x86_xop_vpcomleq:
9245   case Intrinsic::x86_xop_vpcomleub:
9246   case Intrinsic::x86_xop_vpcomleuw:
9247   case Intrinsic::x86_xop_vpcomleud:
9248   case Intrinsic::x86_xop_vpcomleuq:
9249   case Intrinsic::x86_xop_vpcomgtb:
9250   case Intrinsic::x86_xop_vpcomgtw:
9251   case Intrinsic::x86_xop_vpcomgtd:
9252   case Intrinsic::x86_xop_vpcomgtq:
9253   case Intrinsic::x86_xop_vpcomgtub:
9254   case Intrinsic::x86_xop_vpcomgtuw:
9255   case Intrinsic::x86_xop_vpcomgtud:
9256   case Intrinsic::x86_xop_vpcomgtuq:
9257   case Intrinsic::x86_xop_vpcomgeb:
9258   case Intrinsic::x86_xop_vpcomgew:
9259   case Intrinsic::x86_xop_vpcomged:
9260   case Intrinsic::x86_xop_vpcomgeq:
9261   case Intrinsic::x86_xop_vpcomgeub:
9262   case Intrinsic::x86_xop_vpcomgeuw:
9263   case Intrinsic::x86_xop_vpcomgeud:
9264   case Intrinsic::x86_xop_vpcomgeuq:
9265   case Intrinsic::x86_xop_vpcomeqb:
9266   case Intrinsic::x86_xop_vpcomeqw:
9267   case Intrinsic::x86_xop_vpcomeqd:
9268   case Intrinsic::x86_xop_vpcomeqq:
9269   case Intrinsic::x86_xop_vpcomequb:
9270   case Intrinsic::x86_xop_vpcomequw:
9271   case Intrinsic::x86_xop_vpcomequd:
9272   case Intrinsic::x86_xop_vpcomequq:
9273   case Intrinsic::x86_xop_vpcomneb:
9274   case Intrinsic::x86_xop_vpcomnew:
9275   case Intrinsic::x86_xop_vpcomned:
9276   case Intrinsic::x86_xop_vpcomneq:
9277   case Intrinsic::x86_xop_vpcomneub:
9278   case Intrinsic::x86_xop_vpcomneuw:
9279   case Intrinsic::x86_xop_vpcomneud:
9280   case Intrinsic::x86_xop_vpcomneuq:
9281   case Intrinsic::x86_xop_vpcomfalseb:
9282   case Intrinsic::x86_xop_vpcomfalsew:
9283   case Intrinsic::x86_xop_vpcomfalsed:
9284   case Intrinsic::x86_xop_vpcomfalseq:
9285   case Intrinsic::x86_xop_vpcomfalseub:
9286   case Intrinsic::x86_xop_vpcomfalseuw:
9287   case Intrinsic::x86_xop_vpcomfalseud:
9288   case Intrinsic::x86_xop_vpcomfalseuq:
9289   case Intrinsic::x86_xop_vpcomtrueb:
9290   case Intrinsic::x86_xop_vpcomtruew:
9291   case Intrinsic::x86_xop_vpcomtrued:
9292   case Intrinsic::x86_xop_vpcomtrueq:
9293   case Intrinsic::x86_xop_vpcomtrueub:
9294   case Intrinsic::x86_xop_vpcomtrueuw:
9295   case Intrinsic::x86_xop_vpcomtrueud:
9296   case Intrinsic::x86_xop_vpcomtrueuq: {
9297     unsigned CC = 0;
9298     unsigned Opc = 0;
9299
9300     switch (IntNo) {
9301     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9302     case Intrinsic::x86_xop_vpcomltb:
9303     case Intrinsic::x86_xop_vpcomltw:
9304     case Intrinsic::x86_xop_vpcomltd:
9305     case Intrinsic::x86_xop_vpcomltq:
9306       CC = 0;
9307       Opc = X86ISD::VPCOM;
9308       break;
9309     case Intrinsic::x86_xop_vpcomltub:
9310     case Intrinsic::x86_xop_vpcomltuw:
9311     case Intrinsic::x86_xop_vpcomltud:
9312     case Intrinsic::x86_xop_vpcomltuq:
9313       CC = 0;
9314       Opc = X86ISD::VPCOMU;
9315       break;
9316     case Intrinsic::x86_xop_vpcomleb:
9317     case Intrinsic::x86_xop_vpcomlew:
9318     case Intrinsic::x86_xop_vpcomled:
9319     case Intrinsic::x86_xop_vpcomleq:
9320       CC = 1;
9321       Opc = X86ISD::VPCOM;
9322       break;
9323     case Intrinsic::x86_xop_vpcomleub:
9324     case Intrinsic::x86_xop_vpcomleuw:
9325     case Intrinsic::x86_xop_vpcomleud:
9326     case Intrinsic::x86_xop_vpcomleuq:
9327       CC = 1;
9328       Opc = X86ISD::VPCOMU;
9329       break;
9330     case Intrinsic::x86_xop_vpcomgtb:
9331     case Intrinsic::x86_xop_vpcomgtw:
9332     case Intrinsic::x86_xop_vpcomgtd:
9333     case Intrinsic::x86_xop_vpcomgtq:
9334       CC = 2;
9335       Opc = X86ISD::VPCOM;
9336       break;
9337     case Intrinsic::x86_xop_vpcomgtub:
9338     case Intrinsic::x86_xop_vpcomgtuw:
9339     case Intrinsic::x86_xop_vpcomgtud:
9340     case Intrinsic::x86_xop_vpcomgtuq:
9341       CC = 2;
9342       Opc = X86ISD::VPCOMU;
9343       break;
9344     case Intrinsic::x86_xop_vpcomgeb:
9345     case Intrinsic::x86_xop_vpcomgew:
9346     case Intrinsic::x86_xop_vpcomged:
9347     case Intrinsic::x86_xop_vpcomgeq:
9348       CC = 3;
9349       Opc = X86ISD::VPCOM;
9350       break;
9351     case Intrinsic::x86_xop_vpcomgeub:
9352     case Intrinsic::x86_xop_vpcomgeuw:
9353     case Intrinsic::x86_xop_vpcomgeud:
9354     case Intrinsic::x86_xop_vpcomgeuq:
9355       CC = 3;
9356       Opc = X86ISD::VPCOMU;
9357       break;
9358     case Intrinsic::x86_xop_vpcomeqb:
9359     case Intrinsic::x86_xop_vpcomeqw:
9360     case Intrinsic::x86_xop_vpcomeqd:
9361     case Intrinsic::x86_xop_vpcomeqq:
9362       CC = 4;
9363       Opc = X86ISD::VPCOM;
9364       break;
9365     case Intrinsic::x86_xop_vpcomequb:
9366     case Intrinsic::x86_xop_vpcomequw:
9367     case Intrinsic::x86_xop_vpcomequd:
9368     case Intrinsic::x86_xop_vpcomequq:
9369       CC = 4;
9370       Opc = X86ISD::VPCOMU;
9371       break;
9372     case Intrinsic::x86_xop_vpcomneb:
9373     case Intrinsic::x86_xop_vpcomnew:
9374     case Intrinsic::x86_xop_vpcomned:
9375     case Intrinsic::x86_xop_vpcomneq:
9376       CC = 5;
9377       Opc = X86ISD::VPCOM;
9378       break;
9379     case Intrinsic::x86_xop_vpcomneub:
9380     case Intrinsic::x86_xop_vpcomneuw:
9381     case Intrinsic::x86_xop_vpcomneud:
9382     case Intrinsic::x86_xop_vpcomneuq:
9383       CC = 5;
9384       Opc = X86ISD::VPCOMU;
9385       break;
9386     case Intrinsic::x86_xop_vpcomfalseb:
9387     case Intrinsic::x86_xop_vpcomfalsew:
9388     case Intrinsic::x86_xop_vpcomfalsed:
9389     case Intrinsic::x86_xop_vpcomfalseq:
9390       CC = 6;
9391       Opc = X86ISD::VPCOM;
9392       break;
9393     case Intrinsic::x86_xop_vpcomfalseub:
9394     case Intrinsic::x86_xop_vpcomfalseuw:
9395     case Intrinsic::x86_xop_vpcomfalseud:
9396     case Intrinsic::x86_xop_vpcomfalseuq:
9397       CC = 6;
9398       Opc = X86ISD::VPCOMU;
9399       break;
9400     case Intrinsic::x86_xop_vpcomtrueb:
9401     case Intrinsic::x86_xop_vpcomtruew:
9402     case Intrinsic::x86_xop_vpcomtrued:
9403     case Intrinsic::x86_xop_vpcomtrueq:
9404       CC = 7;
9405       Opc = X86ISD::VPCOM;
9406       break;
9407     case Intrinsic::x86_xop_vpcomtrueub:
9408     case Intrinsic::x86_xop_vpcomtrueuw:
9409     case Intrinsic::x86_xop_vpcomtrueud:
9410     case Intrinsic::x86_xop_vpcomtrueuq:
9411       CC = 7;
9412       Opc = X86ISD::VPCOMU;
9413       break;
9414     }
9415
9416     SDValue LHS = Op.getOperand(1);
9417     SDValue RHS = Op.getOperand(2);
9418     return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9419                        DAG.getConstant(CC, MVT::i8));
9420   }
9421
9422   // Arithmetic intrinsics.
9423   case Intrinsic::x86_sse2_pmulu_dq:
9424   case Intrinsic::x86_avx2_pmulu_dq:
9425     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9426                        Op.getOperand(1), Op.getOperand(2));
9427   case Intrinsic::x86_sse3_hadd_ps:
9428   case Intrinsic::x86_sse3_hadd_pd:
9429   case Intrinsic::x86_avx_hadd_ps_256:
9430   case Intrinsic::x86_avx_hadd_pd_256:
9431     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9432                        Op.getOperand(1), Op.getOperand(2));
9433   case Intrinsic::x86_sse3_hsub_ps:
9434   case Intrinsic::x86_sse3_hsub_pd:
9435   case Intrinsic::x86_avx_hsub_ps_256:
9436   case Intrinsic::x86_avx_hsub_pd_256:
9437     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9438                        Op.getOperand(1), Op.getOperand(2));
9439   case Intrinsic::x86_ssse3_phadd_w_128:
9440   case Intrinsic::x86_ssse3_phadd_d_128:
9441   case Intrinsic::x86_avx2_phadd_w:
9442   case Intrinsic::x86_avx2_phadd_d:
9443     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9444                        Op.getOperand(1), Op.getOperand(2));
9445   case Intrinsic::x86_ssse3_phsub_w_128:
9446   case Intrinsic::x86_ssse3_phsub_d_128:
9447   case Intrinsic::x86_avx2_phsub_w:
9448   case Intrinsic::x86_avx2_phsub_d:
9449     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9450                        Op.getOperand(1), Op.getOperand(2));
9451   case Intrinsic::x86_avx2_psllv_d:
9452   case Intrinsic::x86_avx2_psllv_q:
9453   case Intrinsic::x86_avx2_psllv_d_256:
9454   case Intrinsic::x86_avx2_psllv_q_256:
9455     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9456                       Op.getOperand(1), Op.getOperand(2));
9457   case Intrinsic::x86_avx2_psrlv_d:
9458   case Intrinsic::x86_avx2_psrlv_q:
9459   case Intrinsic::x86_avx2_psrlv_d_256:
9460   case Intrinsic::x86_avx2_psrlv_q_256:
9461     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9462                       Op.getOperand(1), Op.getOperand(2));
9463   case Intrinsic::x86_avx2_psrav_d:
9464   case Intrinsic::x86_avx2_psrav_d_256:
9465     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9466                       Op.getOperand(1), Op.getOperand(2));
9467   case Intrinsic::x86_ssse3_pshuf_b_128:
9468   case Intrinsic::x86_avx2_pshuf_b:
9469     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9470                        Op.getOperand(1), Op.getOperand(2));
9471   case Intrinsic::x86_ssse3_psign_b_128:
9472   case Intrinsic::x86_ssse3_psign_w_128:
9473   case Intrinsic::x86_ssse3_psign_d_128:
9474   case Intrinsic::x86_avx2_psign_b:
9475   case Intrinsic::x86_avx2_psign_w:
9476   case Intrinsic::x86_avx2_psign_d:
9477     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9478                        Op.getOperand(1), Op.getOperand(2));
9479   case Intrinsic::x86_sse41_insertps:
9480     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9481                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9482   case Intrinsic::x86_avx_vperm2f128_ps_256:
9483   case Intrinsic::x86_avx_vperm2f128_pd_256:
9484   case Intrinsic::x86_avx_vperm2f128_si_256:
9485   case Intrinsic::x86_avx2_vperm2i128:
9486     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9487                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9488
9489   // ptest and testp intrinsics. The intrinsic these come from are designed to
9490   // return an integer value, not just an instruction so lower it to the ptest
9491   // or testp pattern and a setcc for the result.
9492   case Intrinsic::x86_sse41_ptestz:
9493   case Intrinsic::x86_sse41_ptestc:
9494   case Intrinsic::x86_sse41_ptestnzc:
9495   case Intrinsic::x86_avx_ptestz_256:
9496   case Intrinsic::x86_avx_ptestc_256:
9497   case Intrinsic::x86_avx_ptestnzc_256:
9498   case Intrinsic::x86_avx_vtestz_ps:
9499   case Intrinsic::x86_avx_vtestc_ps:
9500   case Intrinsic::x86_avx_vtestnzc_ps:
9501   case Intrinsic::x86_avx_vtestz_pd:
9502   case Intrinsic::x86_avx_vtestc_pd:
9503   case Intrinsic::x86_avx_vtestnzc_pd:
9504   case Intrinsic::x86_avx_vtestz_ps_256:
9505   case Intrinsic::x86_avx_vtestc_ps_256:
9506   case Intrinsic::x86_avx_vtestnzc_ps_256:
9507   case Intrinsic::x86_avx_vtestz_pd_256:
9508   case Intrinsic::x86_avx_vtestc_pd_256:
9509   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9510     bool IsTestPacked = false;
9511     unsigned X86CC = 0;
9512     switch (IntNo) {
9513     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9514     case Intrinsic::x86_avx_vtestz_ps:
9515     case Intrinsic::x86_avx_vtestz_pd:
9516     case Intrinsic::x86_avx_vtestz_ps_256:
9517     case Intrinsic::x86_avx_vtestz_pd_256:
9518       IsTestPacked = true; // Fallthrough
9519     case Intrinsic::x86_sse41_ptestz:
9520     case Intrinsic::x86_avx_ptestz_256:
9521       // ZF = 1
9522       X86CC = X86::COND_E;
9523       break;
9524     case Intrinsic::x86_avx_vtestc_ps:
9525     case Intrinsic::x86_avx_vtestc_pd:
9526     case Intrinsic::x86_avx_vtestc_ps_256:
9527     case Intrinsic::x86_avx_vtestc_pd_256:
9528       IsTestPacked = true; // Fallthrough
9529     case Intrinsic::x86_sse41_ptestc:
9530     case Intrinsic::x86_avx_ptestc_256:
9531       // CF = 1
9532       X86CC = X86::COND_B;
9533       break;
9534     case Intrinsic::x86_avx_vtestnzc_ps:
9535     case Intrinsic::x86_avx_vtestnzc_pd:
9536     case Intrinsic::x86_avx_vtestnzc_ps_256:
9537     case Intrinsic::x86_avx_vtestnzc_pd_256:
9538       IsTestPacked = true; // Fallthrough
9539     case Intrinsic::x86_sse41_ptestnzc:
9540     case Intrinsic::x86_avx_ptestnzc_256:
9541       // ZF and CF = 0
9542       X86CC = X86::COND_A;
9543       break;
9544     }
9545
9546     SDValue LHS = Op.getOperand(1);
9547     SDValue RHS = Op.getOperand(2);
9548     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9549     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9550     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9551     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9552     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9553   }
9554
9555   // SSE/AVX shift intrinsics
9556   case Intrinsic::x86_sse2_psll_w:
9557   case Intrinsic::x86_sse2_psll_d:
9558   case Intrinsic::x86_sse2_psll_q:
9559   case Intrinsic::x86_avx2_psll_w:
9560   case Intrinsic::x86_avx2_psll_d:
9561   case Intrinsic::x86_avx2_psll_q:
9562     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9563                        Op.getOperand(1), Op.getOperand(2));
9564   case Intrinsic::x86_sse2_psrl_w:
9565   case Intrinsic::x86_sse2_psrl_d:
9566   case Intrinsic::x86_sse2_psrl_q:
9567   case Intrinsic::x86_avx2_psrl_w:
9568   case Intrinsic::x86_avx2_psrl_d:
9569   case Intrinsic::x86_avx2_psrl_q:
9570     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9571                        Op.getOperand(1), Op.getOperand(2));
9572   case Intrinsic::x86_sse2_psra_w:
9573   case Intrinsic::x86_sse2_psra_d:
9574   case Intrinsic::x86_avx2_psra_w:
9575   case Intrinsic::x86_avx2_psra_d:
9576     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9577                        Op.getOperand(1), Op.getOperand(2));
9578   case Intrinsic::x86_sse2_pslli_w:
9579   case Intrinsic::x86_sse2_pslli_d:
9580   case Intrinsic::x86_sse2_pslli_q:
9581   case Intrinsic::x86_avx2_pslli_w:
9582   case Intrinsic::x86_avx2_pslli_d:
9583   case Intrinsic::x86_avx2_pslli_q:
9584     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9585                                Op.getOperand(1), Op.getOperand(2), DAG);
9586   case Intrinsic::x86_sse2_psrli_w:
9587   case Intrinsic::x86_sse2_psrli_d:
9588   case Intrinsic::x86_sse2_psrli_q:
9589   case Intrinsic::x86_avx2_psrli_w:
9590   case Intrinsic::x86_avx2_psrli_d:
9591   case Intrinsic::x86_avx2_psrli_q:
9592     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9593                                Op.getOperand(1), Op.getOperand(2), DAG);
9594   case Intrinsic::x86_sse2_psrai_w:
9595   case Intrinsic::x86_sse2_psrai_d:
9596   case Intrinsic::x86_avx2_psrai_w:
9597   case Intrinsic::x86_avx2_psrai_d:
9598     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9599                                Op.getOperand(1), Op.getOperand(2), DAG);
9600   // Fix vector shift instructions where the last operand is a non-immediate
9601   // i32 value.
9602   case Intrinsic::x86_mmx_pslli_w:
9603   case Intrinsic::x86_mmx_pslli_d:
9604   case Intrinsic::x86_mmx_pslli_q:
9605   case Intrinsic::x86_mmx_psrli_w:
9606   case Intrinsic::x86_mmx_psrli_d:
9607   case Intrinsic::x86_mmx_psrli_q:
9608   case Intrinsic::x86_mmx_psrai_w:
9609   case Intrinsic::x86_mmx_psrai_d: {
9610     SDValue ShAmt = Op.getOperand(2);
9611     if (isa<ConstantSDNode>(ShAmt))
9612       return SDValue();
9613
9614     unsigned NewIntNo = 0;
9615     switch (IntNo) {
9616     case Intrinsic::x86_mmx_pslli_w:
9617       NewIntNo = Intrinsic::x86_mmx_psll_w;
9618       break;
9619     case Intrinsic::x86_mmx_pslli_d:
9620       NewIntNo = Intrinsic::x86_mmx_psll_d;
9621       break;
9622     case Intrinsic::x86_mmx_pslli_q:
9623       NewIntNo = Intrinsic::x86_mmx_psll_q;
9624       break;
9625     case Intrinsic::x86_mmx_psrli_w:
9626       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9627       break;
9628     case Intrinsic::x86_mmx_psrli_d:
9629       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9630       break;
9631     case Intrinsic::x86_mmx_psrli_q:
9632       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9633       break;
9634     case Intrinsic::x86_mmx_psrai_w:
9635       NewIntNo = Intrinsic::x86_mmx_psra_w;
9636       break;
9637     case Intrinsic::x86_mmx_psrai_d:
9638       NewIntNo = Intrinsic::x86_mmx_psra_d;
9639       break;
9640     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9641     }
9642
9643     // The vector shift intrinsics with scalars uses 32b shift amounts but
9644     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9645     // to be zero.
9646     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9647                          DAG.getConstant(0, MVT::i32));
9648 // FIXME this must be lowered to get rid of the invalid type.
9649
9650     EVT VT = Op.getValueType();
9651     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9652     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9653                        DAG.getConstant(NewIntNo, MVT::i32),
9654                        Op.getOperand(1), ShAmt);
9655   }
9656   }
9657 }
9658
9659 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9660                                            SelectionDAG &DAG) const {
9661   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9662   MFI->setReturnAddressIsTaken(true);
9663
9664   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9665   DebugLoc dl = Op.getDebugLoc();
9666
9667   if (Depth > 0) {
9668     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9669     SDValue Offset =
9670       DAG.getConstant(TD->getPointerSize(),
9671                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9672     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9673                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9674                                    FrameAddr, Offset),
9675                        MachinePointerInfo(), false, false, false, 0);
9676   }
9677
9678   // Just load the return address.
9679   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9680   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9681                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9682 }
9683
9684 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9685   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9686   MFI->setFrameAddressIsTaken(true);
9687
9688   EVT VT = Op.getValueType();
9689   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9690   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9691   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9692   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9693   while (Depth--)
9694     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9695                             MachinePointerInfo(),
9696                             false, false, false, 0);
9697   return FrameAddr;
9698 }
9699
9700 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9701                                                      SelectionDAG &DAG) const {
9702   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9703 }
9704
9705 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9706   MachineFunction &MF = DAG.getMachineFunction();
9707   SDValue Chain     = Op.getOperand(0);
9708   SDValue Offset    = Op.getOperand(1);
9709   SDValue Handler   = Op.getOperand(2);
9710   DebugLoc dl       = Op.getDebugLoc();
9711
9712   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9713                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9714                                      getPointerTy());
9715   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9716
9717   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9718                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9719   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9720   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9721                        false, false, 0);
9722   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9723   MF.getRegInfo().addLiveOut(StoreAddrReg);
9724
9725   return DAG.getNode(X86ISD::EH_RETURN, dl,
9726                      MVT::Other,
9727                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9728 }
9729
9730 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9731                                                   SelectionDAG &DAG) const {
9732   return Op.getOperand(0);
9733 }
9734
9735 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9736                                                 SelectionDAG &DAG) const {
9737   SDValue Root = Op.getOperand(0);
9738   SDValue Trmp = Op.getOperand(1); // trampoline
9739   SDValue FPtr = Op.getOperand(2); // nested function
9740   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9741   DebugLoc dl  = Op.getDebugLoc();
9742
9743   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9744
9745   if (Subtarget->is64Bit()) {
9746     SDValue OutChains[6];
9747
9748     // Large code-model.
9749     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9750     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9751
9752     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9753     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9754
9755     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9756
9757     // Load the pointer to the nested function into R11.
9758     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9759     SDValue Addr = Trmp;
9760     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9761                                 Addr, MachinePointerInfo(TrmpAddr),
9762                                 false, false, 0);
9763
9764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9765                        DAG.getConstant(2, MVT::i64));
9766     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9767                                 MachinePointerInfo(TrmpAddr, 2),
9768                                 false, false, 2);
9769
9770     // Load the 'nest' parameter value into R10.
9771     // R10 is specified in X86CallingConv.td
9772     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9774                        DAG.getConstant(10, MVT::i64));
9775     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9776                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9777                                 false, false, 0);
9778
9779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9780                        DAG.getConstant(12, MVT::i64));
9781     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9782                                 MachinePointerInfo(TrmpAddr, 12),
9783                                 false, false, 2);
9784
9785     // Jump to the nested function.
9786     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9787     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9788                        DAG.getConstant(20, MVT::i64));
9789     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9790                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9791                                 false, false, 0);
9792
9793     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9794     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9795                        DAG.getConstant(22, MVT::i64));
9796     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9797                                 MachinePointerInfo(TrmpAddr, 22),
9798                                 false, false, 0);
9799
9800     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9801   } else {
9802     const Function *Func =
9803       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9804     CallingConv::ID CC = Func->getCallingConv();
9805     unsigned NestReg;
9806
9807     switch (CC) {
9808     default:
9809       llvm_unreachable("Unsupported calling convention");
9810     case CallingConv::C:
9811     case CallingConv::X86_StdCall: {
9812       // Pass 'nest' parameter in ECX.
9813       // Must be kept in sync with X86CallingConv.td
9814       NestReg = X86::ECX;
9815
9816       // Check that ECX wasn't needed by an 'inreg' parameter.
9817       FunctionType *FTy = Func->getFunctionType();
9818       const AttrListPtr &Attrs = Func->getAttributes();
9819
9820       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9821         unsigned InRegCount = 0;
9822         unsigned Idx = 1;
9823
9824         for (FunctionType::param_iterator I = FTy->param_begin(),
9825              E = FTy->param_end(); I != E; ++I, ++Idx)
9826           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9827             // FIXME: should only count parameters that are lowered to integers.
9828             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9829
9830         if (InRegCount > 2) {
9831           report_fatal_error("Nest register in use - reduce number of inreg"
9832                              " parameters!");
9833         }
9834       }
9835       break;
9836     }
9837     case CallingConv::X86_FastCall:
9838     case CallingConv::X86_ThisCall:
9839     case CallingConv::Fast:
9840       // Pass 'nest' parameter in EAX.
9841       // Must be kept in sync with X86CallingConv.td
9842       NestReg = X86::EAX;
9843       break;
9844     }
9845
9846     SDValue OutChains[4];
9847     SDValue Addr, Disp;
9848
9849     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9850                        DAG.getConstant(10, MVT::i32));
9851     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9852
9853     // This is storing the opcode for MOV32ri.
9854     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9855     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9856     OutChains[0] = DAG.getStore(Root, dl,
9857                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9858                                 Trmp, MachinePointerInfo(TrmpAddr),
9859                                 false, false, 0);
9860
9861     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9862                        DAG.getConstant(1, MVT::i32));
9863     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9864                                 MachinePointerInfo(TrmpAddr, 1),
9865                                 false, false, 1);
9866
9867     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9868     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9869                        DAG.getConstant(5, MVT::i32));
9870     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9871                                 MachinePointerInfo(TrmpAddr, 5),
9872                                 false, false, 1);
9873
9874     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9875                        DAG.getConstant(6, MVT::i32));
9876     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9877                                 MachinePointerInfo(TrmpAddr, 6),
9878                                 false, false, 1);
9879
9880     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9881   }
9882 }
9883
9884 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9885                                             SelectionDAG &DAG) const {
9886   /*
9887    The rounding mode is in bits 11:10 of FPSR, and has the following
9888    settings:
9889      00 Round to nearest
9890      01 Round to -inf
9891      10 Round to +inf
9892      11 Round to 0
9893
9894   FLT_ROUNDS, on the other hand, expects the following:
9895     -1 Undefined
9896      0 Round to 0
9897      1 Round to nearest
9898      2 Round to +inf
9899      3 Round to -inf
9900
9901   To perform the conversion, we do:
9902     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9903   */
9904
9905   MachineFunction &MF = DAG.getMachineFunction();
9906   const TargetMachine &TM = MF.getTarget();
9907   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9908   unsigned StackAlignment = TFI.getStackAlignment();
9909   EVT VT = Op.getValueType();
9910   DebugLoc DL = Op.getDebugLoc();
9911
9912   // Save FP Control Word to stack slot
9913   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9914   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9915
9916
9917   MachineMemOperand *MMO =
9918    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9919                            MachineMemOperand::MOStore, 2, 2);
9920
9921   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9922   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9923                                           DAG.getVTList(MVT::Other),
9924                                           Ops, 2, MVT::i16, MMO);
9925
9926   // Load FP Control Word from stack slot
9927   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9928                             MachinePointerInfo(), false, false, false, 0);
9929
9930   // Transform as necessary
9931   SDValue CWD1 =
9932     DAG.getNode(ISD::SRL, DL, MVT::i16,
9933                 DAG.getNode(ISD::AND, DL, MVT::i16,
9934                             CWD, DAG.getConstant(0x800, MVT::i16)),
9935                 DAG.getConstant(11, MVT::i8));
9936   SDValue CWD2 =
9937     DAG.getNode(ISD::SRL, DL, MVT::i16,
9938                 DAG.getNode(ISD::AND, DL, MVT::i16,
9939                             CWD, DAG.getConstant(0x400, MVT::i16)),
9940                 DAG.getConstant(9, MVT::i8));
9941
9942   SDValue RetVal =
9943     DAG.getNode(ISD::AND, DL, MVT::i16,
9944                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9945                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9946                             DAG.getConstant(1, MVT::i16)),
9947                 DAG.getConstant(3, MVT::i16));
9948
9949
9950   return DAG.getNode((VT.getSizeInBits() < 16 ?
9951                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9952 }
9953
9954 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9955   EVT VT = Op.getValueType();
9956   EVT OpVT = VT;
9957   unsigned NumBits = VT.getSizeInBits();
9958   DebugLoc dl = Op.getDebugLoc();
9959
9960   Op = Op.getOperand(0);
9961   if (VT == MVT::i8) {
9962     // Zero extend to i32 since there is not an i8 bsr.
9963     OpVT = MVT::i32;
9964     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9965   }
9966
9967   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9968   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9969   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9970
9971   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9972   SDValue Ops[] = {
9973     Op,
9974     DAG.getConstant(NumBits+NumBits-1, OpVT),
9975     DAG.getConstant(X86::COND_E, MVT::i8),
9976     Op.getValue(1)
9977   };
9978   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9979
9980   // Finally xor with NumBits-1.
9981   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9982
9983   if (VT == MVT::i8)
9984     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9985   return Op;
9986 }
9987
9988 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
9989                                                 SelectionDAG &DAG) const {
9990   EVT VT = Op.getValueType();
9991   EVT OpVT = VT;
9992   unsigned NumBits = VT.getSizeInBits();
9993   DebugLoc dl = Op.getDebugLoc();
9994
9995   Op = Op.getOperand(0);
9996   if (VT == MVT::i8) {
9997     // Zero extend to i32 since there is not an i8 bsr.
9998     OpVT = MVT::i32;
9999     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10000   }
10001
10002   // Issue a bsr (scan bits in reverse).
10003   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10004   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10005
10006   // And xor with NumBits-1.
10007   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10008
10009   if (VT == MVT::i8)
10010     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10011   return Op;
10012 }
10013
10014 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10015   EVT VT = Op.getValueType();
10016   unsigned NumBits = VT.getSizeInBits();
10017   DebugLoc dl = Op.getDebugLoc();
10018   Op = Op.getOperand(0);
10019
10020   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10021   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10022   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10023
10024   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10025   SDValue Ops[] = {
10026     Op,
10027     DAG.getConstant(NumBits, VT),
10028     DAG.getConstant(X86::COND_E, MVT::i8),
10029     Op.getValue(1)
10030   };
10031   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10032 }
10033
10034 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10035 // ones, and then concatenate the result back.
10036 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10037   EVT VT = Op.getValueType();
10038
10039   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10040          "Unsupported value type for operation");
10041
10042   int NumElems = VT.getVectorNumElements();
10043   DebugLoc dl = Op.getDebugLoc();
10044   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10045   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10046
10047   // Extract the LHS vectors
10048   SDValue LHS = Op.getOperand(0);
10049   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10050   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10051
10052   // Extract the RHS vectors
10053   SDValue RHS = Op.getOperand(1);
10054   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10055   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10056
10057   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10058   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10059
10060   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10061                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10062                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10063 }
10064
10065 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10066   assert(Op.getValueType().getSizeInBits() == 256 &&
10067          Op.getValueType().isInteger() &&
10068          "Only handle AVX 256-bit vector integer operation");
10069   return Lower256IntArith(Op, DAG);
10070 }
10071
10072 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10073   assert(Op.getValueType().getSizeInBits() == 256 &&
10074          Op.getValueType().isInteger() &&
10075          "Only handle AVX 256-bit vector integer operation");
10076   return Lower256IntArith(Op, DAG);
10077 }
10078
10079 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10080   EVT VT = Op.getValueType();
10081
10082   // Decompose 256-bit ops into smaller 128-bit ops.
10083   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10084     return Lower256IntArith(Op, DAG);
10085
10086   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10087          "Only know how to lower V2I64/V4I64 multiply");
10088
10089   DebugLoc dl = Op.getDebugLoc();
10090
10091   //  Ahi = psrlqi(a, 32);
10092   //  Bhi = psrlqi(b, 32);
10093   //
10094   //  AloBlo = pmuludq(a, b);
10095   //  AloBhi = pmuludq(a, Bhi);
10096   //  AhiBlo = pmuludq(Ahi, b);
10097
10098   //  AloBhi = psllqi(AloBhi, 32);
10099   //  AhiBlo = psllqi(AhiBlo, 32);
10100   //  return AloBlo + AloBhi + AhiBlo;
10101
10102   SDValue A = Op.getOperand(0);
10103   SDValue B = Op.getOperand(1);
10104
10105   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10106
10107   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10108   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10109
10110   // Bit cast to 32-bit vectors for MULUDQ
10111   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10112   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10113   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10114   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10115   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10116
10117   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10118   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10119   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10120
10121   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10122   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10123
10124   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10125   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10126 }
10127
10128 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10129
10130   EVT VT = Op.getValueType();
10131   DebugLoc dl = Op.getDebugLoc();
10132   SDValue R = Op.getOperand(0);
10133   SDValue Amt = Op.getOperand(1);
10134   LLVMContext *Context = DAG.getContext();
10135
10136   if (!Subtarget->hasSSE2())
10137     return SDValue();
10138
10139   // Optimize shl/srl/sra with constant shift amount.
10140   if (isSplatVector(Amt.getNode())) {
10141     SDValue SclrAmt = Amt->getOperand(0);
10142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10143       uint64_t ShiftAmt = C->getZExtValue();
10144
10145       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10146           (Subtarget->hasAVX2() &&
10147            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10148         if (Op.getOpcode() == ISD::SHL)
10149           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10150                              DAG.getConstant(ShiftAmt, MVT::i32));
10151         if (Op.getOpcode() == ISD::SRL)
10152           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10153                              DAG.getConstant(ShiftAmt, MVT::i32));
10154         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10155           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10156                              DAG.getConstant(ShiftAmt, MVT::i32));
10157       }
10158
10159       if (VT == MVT::v16i8) {
10160         if (Op.getOpcode() == ISD::SHL) {
10161           // Make a large shift.
10162           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10163                                     DAG.getConstant(ShiftAmt, MVT::i32));
10164           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10165           // Zero out the rightmost bits.
10166           SmallVector<SDValue, 16> V(16,
10167                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10168                                                      MVT::i8));
10169           return DAG.getNode(ISD::AND, dl, VT, SHL,
10170                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10171         }
10172         if (Op.getOpcode() == ISD::SRL) {
10173           // Make a large shift.
10174           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10175                                     DAG.getConstant(ShiftAmt, MVT::i32));
10176           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10177           // Zero out the leftmost bits.
10178           SmallVector<SDValue, 16> V(16,
10179                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10180                                                      MVT::i8));
10181           return DAG.getNode(ISD::AND, dl, VT, SRL,
10182                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10183         }
10184         if (Op.getOpcode() == ISD::SRA) {
10185           if (ShiftAmt == 7) {
10186             // R s>> 7  ===  R s< 0
10187             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10188             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10189           }
10190
10191           // R s>> a === ((R u>> a) ^ m) - m
10192           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10193           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10194                                                          MVT::i8));
10195           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10196           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10197           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10198           return Res;
10199         }
10200       }
10201
10202       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10203         if (Op.getOpcode() == ISD::SHL) {
10204           // Make a large shift.
10205           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10206                                     DAG.getConstant(ShiftAmt, MVT::i32));
10207           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10208           // Zero out the rightmost bits.
10209           SmallVector<SDValue, 32> V(32,
10210                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10211                                                      MVT::i8));
10212           return DAG.getNode(ISD::AND, dl, VT, SHL,
10213                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10214         }
10215         if (Op.getOpcode() == ISD::SRL) {
10216           // Make a large shift.
10217           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10218                                     DAG.getConstant(ShiftAmt, MVT::i32));
10219           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10220           // Zero out the leftmost bits.
10221           SmallVector<SDValue, 32> V(32,
10222                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10223                                                      MVT::i8));
10224           return DAG.getNode(ISD::AND, dl, VT, SRL,
10225                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10226         }
10227         if (Op.getOpcode() == ISD::SRA) {
10228           if (ShiftAmt == 7) {
10229             // R s>> 7  ===  R s< 0
10230             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10231             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10232           }
10233
10234           // R s>> a === ((R u>> a) ^ m) - m
10235           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10236           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10237                                                          MVT::i8));
10238           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10239           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10240           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10241           return Res;
10242         }
10243       }
10244     }
10245   }
10246
10247   // Lower SHL with variable shift amount.
10248   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10249     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10250                      DAG.getConstant(23, MVT::i32));
10251
10252     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10253     Constant *C = ConstantVector::getSplat(4, CI);
10254     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10255     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10256                                  MachinePointerInfo::getConstantPool(),
10257                                  false, false, false, 16);
10258
10259     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10260     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10261     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10262     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10263   }
10264   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10265     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10266
10267     // a = a << 5;
10268     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10269                      DAG.getConstant(5, MVT::i32));
10270     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10271
10272     // Turn 'a' into a mask suitable for VSELECT
10273     SDValue VSelM = DAG.getConstant(0x80, VT);
10274     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10275     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10276
10277     SDValue CM1 = DAG.getConstant(0x0f, VT);
10278     SDValue CM2 = DAG.getConstant(0x3f, VT);
10279
10280     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10281     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10282     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10283                             DAG.getConstant(4, MVT::i32), DAG);
10284     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10285     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10286
10287     // a += a
10288     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10289     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10290     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10291
10292     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10293     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10294     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10295                             DAG.getConstant(2, MVT::i32), DAG);
10296     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10297     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10298
10299     // a += a
10300     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10301     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10302     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10303
10304     // return VSELECT(r, r+r, a);
10305     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10306                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10307     return R;
10308   }
10309
10310   // Decompose 256-bit shifts into smaller 128-bit shifts.
10311   if (VT.getSizeInBits() == 256) {
10312     unsigned NumElems = VT.getVectorNumElements();
10313     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10314     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10315
10316     // Extract the two vectors
10317     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10318     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10319                                      DAG, dl);
10320
10321     // Recreate the shift amount vectors
10322     SDValue Amt1, Amt2;
10323     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10324       // Constant shift amount
10325       SmallVector<SDValue, 4> Amt1Csts;
10326       SmallVector<SDValue, 4> Amt2Csts;
10327       for (unsigned i = 0; i != NumElems/2; ++i)
10328         Amt1Csts.push_back(Amt->getOperand(i));
10329       for (unsigned i = NumElems/2; i != NumElems; ++i)
10330         Amt2Csts.push_back(Amt->getOperand(i));
10331
10332       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10333                                  &Amt1Csts[0], NumElems/2);
10334       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10335                                  &Amt2Csts[0], NumElems/2);
10336     } else {
10337       // Variable shift amount
10338       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10339       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10340                                  DAG, dl);
10341     }
10342
10343     // Issue new vector shifts for the smaller types
10344     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10345     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10346
10347     // Concatenate the result back
10348     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10349   }
10350
10351   return SDValue();
10352 }
10353
10354 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10355   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10356   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10357   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10358   // has only one use.
10359   SDNode *N = Op.getNode();
10360   SDValue LHS = N->getOperand(0);
10361   SDValue RHS = N->getOperand(1);
10362   unsigned BaseOp = 0;
10363   unsigned Cond = 0;
10364   DebugLoc DL = Op.getDebugLoc();
10365   switch (Op.getOpcode()) {
10366   default: llvm_unreachable("Unknown ovf instruction!");
10367   case ISD::SADDO:
10368     // A subtract of one will be selected as a INC. Note that INC doesn't
10369     // set CF, so we can't do this for UADDO.
10370     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10371       if (C->isOne()) {
10372         BaseOp = X86ISD::INC;
10373         Cond = X86::COND_O;
10374         break;
10375       }
10376     BaseOp = X86ISD::ADD;
10377     Cond = X86::COND_O;
10378     break;
10379   case ISD::UADDO:
10380     BaseOp = X86ISD::ADD;
10381     Cond = X86::COND_B;
10382     break;
10383   case ISD::SSUBO:
10384     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10385     // set CF, so we can't do this for USUBO.
10386     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10387       if (C->isOne()) {
10388         BaseOp = X86ISD::DEC;
10389         Cond = X86::COND_O;
10390         break;
10391       }
10392     BaseOp = X86ISD::SUB;
10393     Cond = X86::COND_O;
10394     break;
10395   case ISD::USUBO:
10396     BaseOp = X86ISD::SUB;
10397     Cond = X86::COND_B;
10398     break;
10399   case ISD::SMULO:
10400     BaseOp = X86ISD::SMUL;
10401     Cond = X86::COND_O;
10402     break;
10403   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10404     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10405                                  MVT::i32);
10406     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10407
10408     SDValue SetCC =
10409       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10410                   DAG.getConstant(X86::COND_O, MVT::i32),
10411                   SDValue(Sum.getNode(), 2));
10412
10413     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10414   }
10415   }
10416
10417   // Also sets EFLAGS.
10418   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10419   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10420
10421   SDValue SetCC =
10422     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10423                 DAG.getConstant(Cond, MVT::i32),
10424                 SDValue(Sum.getNode(), 1));
10425
10426   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10427 }
10428
10429 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10430                                                   SelectionDAG &DAG) const {
10431   DebugLoc dl = Op.getDebugLoc();
10432   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10433   EVT VT = Op.getValueType();
10434
10435   if (!Subtarget->hasSSE2() || !VT.isVector())
10436     return SDValue();
10437
10438   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10439                       ExtraVT.getScalarType().getSizeInBits();
10440   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10441
10442   switch (VT.getSimpleVT().SimpleTy) {
10443     default: return SDValue();
10444     case MVT::v8i32:
10445     case MVT::v16i16:
10446       if (!Subtarget->hasAVX())
10447         return SDValue();
10448       if (!Subtarget->hasAVX2()) {
10449         // needs to be split
10450         int NumElems = VT.getVectorNumElements();
10451         SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10452         SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10453
10454         // Extract the LHS vectors
10455         SDValue LHS = Op.getOperand(0);
10456         SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10457         SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10458
10459         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10460         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10461
10462         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10463         int ExtraNumElems = ExtraVT.getVectorNumElements();
10464         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10465                                    ExtraNumElems/2);
10466         SDValue Extra = DAG.getValueType(ExtraVT);
10467
10468         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10469         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10470
10471         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10472       }
10473       // fall through
10474     case MVT::v4i32:
10475     case MVT::v8i16: {
10476       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10477                                          Op.getOperand(0), ShAmt, DAG);
10478       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10479     }
10480   }
10481 }
10482
10483
10484 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10485   DebugLoc dl = Op.getDebugLoc();
10486
10487   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10488   // There isn't any reason to disable it if the target processor supports it.
10489   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10490     SDValue Chain = Op.getOperand(0);
10491     SDValue Zero = DAG.getConstant(0, MVT::i32);
10492     SDValue Ops[] = {
10493       DAG.getRegister(X86::ESP, MVT::i32), // Base
10494       DAG.getTargetConstant(1, MVT::i8),   // Scale
10495       DAG.getRegister(0, MVT::i32),        // Index
10496       DAG.getTargetConstant(0, MVT::i32),  // Disp
10497       DAG.getRegister(0, MVT::i32),        // Segment.
10498       Zero,
10499       Chain
10500     };
10501     SDNode *Res =
10502       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10503                           array_lengthof(Ops));
10504     return SDValue(Res, 0);
10505   }
10506
10507   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10508   if (!isDev)
10509     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10510
10511   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10512   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10513   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10514   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10515
10516   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10517   if (!Op1 && !Op2 && !Op3 && Op4)
10518     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10519
10520   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10521   if (Op1 && !Op2 && !Op3 && !Op4)
10522     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10523
10524   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10525   //           (MFENCE)>;
10526   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10527 }
10528
10529 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10530                                              SelectionDAG &DAG) const {
10531   DebugLoc dl = Op.getDebugLoc();
10532   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10533     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10534   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10535     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10536
10537   // The only fence that needs an instruction is a sequentially-consistent
10538   // cross-thread fence.
10539   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10540     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10541     // no-sse2). There isn't any reason to disable it if the target processor
10542     // supports it.
10543     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10544       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10545
10546     SDValue Chain = Op.getOperand(0);
10547     SDValue Zero = DAG.getConstant(0, MVT::i32);
10548     SDValue Ops[] = {
10549       DAG.getRegister(X86::ESP, MVT::i32), // Base
10550       DAG.getTargetConstant(1, MVT::i8),   // Scale
10551       DAG.getRegister(0, MVT::i32),        // Index
10552       DAG.getTargetConstant(0, MVT::i32),  // Disp
10553       DAG.getRegister(0, MVT::i32),        // Segment.
10554       Zero,
10555       Chain
10556     };
10557     SDNode *Res =
10558       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10559                          array_lengthof(Ops));
10560     return SDValue(Res, 0);
10561   }
10562
10563   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10564   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10565 }
10566
10567
10568 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10569   EVT T = Op.getValueType();
10570   DebugLoc DL = Op.getDebugLoc();
10571   unsigned Reg = 0;
10572   unsigned size = 0;
10573   switch(T.getSimpleVT().SimpleTy) {
10574   default: llvm_unreachable("Invalid value type!");
10575   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10576   case MVT::i16: Reg = X86::AX;  size = 2; break;
10577   case MVT::i32: Reg = X86::EAX; size = 4; break;
10578   case MVT::i64:
10579     assert(Subtarget->is64Bit() && "Node not type legal!");
10580     Reg = X86::RAX; size = 8;
10581     break;
10582   }
10583   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10584                                     Op.getOperand(2), SDValue());
10585   SDValue Ops[] = { cpIn.getValue(0),
10586                     Op.getOperand(1),
10587                     Op.getOperand(3),
10588                     DAG.getTargetConstant(size, MVT::i8),
10589                     cpIn.getValue(1) };
10590   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10591   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10592   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10593                                            Ops, 5, T, MMO);
10594   SDValue cpOut =
10595     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10596   return cpOut;
10597 }
10598
10599 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10600                                                  SelectionDAG &DAG) const {
10601   assert(Subtarget->is64Bit() && "Result not type legalized?");
10602   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10603   SDValue TheChain = Op.getOperand(0);
10604   DebugLoc dl = Op.getDebugLoc();
10605   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10606   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10607   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10608                                    rax.getValue(2));
10609   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10610                             DAG.getConstant(32, MVT::i8));
10611   SDValue Ops[] = {
10612     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10613     rdx.getValue(1)
10614   };
10615   return DAG.getMergeValues(Ops, 2, dl);
10616 }
10617
10618 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10619                                             SelectionDAG &DAG) const {
10620   EVT SrcVT = Op.getOperand(0).getValueType();
10621   EVT DstVT = Op.getValueType();
10622   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10623          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10624   assert((DstVT == MVT::i64 ||
10625           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10626          "Unexpected custom BITCAST");
10627   // i64 <=> MMX conversions are Legal.
10628   if (SrcVT==MVT::i64 && DstVT.isVector())
10629     return Op;
10630   if (DstVT==MVT::i64 && SrcVT.isVector())
10631     return Op;
10632   // MMX <=> MMX conversions are Legal.
10633   if (SrcVT.isVector() && DstVT.isVector())
10634     return Op;
10635   // All other conversions need to be expanded.
10636   return SDValue();
10637 }
10638
10639 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10640   SDNode *Node = Op.getNode();
10641   DebugLoc dl = Node->getDebugLoc();
10642   EVT T = Node->getValueType(0);
10643   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10644                               DAG.getConstant(0, T), Node->getOperand(2));
10645   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10646                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10647                        Node->getOperand(0),
10648                        Node->getOperand(1), negOp,
10649                        cast<AtomicSDNode>(Node)->getSrcValue(),
10650                        cast<AtomicSDNode>(Node)->getAlignment(),
10651                        cast<AtomicSDNode>(Node)->getOrdering(),
10652                        cast<AtomicSDNode>(Node)->getSynchScope());
10653 }
10654
10655 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10656   SDNode *Node = Op.getNode();
10657   DebugLoc dl = Node->getDebugLoc();
10658   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10659
10660   // Convert seq_cst store -> xchg
10661   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10662   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10663   //        (The only way to get a 16-byte store is cmpxchg16b)
10664   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10665   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10666       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10667     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10668                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10669                                  Node->getOperand(0),
10670                                  Node->getOperand(1), Node->getOperand(2),
10671                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10672                                  cast<AtomicSDNode>(Node)->getOrdering(),
10673                                  cast<AtomicSDNode>(Node)->getSynchScope());
10674     return Swap.getValue(1);
10675   }
10676   // Other atomic stores have a simple pattern.
10677   return Op;
10678 }
10679
10680 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10681   EVT VT = Op.getNode()->getValueType(0);
10682
10683   // Let legalize expand this if it isn't a legal type yet.
10684   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10685     return SDValue();
10686
10687   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10688
10689   unsigned Opc;
10690   bool ExtraOp = false;
10691   switch (Op.getOpcode()) {
10692   default: llvm_unreachable("Invalid code");
10693   case ISD::ADDC: Opc = X86ISD::ADD; break;
10694   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10695   case ISD::SUBC: Opc = X86ISD::SUB; break;
10696   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10697   }
10698
10699   if (!ExtraOp)
10700     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10701                        Op.getOperand(1));
10702   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10703                      Op.getOperand(1), Op.getOperand(2));
10704 }
10705
10706 /// LowerOperation - Provide custom lowering hooks for some operations.
10707 ///
10708 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10709   switch (Op.getOpcode()) {
10710   default: llvm_unreachable("Should not custom lower this!");
10711   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10712   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10713   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10714   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10715   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10716   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10717   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10718   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10719   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10720   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10721   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10722   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10723   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10724   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10725   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10726   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10727   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10728   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10729   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10730   case ISD::SHL_PARTS:
10731   case ISD::SRA_PARTS:
10732   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10733   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10734   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10735   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10736   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10737   case ISD::FABS:               return LowerFABS(Op, DAG);
10738   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10739   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10740   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10741   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10742   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10743   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10744   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10745   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10746   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10747   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10748   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10749   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10750   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10751   case ISD::FRAME_TO_ARGS_OFFSET:
10752                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10753   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10754   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10755   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10756   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10757   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10758   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10759   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10760   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10761   case ISD::MUL:                return LowerMUL(Op, DAG);
10762   case ISD::SRA:
10763   case ISD::SRL:
10764   case ISD::SHL:                return LowerShift(Op, DAG);
10765   case ISD::SADDO:
10766   case ISD::UADDO:
10767   case ISD::SSUBO:
10768   case ISD::USUBO:
10769   case ISD::SMULO:
10770   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10771   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10772   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10773   case ISD::ADDC:
10774   case ISD::ADDE:
10775   case ISD::SUBC:
10776   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10777   case ISD::ADD:                return LowerADD(Op, DAG);
10778   case ISD::SUB:                return LowerSUB(Op, DAG);
10779   }
10780 }
10781
10782 static void ReplaceATOMIC_LOAD(SDNode *Node,
10783                                   SmallVectorImpl<SDValue> &Results,
10784                                   SelectionDAG &DAG) {
10785   DebugLoc dl = Node->getDebugLoc();
10786   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10787
10788   // Convert wide load -> cmpxchg8b/cmpxchg16b
10789   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10790   //        (The only way to get a 16-byte load is cmpxchg16b)
10791   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10792   SDValue Zero = DAG.getConstant(0, VT);
10793   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10794                                Node->getOperand(0),
10795                                Node->getOperand(1), Zero, Zero,
10796                                cast<AtomicSDNode>(Node)->getMemOperand(),
10797                                cast<AtomicSDNode>(Node)->getOrdering(),
10798                                cast<AtomicSDNode>(Node)->getSynchScope());
10799   Results.push_back(Swap.getValue(0));
10800   Results.push_back(Swap.getValue(1));
10801 }
10802
10803 void X86TargetLowering::
10804 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10805                         SelectionDAG &DAG, unsigned NewOp) const {
10806   DebugLoc dl = Node->getDebugLoc();
10807   assert (Node->getValueType(0) == MVT::i64 &&
10808           "Only know how to expand i64 atomics");
10809
10810   SDValue Chain = Node->getOperand(0);
10811   SDValue In1 = Node->getOperand(1);
10812   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10813                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10814   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10815                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10816   SDValue Ops[] = { Chain, In1, In2L, In2H };
10817   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10818   SDValue Result =
10819     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10820                             cast<MemSDNode>(Node)->getMemOperand());
10821   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10822   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10823   Results.push_back(Result.getValue(2));
10824 }
10825
10826 /// ReplaceNodeResults - Replace a node with an illegal result type
10827 /// with a new node built out of custom code.
10828 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10829                                            SmallVectorImpl<SDValue>&Results,
10830                                            SelectionDAG &DAG) const {
10831   DebugLoc dl = N->getDebugLoc();
10832   switch (N->getOpcode()) {
10833   default:
10834     llvm_unreachable("Do not know how to custom type legalize this operation!");
10835   case ISD::SIGN_EXTEND_INREG:
10836   case ISD::ADDC:
10837   case ISD::ADDE:
10838   case ISD::SUBC:
10839   case ISD::SUBE:
10840     // We don't want to expand or promote these.
10841     return;
10842   case ISD::FP_TO_SINT: {
10843     std::pair<SDValue,SDValue> Vals =
10844         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10845     SDValue FIST = Vals.first, StackSlot = Vals.second;
10846     if (FIST.getNode() != 0) {
10847       EVT VT = N->getValueType(0);
10848       // Return a load from the stack slot.
10849       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10850                                     MachinePointerInfo(), 
10851                                     false, false, false, 0));
10852     }
10853     return;
10854   }
10855   case ISD::READCYCLECOUNTER: {
10856     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10857     SDValue TheChain = N->getOperand(0);
10858     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10859     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10860                                      rd.getValue(1));
10861     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10862                                      eax.getValue(2));
10863     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10864     SDValue Ops[] = { eax, edx };
10865     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10866     Results.push_back(edx.getValue(1));
10867     return;
10868   }
10869   case ISD::ATOMIC_CMP_SWAP: {
10870     EVT T = N->getValueType(0);
10871     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10872     bool Regs64bit = T == MVT::i128;
10873     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10874     SDValue cpInL, cpInH;
10875     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10876                         DAG.getConstant(0, HalfT));
10877     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10878                         DAG.getConstant(1, HalfT));
10879     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10880                              Regs64bit ? X86::RAX : X86::EAX,
10881                              cpInL, SDValue());
10882     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10883                              Regs64bit ? X86::RDX : X86::EDX,
10884                              cpInH, cpInL.getValue(1));
10885     SDValue swapInL, swapInH;
10886     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10887                           DAG.getConstant(0, HalfT));
10888     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10889                           DAG.getConstant(1, HalfT));
10890     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10891                                Regs64bit ? X86::RBX : X86::EBX,
10892                                swapInL, cpInH.getValue(1));
10893     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10894                                Regs64bit ? X86::RCX : X86::ECX, 
10895                                swapInH, swapInL.getValue(1));
10896     SDValue Ops[] = { swapInH.getValue(0),
10897                       N->getOperand(1),
10898                       swapInH.getValue(1) };
10899     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10900     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10901     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10902                                   X86ISD::LCMPXCHG8_DAG;
10903     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10904                                              Ops, 3, T, MMO);
10905     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10906                                         Regs64bit ? X86::RAX : X86::EAX,
10907                                         HalfT, Result.getValue(1));
10908     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10909                                         Regs64bit ? X86::RDX : X86::EDX,
10910                                         HalfT, cpOutL.getValue(2));
10911     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10912     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10913     Results.push_back(cpOutH.getValue(1));
10914     return;
10915   }
10916   case ISD::ATOMIC_LOAD_ADD:
10917     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10918     return;
10919   case ISD::ATOMIC_LOAD_AND:
10920     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10921     return;
10922   case ISD::ATOMIC_LOAD_NAND:
10923     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10924     return;
10925   case ISD::ATOMIC_LOAD_OR:
10926     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10927     return;
10928   case ISD::ATOMIC_LOAD_SUB:
10929     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10930     return;
10931   case ISD::ATOMIC_LOAD_XOR:
10932     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10933     return;
10934   case ISD::ATOMIC_SWAP:
10935     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10936     return;
10937   case ISD::ATOMIC_LOAD:
10938     ReplaceATOMIC_LOAD(N, Results, DAG);
10939   }
10940 }
10941
10942 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10943   switch (Opcode) {
10944   default: return NULL;
10945   case X86ISD::BSF:                return "X86ISD::BSF";
10946   case X86ISD::BSR:                return "X86ISD::BSR";
10947   case X86ISD::SHLD:               return "X86ISD::SHLD";
10948   case X86ISD::SHRD:               return "X86ISD::SHRD";
10949   case X86ISD::FAND:               return "X86ISD::FAND";
10950   case X86ISD::FOR:                return "X86ISD::FOR";
10951   case X86ISD::FXOR:               return "X86ISD::FXOR";
10952   case X86ISD::FSRL:               return "X86ISD::FSRL";
10953   case X86ISD::FILD:               return "X86ISD::FILD";
10954   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10955   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10956   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10957   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10958   case X86ISD::FLD:                return "X86ISD::FLD";
10959   case X86ISD::FST:                return "X86ISD::FST";
10960   case X86ISD::CALL:               return "X86ISD::CALL";
10961   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10962   case X86ISD::BT:                 return "X86ISD::BT";
10963   case X86ISD::CMP:                return "X86ISD::CMP";
10964   case X86ISD::COMI:               return "X86ISD::COMI";
10965   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10966   case X86ISD::SETCC:              return "X86ISD::SETCC";
10967   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10968   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10969   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10970   case X86ISD::CMOV:               return "X86ISD::CMOV";
10971   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10972   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10973   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10974   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10975   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10976   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10977   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10978   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10979   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10980   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10981   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10982   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10983   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10984   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10985   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
10986   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
10987   case X86ISD::HADD:               return "X86ISD::HADD";
10988   case X86ISD::HSUB:               return "X86ISD::HSUB";
10989   case X86ISD::FHADD:              return "X86ISD::FHADD";
10990   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10991   case X86ISD::FMAX:               return "X86ISD::FMAX";
10992   case X86ISD::FMIN:               return "X86ISD::FMIN";
10993   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10994   case X86ISD::FRCP:               return "X86ISD::FRCP";
10995   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10996   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10997   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10998   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10999   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11000   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11001   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11002   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11003   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11004   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11005   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11006   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11007   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11008   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11009   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11010   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11011   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11012   case X86ISD::VSHL:               return "X86ISD::VSHL";
11013   case X86ISD::VSRL:               return "X86ISD::VSRL";
11014   case X86ISD::VSRA:               return "X86ISD::VSRA";
11015   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11016   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11017   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11018   case X86ISD::CMPP:               return "X86ISD::CMPP";
11019   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11020   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11021   case X86ISD::ADD:                return "X86ISD::ADD";
11022   case X86ISD::SUB:                return "X86ISD::SUB";
11023   case X86ISD::ADC:                return "X86ISD::ADC";
11024   case X86ISD::SBB:                return "X86ISD::SBB";
11025   case X86ISD::SMUL:               return "X86ISD::SMUL";
11026   case X86ISD::UMUL:               return "X86ISD::UMUL";
11027   case X86ISD::INC:                return "X86ISD::INC";
11028   case X86ISD::DEC:                return "X86ISD::DEC";
11029   case X86ISD::OR:                 return "X86ISD::OR";
11030   case X86ISD::XOR:                return "X86ISD::XOR";
11031   case X86ISD::AND:                return "X86ISD::AND";
11032   case X86ISD::ANDN:               return "X86ISD::ANDN";
11033   case X86ISD::BLSI:               return "X86ISD::BLSI";
11034   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11035   case X86ISD::BLSR:               return "X86ISD::BLSR";
11036   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11037   case X86ISD::PTEST:              return "X86ISD::PTEST";
11038   case X86ISD::TESTP:              return "X86ISD::TESTP";
11039   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11040   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11041   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11042   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11043   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11044   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11045   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11046   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11047   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11048   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11049   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11050   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11051   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11052   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11053   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11054   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11055   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11056   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11057   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11058   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11059   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11060   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11061   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11062   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11063   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11064   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11065   }
11066 }
11067
11068 // isLegalAddressingMode - Return true if the addressing mode represented
11069 // by AM is legal for this target, for a load/store of the specified type.
11070 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11071                                               Type *Ty) const {
11072   // X86 supports extremely general addressing modes.
11073   CodeModel::Model M = getTargetMachine().getCodeModel();
11074   Reloc::Model R = getTargetMachine().getRelocationModel();
11075
11076   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11077   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11078     return false;
11079
11080   if (AM.BaseGV) {
11081     unsigned GVFlags =
11082       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11083
11084     // If a reference to this global requires an extra load, we can't fold it.
11085     if (isGlobalStubReference(GVFlags))
11086       return false;
11087
11088     // If BaseGV requires a register for the PIC base, we cannot also have a
11089     // BaseReg specified.
11090     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11091       return false;
11092
11093     // If lower 4G is not available, then we must use rip-relative addressing.
11094     if ((M != CodeModel::Small || R != Reloc::Static) &&
11095         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11096       return false;
11097   }
11098
11099   switch (AM.Scale) {
11100   case 0:
11101   case 1:
11102   case 2:
11103   case 4:
11104   case 8:
11105     // These scales always work.
11106     break;
11107   case 3:
11108   case 5:
11109   case 9:
11110     // These scales are formed with basereg+scalereg.  Only accept if there is
11111     // no basereg yet.
11112     if (AM.HasBaseReg)
11113       return false;
11114     break;
11115   default:  // Other stuff never works.
11116     return false;
11117   }
11118
11119   return true;
11120 }
11121
11122
11123 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11124   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11125     return false;
11126   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11127   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11128   if (NumBits1 <= NumBits2)
11129     return false;
11130   return true;
11131 }
11132
11133 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11134   if (!VT1.isInteger() || !VT2.isInteger())
11135     return false;
11136   unsigned NumBits1 = VT1.getSizeInBits();
11137   unsigned NumBits2 = VT2.getSizeInBits();
11138   if (NumBits1 <= NumBits2)
11139     return false;
11140   return true;
11141 }
11142
11143 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11144   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11145   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11146 }
11147
11148 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11149   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11150   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11151 }
11152
11153 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11154   // i16 instructions are longer (0x66 prefix) and potentially slower.
11155   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11156 }
11157
11158 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11159 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11160 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11161 /// are assumed to be legal.
11162 bool
11163 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11164                                       EVT VT) const {
11165   // Very little shuffling can be done for 64-bit vectors right now.
11166   if (VT.getSizeInBits() == 64)
11167     return false;
11168
11169   // FIXME: pshufb, blends, shifts.
11170   return (VT.getVectorNumElements() == 2 ||
11171           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11172           isMOVLMask(M, VT) ||
11173           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11174           isPSHUFDMask(M, VT) ||
11175           isPSHUFHWMask(M, VT) ||
11176           isPSHUFLWMask(M, VT) ||
11177           isPALIGNRMask(M, VT, Subtarget) ||
11178           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11179           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11180           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11181           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11182 }
11183
11184 bool
11185 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11186                                           EVT VT) const {
11187   unsigned NumElts = VT.getVectorNumElements();
11188   // FIXME: This collection of masks seems suspect.
11189   if (NumElts == 2)
11190     return true;
11191   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11192     return (isMOVLMask(Mask, VT)  ||
11193             isCommutedMOVLMask(Mask, VT, true) ||
11194             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11195             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11196   }
11197   return false;
11198 }
11199
11200 //===----------------------------------------------------------------------===//
11201 //                           X86 Scheduler Hooks
11202 //===----------------------------------------------------------------------===//
11203
11204 // private utility function
11205 MachineBasicBlock *
11206 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11207                                                        MachineBasicBlock *MBB,
11208                                                        unsigned regOpc,
11209                                                        unsigned immOpc,
11210                                                        unsigned LoadOpc,
11211                                                        unsigned CXchgOpc,
11212                                                        unsigned notOpc,
11213                                                        unsigned EAXreg,
11214                                                        TargetRegisterClass *RC,
11215                                                        bool invSrc) const {
11216   // For the atomic bitwise operator, we generate
11217   //   thisMBB:
11218   //   newMBB:
11219   //     ld  t1 = [bitinstr.addr]
11220   //     op  t2 = t1, [bitinstr.val]
11221   //     mov EAX = t1
11222   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11223   //     bz  newMBB
11224   //     fallthrough -->nextMBB
11225   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11226   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11227   MachineFunction::iterator MBBIter = MBB;
11228   ++MBBIter;
11229
11230   /// First build the CFG
11231   MachineFunction *F = MBB->getParent();
11232   MachineBasicBlock *thisMBB = MBB;
11233   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11234   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11235   F->insert(MBBIter, newMBB);
11236   F->insert(MBBIter, nextMBB);
11237
11238   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11239   nextMBB->splice(nextMBB->begin(), thisMBB,
11240                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11241                   thisMBB->end());
11242   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11243
11244   // Update thisMBB to fall through to newMBB
11245   thisMBB->addSuccessor(newMBB);
11246
11247   // newMBB jumps to itself and fall through to nextMBB
11248   newMBB->addSuccessor(nextMBB);
11249   newMBB->addSuccessor(newMBB);
11250
11251   // Insert instructions into newMBB based on incoming instruction
11252   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11253          "unexpected number of operands");
11254   DebugLoc dl = bInstr->getDebugLoc();
11255   MachineOperand& destOper = bInstr->getOperand(0);
11256   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11257   int numArgs = bInstr->getNumOperands() - 1;
11258   for (int i=0; i < numArgs; ++i)
11259     argOpers[i] = &bInstr->getOperand(i+1);
11260
11261   // x86 address has 4 operands: base, index, scale, and displacement
11262   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11263   int valArgIndx = lastAddrIndx + 1;
11264
11265   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11266   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11267   for (int i=0; i <= lastAddrIndx; ++i)
11268     (*MIB).addOperand(*argOpers[i]);
11269
11270   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11271   if (invSrc) {
11272     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11273   }
11274   else
11275     tt = t1;
11276
11277   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11278   assert((argOpers[valArgIndx]->isReg() ||
11279           argOpers[valArgIndx]->isImm()) &&
11280          "invalid operand");
11281   if (argOpers[valArgIndx]->isReg())
11282     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11283   else
11284     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11285   MIB.addReg(tt);
11286   (*MIB).addOperand(*argOpers[valArgIndx]);
11287
11288   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11289   MIB.addReg(t1);
11290
11291   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11292   for (int i=0; i <= lastAddrIndx; ++i)
11293     (*MIB).addOperand(*argOpers[i]);
11294   MIB.addReg(t2);
11295   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11296   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11297                     bInstr->memoperands_end());
11298
11299   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11300   MIB.addReg(EAXreg);
11301
11302   // insert branch
11303   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11304
11305   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11306   return nextMBB;
11307 }
11308
11309 // private utility function:  64 bit atomics on 32 bit host.
11310 MachineBasicBlock *
11311 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11312                                                        MachineBasicBlock *MBB,
11313                                                        unsigned regOpcL,
11314                                                        unsigned regOpcH,
11315                                                        unsigned immOpcL,
11316                                                        unsigned immOpcH,
11317                                                        bool invSrc) const {
11318   // For the atomic bitwise operator, we generate
11319   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11320   //     ld t1,t2 = [bitinstr.addr]
11321   //   newMBB:
11322   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11323   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11324   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11325   //     mov ECX, EBX <- t5, t6
11326   //     mov EAX, EDX <- t1, t2
11327   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11328   //     mov t3, t4 <- EAX, EDX
11329   //     bz  newMBB
11330   //     result in out1, out2
11331   //     fallthrough -->nextMBB
11332
11333   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11334   const unsigned LoadOpc = X86::MOV32rm;
11335   const unsigned NotOpc = X86::NOT32r;
11336   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11337   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11338   MachineFunction::iterator MBBIter = MBB;
11339   ++MBBIter;
11340
11341   /// First build the CFG
11342   MachineFunction *F = MBB->getParent();
11343   MachineBasicBlock *thisMBB = MBB;
11344   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11345   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11346   F->insert(MBBIter, newMBB);
11347   F->insert(MBBIter, nextMBB);
11348
11349   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11350   nextMBB->splice(nextMBB->begin(), thisMBB,
11351                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11352                   thisMBB->end());
11353   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11354
11355   // Update thisMBB to fall through to newMBB
11356   thisMBB->addSuccessor(newMBB);
11357
11358   // newMBB jumps to itself and fall through to nextMBB
11359   newMBB->addSuccessor(nextMBB);
11360   newMBB->addSuccessor(newMBB);
11361
11362   DebugLoc dl = bInstr->getDebugLoc();
11363   // Insert instructions into newMBB based on incoming instruction
11364   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11365   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11366          "unexpected number of operands");
11367   MachineOperand& dest1Oper = bInstr->getOperand(0);
11368   MachineOperand& dest2Oper = bInstr->getOperand(1);
11369   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11370   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11371     argOpers[i] = &bInstr->getOperand(i+2);
11372
11373     // We use some of the operands multiple times, so conservatively just
11374     // clear any kill flags that might be present.
11375     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11376       argOpers[i]->setIsKill(false);
11377   }
11378
11379   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11380   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11381
11382   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11383   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11384   for (int i=0; i <= lastAddrIndx; ++i)
11385     (*MIB).addOperand(*argOpers[i]);
11386   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11387   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11388   // add 4 to displacement.
11389   for (int i=0; i <= lastAddrIndx-2; ++i)
11390     (*MIB).addOperand(*argOpers[i]);
11391   MachineOperand newOp3 = *(argOpers[3]);
11392   if (newOp3.isImm())
11393     newOp3.setImm(newOp3.getImm()+4);
11394   else
11395     newOp3.setOffset(newOp3.getOffset()+4);
11396   (*MIB).addOperand(newOp3);
11397   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11398
11399   // t3/4 are defined later, at the bottom of the loop
11400   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11401   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11402   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11403     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11404   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11405     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11406
11407   // The subsequent operations should be using the destination registers of
11408   //the PHI instructions.
11409   if (invSrc) {
11410     t1 = F->getRegInfo().createVirtualRegister(RC);
11411     t2 = F->getRegInfo().createVirtualRegister(RC);
11412     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11413     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11414   } else {
11415     t1 = dest1Oper.getReg();
11416     t2 = dest2Oper.getReg();
11417   }
11418
11419   int valArgIndx = lastAddrIndx + 1;
11420   assert((argOpers[valArgIndx]->isReg() ||
11421           argOpers[valArgIndx]->isImm()) &&
11422          "invalid operand");
11423   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11424   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11425   if (argOpers[valArgIndx]->isReg())
11426     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11427   else
11428     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11429   if (regOpcL != X86::MOV32rr)
11430     MIB.addReg(t1);
11431   (*MIB).addOperand(*argOpers[valArgIndx]);
11432   assert(argOpers[valArgIndx + 1]->isReg() ==
11433          argOpers[valArgIndx]->isReg());
11434   assert(argOpers[valArgIndx + 1]->isImm() ==
11435          argOpers[valArgIndx]->isImm());
11436   if (argOpers[valArgIndx + 1]->isReg())
11437     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11438   else
11439     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11440   if (regOpcH != X86::MOV32rr)
11441     MIB.addReg(t2);
11442   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11443
11444   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11445   MIB.addReg(t1);
11446   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11447   MIB.addReg(t2);
11448
11449   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11450   MIB.addReg(t5);
11451   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11452   MIB.addReg(t6);
11453
11454   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11455   for (int i=0; i <= lastAddrIndx; ++i)
11456     (*MIB).addOperand(*argOpers[i]);
11457
11458   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11459   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11460                     bInstr->memoperands_end());
11461
11462   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11463   MIB.addReg(X86::EAX);
11464   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11465   MIB.addReg(X86::EDX);
11466
11467   // insert branch
11468   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11469
11470   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11471   return nextMBB;
11472 }
11473
11474 // private utility function
11475 MachineBasicBlock *
11476 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11477                                                       MachineBasicBlock *MBB,
11478                                                       unsigned cmovOpc) const {
11479   // For the atomic min/max operator, we generate
11480   //   thisMBB:
11481   //   newMBB:
11482   //     ld t1 = [min/max.addr]
11483   //     mov t2 = [min/max.val]
11484   //     cmp  t1, t2
11485   //     cmov[cond] t2 = t1
11486   //     mov EAX = t1
11487   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11488   //     bz   newMBB
11489   //     fallthrough -->nextMBB
11490   //
11491   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11492   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11493   MachineFunction::iterator MBBIter = MBB;
11494   ++MBBIter;
11495
11496   /// First build the CFG
11497   MachineFunction *F = MBB->getParent();
11498   MachineBasicBlock *thisMBB = MBB;
11499   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11500   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11501   F->insert(MBBIter, newMBB);
11502   F->insert(MBBIter, nextMBB);
11503
11504   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11505   nextMBB->splice(nextMBB->begin(), thisMBB,
11506                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11507                   thisMBB->end());
11508   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11509
11510   // Update thisMBB to fall through to newMBB
11511   thisMBB->addSuccessor(newMBB);
11512
11513   // newMBB jumps to newMBB and fall through to nextMBB
11514   newMBB->addSuccessor(nextMBB);
11515   newMBB->addSuccessor(newMBB);
11516
11517   DebugLoc dl = mInstr->getDebugLoc();
11518   // Insert instructions into newMBB based on incoming instruction
11519   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11520          "unexpected number of operands");
11521   MachineOperand& destOper = mInstr->getOperand(0);
11522   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11523   int numArgs = mInstr->getNumOperands() - 1;
11524   for (int i=0; i < numArgs; ++i)
11525     argOpers[i] = &mInstr->getOperand(i+1);
11526
11527   // x86 address has 4 operands: base, index, scale, and displacement
11528   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11529   int valArgIndx = lastAddrIndx + 1;
11530
11531   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11532   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11533   for (int i=0; i <= lastAddrIndx; ++i)
11534     (*MIB).addOperand(*argOpers[i]);
11535
11536   // We only support register and immediate values
11537   assert((argOpers[valArgIndx]->isReg() ||
11538           argOpers[valArgIndx]->isImm()) &&
11539          "invalid operand");
11540
11541   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11542   if (argOpers[valArgIndx]->isReg())
11543     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11544   else
11545     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11546   (*MIB).addOperand(*argOpers[valArgIndx]);
11547
11548   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11549   MIB.addReg(t1);
11550
11551   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11552   MIB.addReg(t1);
11553   MIB.addReg(t2);
11554
11555   // Generate movc
11556   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11557   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11558   MIB.addReg(t2);
11559   MIB.addReg(t1);
11560
11561   // Cmp and exchange if none has modified the memory location
11562   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11563   for (int i=0; i <= lastAddrIndx; ++i)
11564     (*MIB).addOperand(*argOpers[i]);
11565   MIB.addReg(t3);
11566   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11567   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11568                     mInstr->memoperands_end());
11569
11570   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11571   MIB.addReg(X86::EAX);
11572
11573   // insert branch
11574   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11575
11576   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11577   return nextMBB;
11578 }
11579
11580 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11581 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11582 // in the .td file.
11583 MachineBasicBlock *
11584 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11585                             unsigned numArgs, bool memArg) const {
11586   assert(Subtarget->hasSSE42() &&
11587          "Target must have SSE4.2 or AVX features enabled");
11588
11589   DebugLoc dl = MI->getDebugLoc();
11590   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11591   unsigned Opc;
11592   if (!Subtarget->hasAVX()) {
11593     if (memArg)
11594       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11595     else
11596       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11597   } else {
11598     if (memArg)
11599       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11600     else
11601       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11602   }
11603
11604   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11605   for (unsigned i = 0; i < numArgs; ++i) {
11606     MachineOperand &Op = MI->getOperand(i+1);
11607     if (!(Op.isReg() && Op.isImplicit()))
11608       MIB.addOperand(Op);
11609   }
11610   BuildMI(*BB, MI, dl,
11611     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11612              MI->getOperand(0).getReg())
11613     .addReg(X86::XMM0);
11614
11615   MI->eraseFromParent();
11616   return BB;
11617 }
11618
11619 MachineBasicBlock *
11620 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11621   DebugLoc dl = MI->getDebugLoc();
11622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11623
11624   // Address into RAX/EAX, other two args into ECX, EDX.
11625   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11626   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11627   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11628   for (int i = 0; i < X86::AddrNumOperands; ++i)
11629     MIB.addOperand(MI->getOperand(i));
11630
11631   unsigned ValOps = X86::AddrNumOperands;
11632   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11633     .addReg(MI->getOperand(ValOps).getReg());
11634   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11635     .addReg(MI->getOperand(ValOps+1).getReg());
11636
11637   // The instruction doesn't actually take any operands though.
11638   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11639
11640   MI->eraseFromParent(); // The pseudo is gone now.
11641   return BB;
11642 }
11643
11644 MachineBasicBlock *
11645 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11646   DebugLoc dl = MI->getDebugLoc();
11647   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11648
11649   // First arg in ECX, the second in EAX.
11650   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11651     .addReg(MI->getOperand(0).getReg());
11652   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11653     .addReg(MI->getOperand(1).getReg());
11654
11655   // The instruction doesn't actually take any operands though.
11656   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11657
11658   MI->eraseFromParent(); // The pseudo is gone now.
11659   return BB;
11660 }
11661
11662 MachineBasicBlock *
11663 X86TargetLowering::EmitVAARG64WithCustomInserter(
11664                    MachineInstr *MI,
11665                    MachineBasicBlock *MBB) const {
11666   // Emit va_arg instruction on X86-64.
11667
11668   // Operands to this pseudo-instruction:
11669   // 0  ) Output        : destination address (reg)
11670   // 1-5) Input         : va_list address (addr, i64mem)
11671   // 6  ) ArgSize       : Size (in bytes) of vararg type
11672   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11673   // 8  ) Align         : Alignment of type
11674   // 9  ) EFLAGS (implicit-def)
11675
11676   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11677   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11678
11679   unsigned DestReg = MI->getOperand(0).getReg();
11680   MachineOperand &Base = MI->getOperand(1);
11681   MachineOperand &Scale = MI->getOperand(2);
11682   MachineOperand &Index = MI->getOperand(3);
11683   MachineOperand &Disp = MI->getOperand(4);
11684   MachineOperand &Segment = MI->getOperand(5);
11685   unsigned ArgSize = MI->getOperand(6).getImm();
11686   unsigned ArgMode = MI->getOperand(7).getImm();
11687   unsigned Align = MI->getOperand(8).getImm();
11688
11689   // Memory Reference
11690   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11691   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11692   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11693
11694   // Machine Information
11695   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11696   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11697   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11698   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11699   DebugLoc DL = MI->getDebugLoc();
11700
11701   // struct va_list {
11702   //   i32   gp_offset
11703   //   i32   fp_offset
11704   //   i64   overflow_area (address)
11705   //   i64   reg_save_area (address)
11706   // }
11707   // sizeof(va_list) = 24
11708   // alignment(va_list) = 8
11709
11710   unsigned TotalNumIntRegs = 6;
11711   unsigned TotalNumXMMRegs = 8;
11712   bool UseGPOffset = (ArgMode == 1);
11713   bool UseFPOffset = (ArgMode == 2);
11714   unsigned MaxOffset = TotalNumIntRegs * 8 +
11715                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11716
11717   /* Align ArgSize to a multiple of 8 */
11718   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11719   bool NeedsAlign = (Align > 8);
11720
11721   MachineBasicBlock *thisMBB = MBB;
11722   MachineBasicBlock *overflowMBB;
11723   MachineBasicBlock *offsetMBB;
11724   MachineBasicBlock *endMBB;
11725
11726   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11727   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11728   unsigned OffsetReg = 0;
11729
11730   if (!UseGPOffset && !UseFPOffset) {
11731     // If we only pull from the overflow region, we don't create a branch.
11732     // We don't need to alter control flow.
11733     OffsetDestReg = 0; // unused
11734     OverflowDestReg = DestReg;
11735
11736     offsetMBB = NULL;
11737     overflowMBB = thisMBB;
11738     endMBB = thisMBB;
11739   } else {
11740     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11741     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11742     // If not, pull from overflow_area. (branch to overflowMBB)
11743     //
11744     //       thisMBB
11745     //         |     .
11746     //         |        .
11747     //     offsetMBB   overflowMBB
11748     //         |        .
11749     //         |     .
11750     //        endMBB
11751
11752     // Registers for the PHI in endMBB
11753     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11754     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11755
11756     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11757     MachineFunction *MF = MBB->getParent();
11758     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11759     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11760     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11761
11762     MachineFunction::iterator MBBIter = MBB;
11763     ++MBBIter;
11764
11765     // Insert the new basic blocks
11766     MF->insert(MBBIter, offsetMBB);
11767     MF->insert(MBBIter, overflowMBB);
11768     MF->insert(MBBIter, endMBB);
11769
11770     // Transfer the remainder of MBB and its successor edges to endMBB.
11771     endMBB->splice(endMBB->begin(), thisMBB,
11772                     llvm::next(MachineBasicBlock::iterator(MI)),
11773                     thisMBB->end());
11774     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11775
11776     // Make offsetMBB and overflowMBB successors of thisMBB
11777     thisMBB->addSuccessor(offsetMBB);
11778     thisMBB->addSuccessor(overflowMBB);
11779
11780     // endMBB is a successor of both offsetMBB and overflowMBB
11781     offsetMBB->addSuccessor(endMBB);
11782     overflowMBB->addSuccessor(endMBB);
11783
11784     // Load the offset value into a register
11785     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11786     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11787       .addOperand(Base)
11788       .addOperand(Scale)
11789       .addOperand(Index)
11790       .addDisp(Disp, UseFPOffset ? 4 : 0)
11791       .addOperand(Segment)
11792       .setMemRefs(MMOBegin, MMOEnd);
11793
11794     // Check if there is enough room left to pull this argument.
11795     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11796       .addReg(OffsetReg)
11797       .addImm(MaxOffset + 8 - ArgSizeA8);
11798
11799     // Branch to "overflowMBB" if offset >= max
11800     // Fall through to "offsetMBB" otherwise
11801     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11802       .addMBB(overflowMBB);
11803   }
11804
11805   // In offsetMBB, emit code to use the reg_save_area.
11806   if (offsetMBB) {
11807     assert(OffsetReg != 0);
11808
11809     // Read the reg_save_area address.
11810     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11811     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11812       .addOperand(Base)
11813       .addOperand(Scale)
11814       .addOperand(Index)
11815       .addDisp(Disp, 16)
11816       .addOperand(Segment)
11817       .setMemRefs(MMOBegin, MMOEnd);
11818
11819     // Zero-extend the offset
11820     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11821       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11822         .addImm(0)
11823         .addReg(OffsetReg)
11824         .addImm(X86::sub_32bit);
11825
11826     // Add the offset to the reg_save_area to get the final address.
11827     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11828       .addReg(OffsetReg64)
11829       .addReg(RegSaveReg);
11830
11831     // Compute the offset for the next argument
11832     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11833     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11834       .addReg(OffsetReg)
11835       .addImm(UseFPOffset ? 16 : 8);
11836
11837     // Store it back into the va_list.
11838     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11839       .addOperand(Base)
11840       .addOperand(Scale)
11841       .addOperand(Index)
11842       .addDisp(Disp, UseFPOffset ? 4 : 0)
11843       .addOperand(Segment)
11844       .addReg(NextOffsetReg)
11845       .setMemRefs(MMOBegin, MMOEnd);
11846
11847     // Jump to endMBB
11848     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11849       .addMBB(endMBB);
11850   }
11851
11852   //
11853   // Emit code to use overflow area
11854   //
11855
11856   // Load the overflow_area address into a register.
11857   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11858   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11859     .addOperand(Base)
11860     .addOperand(Scale)
11861     .addOperand(Index)
11862     .addDisp(Disp, 8)
11863     .addOperand(Segment)
11864     .setMemRefs(MMOBegin, MMOEnd);
11865
11866   // If we need to align it, do so. Otherwise, just copy the address
11867   // to OverflowDestReg.
11868   if (NeedsAlign) {
11869     // Align the overflow address
11870     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11871     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11872
11873     // aligned_addr = (addr + (align-1)) & ~(align-1)
11874     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11875       .addReg(OverflowAddrReg)
11876       .addImm(Align-1);
11877
11878     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11879       .addReg(TmpReg)
11880       .addImm(~(uint64_t)(Align-1));
11881   } else {
11882     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11883       .addReg(OverflowAddrReg);
11884   }
11885
11886   // Compute the next overflow address after this argument.
11887   // (the overflow address should be kept 8-byte aligned)
11888   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11889   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11890     .addReg(OverflowDestReg)
11891     .addImm(ArgSizeA8);
11892
11893   // Store the new overflow address.
11894   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11895     .addOperand(Base)
11896     .addOperand(Scale)
11897     .addOperand(Index)
11898     .addDisp(Disp, 8)
11899     .addOperand(Segment)
11900     .addReg(NextAddrReg)
11901     .setMemRefs(MMOBegin, MMOEnd);
11902
11903   // If we branched, emit the PHI to the front of endMBB.
11904   if (offsetMBB) {
11905     BuildMI(*endMBB, endMBB->begin(), DL,
11906             TII->get(X86::PHI), DestReg)
11907       .addReg(OffsetDestReg).addMBB(offsetMBB)
11908       .addReg(OverflowDestReg).addMBB(overflowMBB);
11909   }
11910
11911   // Erase the pseudo instruction
11912   MI->eraseFromParent();
11913
11914   return endMBB;
11915 }
11916
11917 MachineBasicBlock *
11918 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11919                                                  MachineInstr *MI,
11920                                                  MachineBasicBlock *MBB) const {
11921   // Emit code to save XMM registers to the stack. The ABI says that the
11922   // number of registers to save is given in %al, so it's theoretically
11923   // possible to do an indirect jump trick to avoid saving all of them,
11924   // however this code takes a simpler approach and just executes all
11925   // of the stores if %al is non-zero. It's less code, and it's probably
11926   // easier on the hardware branch predictor, and stores aren't all that
11927   // expensive anyway.
11928
11929   // Create the new basic blocks. One block contains all the XMM stores,
11930   // and one block is the final destination regardless of whether any
11931   // stores were performed.
11932   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11933   MachineFunction *F = MBB->getParent();
11934   MachineFunction::iterator MBBIter = MBB;
11935   ++MBBIter;
11936   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11937   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11938   F->insert(MBBIter, XMMSaveMBB);
11939   F->insert(MBBIter, EndMBB);
11940
11941   // Transfer the remainder of MBB and its successor edges to EndMBB.
11942   EndMBB->splice(EndMBB->begin(), MBB,
11943                  llvm::next(MachineBasicBlock::iterator(MI)),
11944                  MBB->end());
11945   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11946
11947   // The original block will now fall through to the XMM save block.
11948   MBB->addSuccessor(XMMSaveMBB);
11949   // The XMMSaveMBB will fall through to the end block.
11950   XMMSaveMBB->addSuccessor(EndMBB);
11951
11952   // Now add the instructions.
11953   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11954   DebugLoc DL = MI->getDebugLoc();
11955
11956   unsigned CountReg = MI->getOperand(0).getReg();
11957   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11958   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11959
11960   if (!Subtarget->isTargetWin64()) {
11961     // If %al is 0, branch around the XMM save block.
11962     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11963     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11964     MBB->addSuccessor(EndMBB);
11965   }
11966
11967   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11968   // In the XMM save block, save all the XMM argument registers.
11969   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11970     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11971     MachineMemOperand *MMO =
11972       F->getMachineMemOperand(
11973           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11974         MachineMemOperand::MOStore,
11975         /*Size=*/16, /*Align=*/16);
11976     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11977       .addFrameIndex(RegSaveFrameIndex)
11978       .addImm(/*Scale=*/1)
11979       .addReg(/*IndexReg=*/0)
11980       .addImm(/*Disp=*/Offset)
11981       .addReg(/*Segment=*/0)
11982       .addReg(MI->getOperand(i).getReg())
11983       .addMemOperand(MMO);
11984   }
11985
11986   MI->eraseFromParent();   // The pseudo instruction is gone now.
11987
11988   return EndMBB;
11989 }
11990
11991 // The EFLAGS operand of SelectItr might be missing a kill marker
11992 // because there were multiple uses of EFLAGS, and ISel didn't know
11993 // which to mark. Figure out whether SelectItr should have had a
11994 // kill marker, and set it if it should. Returns the correct kill
11995 // marker value.
11996 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
11997                                      MachineBasicBlock* BB,
11998                                      const TargetRegisterInfo* TRI) {
11999   // Scan forward through BB for a use/def of EFLAGS.
12000   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12001   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12002     const MachineInstr& mi = *miI;
12003     if (mi.readsRegister(X86::EFLAGS))
12004       return false;
12005     if (mi.definesRegister(X86::EFLAGS))
12006       break; // Should have kill-flag - update below.
12007   }
12008
12009   // If we hit the end of the block, check whether EFLAGS is live into a
12010   // successor.
12011   if (miI == BB->end()) {
12012     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12013                                           sEnd = BB->succ_end();
12014          sItr != sEnd; ++sItr) {
12015       MachineBasicBlock* succ = *sItr;
12016       if (succ->isLiveIn(X86::EFLAGS))
12017         return false;
12018     }
12019   }
12020
12021   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12022   // out. SelectMI should have a kill flag on EFLAGS.
12023   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12024   return true;
12025 }
12026
12027 MachineBasicBlock *
12028 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12029                                      MachineBasicBlock *BB) const {
12030   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12031   DebugLoc DL = MI->getDebugLoc();
12032
12033   // To "insert" a SELECT_CC instruction, we actually have to insert the
12034   // diamond control-flow pattern.  The incoming instruction knows the
12035   // destination vreg to set, the condition code register to branch on, the
12036   // true/false values to select between, and a branch opcode to use.
12037   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12038   MachineFunction::iterator It = BB;
12039   ++It;
12040
12041   //  thisMBB:
12042   //  ...
12043   //   TrueVal = ...
12044   //   cmpTY ccX, r1, r2
12045   //   bCC copy1MBB
12046   //   fallthrough --> copy0MBB
12047   MachineBasicBlock *thisMBB = BB;
12048   MachineFunction *F = BB->getParent();
12049   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12050   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12051   F->insert(It, copy0MBB);
12052   F->insert(It, sinkMBB);
12053
12054   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12055   // live into the sink and copy blocks.
12056   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12057   if (!MI->killsRegister(X86::EFLAGS) &&
12058       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12059     copy0MBB->addLiveIn(X86::EFLAGS);
12060     sinkMBB->addLiveIn(X86::EFLAGS);
12061   }
12062
12063   // Transfer the remainder of BB and its successor edges to sinkMBB.
12064   sinkMBB->splice(sinkMBB->begin(), BB,
12065                   llvm::next(MachineBasicBlock::iterator(MI)),
12066                   BB->end());
12067   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12068
12069   // Add the true and fallthrough blocks as its successors.
12070   BB->addSuccessor(copy0MBB);
12071   BB->addSuccessor(sinkMBB);
12072
12073   // Create the conditional branch instruction.
12074   unsigned Opc =
12075     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12076   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12077
12078   //  copy0MBB:
12079   //   %FalseValue = ...
12080   //   # fallthrough to sinkMBB
12081   copy0MBB->addSuccessor(sinkMBB);
12082
12083   //  sinkMBB:
12084   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12085   //  ...
12086   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12087           TII->get(X86::PHI), MI->getOperand(0).getReg())
12088     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12089     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12090
12091   MI->eraseFromParent();   // The pseudo instruction is gone now.
12092   return sinkMBB;
12093 }
12094
12095 MachineBasicBlock *
12096 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12097                                         bool Is64Bit) const {
12098   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12099   DebugLoc DL = MI->getDebugLoc();
12100   MachineFunction *MF = BB->getParent();
12101   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12102
12103   assert(getTargetMachine().Options.EnableSegmentedStacks);
12104
12105   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12106   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12107
12108   // BB:
12109   //  ... [Till the alloca]
12110   // If stacklet is not large enough, jump to mallocMBB
12111   //
12112   // bumpMBB:
12113   //  Allocate by subtracting from RSP
12114   //  Jump to continueMBB
12115   //
12116   // mallocMBB:
12117   //  Allocate by call to runtime
12118   //
12119   // continueMBB:
12120   //  ...
12121   //  [rest of original BB]
12122   //
12123
12124   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12125   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12126   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12127
12128   MachineRegisterInfo &MRI = MF->getRegInfo();
12129   const TargetRegisterClass *AddrRegClass =
12130     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12131
12132   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12133     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12134     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12135     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12136     sizeVReg = MI->getOperand(1).getReg(),
12137     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12138
12139   MachineFunction::iterator MBBIter = BB;
12140   ++MBBIter;
12141
12142   MF->insert(MBBIter, bumpMBB);
12143   MF->insert(MBBIter, mallocMBB);
12144   MF->insert(MBBIter, continueMBB);
12145
12146   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12147                       (MachineBasicBlock::iterator(MI)), BB->end());
12148   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12149
12150   // Add code to the main basic block to check if the stack limit has been hit,
12151   // and if so, jump to mallocMBB otherwise to bumpMBB.
12152   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12153   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12154     .addReg(tmpSPVReg).addReg(sizeVReg);
12155   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12156     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12157     .addReg(SPLimitVReg);
12158   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12159
12160   // bumpMBB simply decreases the stack pointer, since we know the current
12161   // stacklet has enough space.
12162   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12163     .addReg(SPLimitVReg);
12164   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12165     .addReg(SPLimitVReg);
12166   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12167
12168   // Calls into a routine in libgcc to allocate more space from the heap.
12169   if (Is64Bit) {
12170     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12171       .addReg(sizeVReg);
12172     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12173     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12174   } else {
12175     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12176       .addImm(12);
12177     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12178     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12179       .addExternalSymbol("__morestack_allocate_stack_space");
12180   }
12181
12182   if (!Is64Bit)
12183     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12184       .addImm(16);
12185
12186   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12187     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12188   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12189
12190   // Set up the CFG correctly.
12191   BB->addSuccessor(bumpMBB);
12192   BB->addSuccessor(mallocMBB);
12193   mallocMBB->addSuccessor(continueMBB);
12194   bumpMBB->addSuccessor(continueMBB);
12195
12196   // Take care of the PHI nodes.
12197   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12198           MI->getOperand(0).getReg())
12199     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12200     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12201
12202   // Delete the original pseudo instruction.
12203   MI->eraseFromParent();
12204
12205   // And we're done.
12206   return continueMBB;
12207 }
12208
12209 MachineBasicBlock *
12210 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12211                                           MachineBasicBlock *BB) const {
12212   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12213   DebugLoc DL = MI->getDebugLoc();
12214
12215   assert(!Subtarget->isTargetEnvMacho());
12216
12217   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12218   // non-trivial part is impdef of ESP.
12219
12220   if (Subtarget->isTargetWin64()) {
12221     if (Subtarget->isTargetCygMing()) {
12222       // ___chkstk(Mingw64):
12223       // Clobbers R10, R11, RAX and EFLAGS.
12224       // Updates RSP.
12225       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12226         .addExternalSymbol("___chkstk")
12227         .addReg(X86::RAX, RegState::Implicit)
12228         .addReg(X86::RSP, RegState::Implicit)
12229         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12230         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12231         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12232     } else {
12233       // __chkstk(MSVCRT): does not update stack pointer.
12234       // Clobbers R10, R11 and EFLAGS.
12235       // FIXME: RAX(allocated size) might be reused and not killed.
12236       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12237         .addExternalSymbol("__chkstk")
12238         .addReg(X86::RAX, RegState::Implicit)
12239         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12240       // RAX has the offset to subtracted from RSP.
12241       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12242         .addReg(X86::RSP)
12243         .addReg(X86::RAX);
12244     }
12245   } else {
12246     const char *StackProbeSymbol =
12247       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12248
12249     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12250       .addExternalSymbol(StackProbeSymbol)
12251       .addReg(X86::EAX, RegState::Implicit)
12252       .addReg(X86::ESP, RegState::Implicit)
12253       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12254       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12255       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12256   }
12257
12258   MI->eraseFromParent();   // The pseudo instruction is gone now.
12259   return BB;
12260 }
12261
12262 MachineBasicBlock *
12263 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12264                                       MachineBasicBlock *BB) const {
12265   // This is pretty easy.  We're taking the value that we received from
12266   // our load from the relocation, sticking it in either RDI (x86-64)
12267   // or EAX and doing an indirect call.  The return value will then
12268   // be in the normal return register.
12269   const X86InstrInfo *TII
12270     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12271   DebugLoc DL = MI->getDebugLoc();
12272   MachineFunction *F = BB->getParent();
12273
12274   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12275   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12276
12277   if (Subtarget->is64Bit()) {
12278     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12279                                       TII->get(X86::MOV64rm), X86::RDI)
12280     .addReg(X86::RIP)
12281     .addImm(0).addReg(0)
12282     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12283                       MI->getOperand(3).getTargetFlags())
12284     .addReg(0);
12285     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12286     addDirectMem(MIB, X86::RDI);
12287   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12288     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12289                                       TII->get(X86::MOV32rm), X86::EAX)
12290     .addReg(0)
12291     .addImm(0).addReg(0)
12292     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12293                       MI->getOperand(3).getTargetFlags())
12294     .addReg(0);
12295     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12296     addDirectMem(MIB, X86::EAX);
12297   } else {
12298     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12299                                       TII->get(X86::MOV32rm), X86::EAX)
12300     .addReg(TII->getGlobalBaseReg(F))
12301     .addImm(0).addReg(0)
12302     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12303                       MI->getOperand(3).getTargetFlags())
12304     .addReg(0);
12305     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12306     addDirectMem(MIB, X86::EAX);
12307   }
12308
12309   MI->eraseFromParent(); // The pseudo instruction is gone now.
12310   return BB;
12311 }
12312
12313 MachineBasicBlock *
12314 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12315                                                MachineBasicBlock *BB) const {
12316   switch (MI->getOpcode()) {
12317   default: llvm_unreachable("Unexpected instr type to insert");
12318   case X86::TAILJMPd64:
12319   case X86::TAILJMPr64:
12320   case X86::TAILJMPm64:
12321     llvm_unreachable("TAILJMP64 would not be touched here.");
12322   case X86::TCRETURNdi64:
12323   case X86::TCRETURNri64:
12324   case X86::TCRETURNmi64:
12325     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12326     // On AMD64, additional defs should be added before register allocation.
12327     if (!Subtarget->isTargetWin64()) {
12328       MI->addRegisterDefined(X86::RSI);
12329       MI->addRegisterDefined(X86::RDI);
12330       MI->addRegisterDefined(X86::XMM6);
12331       MI->addRegisterDefined(X86::XMM7);
12332       MI->addRegisterDefined(X86::XMM8);
12333       MI->addRegisterDefined(X86::XMM9);
12334       MI->addRegisterDefined(X86::XMM10);
12335       MI->addRegisterDefined(X86::XMM11);
12336       MI->addRegisterDefined(X86::XMM12);
12337       MI->addRegisterDefined(X86::XMM13);
12338       MI->addRegisterDefined(X86::XMM14);
12339       MI->addRegisterDefined(X86::XMM15);
12340     }
12341     return BB;
12342   case X86::WIN_ALLOCA:
12343     return EmitLoweredWinAlloca(MI, BB);
12344   case X86::SEG_ALLOCA_32:
12345     return EmitLoweredSegAlloca(MI, BB, false);
12346   case X86::SEG_ALLOCA_64:
12347     return EmitLoweredSegAlloca(MI, BB, true);
12348   case X86::TLSCall_32:
12349   case X86::TLSCall_64:
12350     return EmitLoweredTLSCall(MI, BB);
12351   case X86::CMOV_GR8:
12352   case X86::CMOV_FR32:
12353   case X86::CMOV_FR64:
12354   case X86::CMOV_V4F32:
12355   case X86::CMOV_V2F64:
12356   case X86::CMOV_V2I64:
12357   case X86::CMOV_V8F32:
12358   case X86::CMOV_V4F64:
12359   case X86::CMOV_V4I64:
12360   case X86::CMOV_GR16:
12361   case X86::CMOV_GR32:
12362   case X86::CMOV_RFP32:
12363   case X86::CMOV_RFP64:
12364   case X86::CMOV_RFP80:
12365     return EmitLoweredSelect(MI, BB);
12366
12367   case X86::FP32_TO_INT16_IN_MEM:
12368   case X86::FP32_TO_INT32_IN_MEM:
12369   case X86::FP32_TO_INT64_IN_MEM:
12370   case X86::FP64_TO_INT16_IN_MEM:
12371   case X86::FP64_TO_INT32_IN_MEM:
12372   case X86::FP64_TO_INT64_IN_MEM:
12373   case X86::FP80_TO_INT16_IN_MEM:
12374   case X86::FP80_TO_INT32_IN_MEM:
12375   case X86::FP80_TO_INT64_IN_MEM: {
12376     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12377     DebugLoc DL = MI->getDebugLoc();
12378
12379     // Change the floating point control register to use "round towards zero"
12380     // mode when truncating to an integer value.
12381     MachineFunction *F = BB->getParent();
12382     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12383     addFrameReference(BuildMI(*BB, MI, DL,
12384                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12385
12386     // Load the old value of the high byte of the control word...
12387     unsigned OldCW =
12388       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12389     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12390                       CWFrameIdx);
12391
12392     // Set the high part to be round to zero...
12393     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12394       .addImm(0xC7F);
12395
12396     // Reload the modified control word now...
12397     addFrameReference(BuildMI(*BB, MI, DL,
12398                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12399
12400     // Restore the memory image of control word to original value
12401     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12402       .addReg(OldCW);
12403
12404     // Get the X86 opcode to use.
12405     unsigned Opc;
12406     switch (MI->getOpcode()) {
12407     default: llvm_unreachable("illegal opcode!");
12408     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12409     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12410     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12411     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12412     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12413     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12414     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12415     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12416     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12417     }
12418
12419     X86AddressMode AM;
12420     MachineOperand &Op = MI->getOperand(0);
12421     if (Op.isReg()) {
12422       AM.BaseType = X86AddressMode::RegBase;
12423       AM.Base.Reg = Op.getReg();
12424     } else {
12425       AM.BaseType = X86AddressMode::FrameIndexBase;
12426       AM.Base.FrameIndex = Op.getIndex();
12427     }
12428     Op = MI->getOperand(1);
12429     if (Op.isImm())
12430       AM.Scale = Op.getImm();
12431     Op = MI->getOperand(2);
12432     if (Op.isImm())
12433       AM.IndexReg = Op.getImm();
12434     Op = MI->getOperand(3);
12435     if (Op.isGlobal()) {
12436       AM.GV = Op.getGlobal();
12437     } else {
12438       AM.Disp = Op.getImm();
12439     }
12440     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12441                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12442
12443     // Reload the original control word now.
12444     addFrameReference(BuildMI(*BB, MI, DL,
12445                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12446
12447     MI->eraseFromParent();   // The pseudo instruction is gone now.
12448     return BB;
12449   }
12450     // String/text processing lowering.
12451   case X86::PCMPISTRM128REG:
12452   case X86::VPCMPISTRM128REG:
12453     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12454   case X86::PCMPISTRM128MEM:
12455   case X86::VPCMPISTRM128MEM:
12456     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12457   case X86::PCMPESTRM128REG:
12458   case X86::VPCMPESTRM128REG:
12459     return EmitPCMP(MI, BB, 5, false /* in mem */);
12460   case X86::PCMPESTRM128MEM:
12461   case X86::VPCMPESTRM128MEM:
12462     return EmitPCMP(MI, BB, 5, true /* in mem */);
12463
12464     // Thread synchronization.
12465   case X86::MONITOR:
12466     return EmitMonitor(MI, BB);
12467   case X86::MWAIT:
12468     return EmitMwait(MI, BB);
12469
12470     // Atomic Lowering.
12471   case X86::ATOMAND32:
12472     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12473                                                X86::AND32ri, X86::MOV32rm,
12474                                                X86::LCMPXCHG32,
12475                                                X86::NOT32r, X86::EAX,
12476                                                X86::GR32RegisterClass);
12477   case X86::ATOMOR32:
12478     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12479                                                X86::OR32ri, X86::MOV32rm,
12480                                                X86::LCMPXCHG32,
12481                                                X86::NOT32r, X86::EAX,
12482                                                X86::GR32RegisterClass);
12483   case X86::ATOMXOR32:
12484     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12485                                                X86::XOR32ri, X86::MOV32rm,
12486                                                X86::LCMPXCHG32,
12487                                                X86::NOT32r, X86::EAX,
12488                                                X86::GR32RegisterClass);
12489   case X86::ATOMNAND32:
12490     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12491                                                X86::AND32ri, X86::MOV32rm,
12492                                                X86::LCMPXCHG32,
12493                                                X86::NOT32r, X86::EAX,
12494                                                X86::GR32RegisterClass, true);
12495   case X86::ATOMMIN32:
12496     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12497   case X86::ATOMMAX32:
12498     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12499   case X86::ATOMUMIN32:
12500     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12501   case X86::ATOMUMAX32:
12502     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12503
12504   case X86::ATOMAND16:
12505     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12506                                                X86::AND16ri, X86::MOV16rm,
12507                                                X86::LCMPXCHG16,
12508                                                X86::NOT16r, X86::AX,
12509                                                X86::GR16RegisterClass);
12510   case X86::ATOMOR16:
12511     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12512                                                X86::OR16ri, X86::MOV16rm,
12513                                                X86::LCMPXCHG16,
12514                                                X86::NOT16r, X86::AX,
12515                                                X86::GR16RegisterClass);
12516   case X86::ATOMXOR16:
12517     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12518                                                X86::XOR16ri, X86::MOV16rm,
12519                                                X86::LCMPXCHG16,
12520                                                X86::NOT16r, X86::AX,
12521                                                X86::GR16RegisterClass);
12522   case X86::ATOMNAND16:
12523     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12524                                                X86::AND16ri, X86::MOV16rm,
12525                                                X86::LCMPXCHG16,
12526                                                X86::NOT16r, X86::AX,
12527                                                X86::GR16RegisterClass, true);
12528   case X86::ATOMMIN16:
12529     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12530   case X86::ATOMMAX16:
12531     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12532   case X86::ATOMUMIN16:
12533     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12534   case X86::ATOMUMAX16:
12535     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12536
12537   case X86::ATOMAND8:
12538     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12539                                                X86::AND8ri, X86::MOV8rm,
12540                                                X86::LCMPXCHG8,
12541                                                X86::NOT8r, X86::AL,
12542                                                X86::GR8RegisterClass);
12543   case X86::ATOMOR8:
12544     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12545                                                X86::OR8ri, X86::MOV8rm,
12546                                                X86::LCMPXCHG8,
12547                                                X86::NOT8r, X86::AL,
12548                                                X86::GR8RegisterClass);
12549   case X86::ATOMXOR8:
12550     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12551                                                X86::XOR8ri, X86::MOV8rm,
12552                                                X86::LCMPXCHG8,
12553                                                X86::NOT8r, X86::AL,
12554                                                X86::GR8RegisterClass);
12555   case X86::ATOMNAND8:
12556     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12557                                                X86::AND8ri, X86::MOV8rm,
12558                                                X86::LCMPXCHG8,
12559                                                X86::NOT8r, X86::AL,
12560                                                X86::GR8RegisterClass, true);
12561   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12562   // This group is for 64-bit host.
12563   case X86::ATOMAND64:
12564     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12565                                                X86::AND64ri32, X86::MOV64rm,
12566                                                X86::LCMPXCHG64,
12567                                                X86::NOT64r, X86::RAX,
12568                                                X86::GR64RegisterClass);
12569   case X86::ATOMOR64:
12570     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12571                                                X86::OR64ri32, X86::MOV64rm,
12572                                                X86::LCMPXCHG64,
12573                                                X86::NOT64r, X86::RAX,
12574                                                X86::GR64RegisterClass);
12575   case X86::ATOMXOR64:
12576     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12577                                                X86::XOR64ri32, X86::MOV64rm,
12578                                                X86::LCMPXCHG64,
12579                                                X86::NOT64r, X86::RAX,
12580                                                X86::GR64RegisterClass);
12581   case X86::ATOMNAND64:
12582     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12583                                                X86::AND64ri32, X86::MOV64rm,
12584                                                X86::LCMPXCHG64,
12585                                                X86::NOT64r, X86::RAX,
12586                                                X86::GR64RegisterClass, true);
12587   case X86::ATOMMIN64:
12588     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12589   case X86::ATOMMAX64:
12590     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12591   case X86::ATOMUMIN64:
12592     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12593   case X86::ATOMUMAX64:
12594     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12595
12596   // This group does 64-bit operations on a 32-bit host.
12597   case X86::ATOMAND6432:
12598     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12599                                                X86::AND32rr, X86::AND32rr,
12600                                                X86::AND32ri, X86::AND32ri,
12601                                                false);
12602   case X86::ATOMOR6432:
12603     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12604                                                X86::OR32rr, X86::OR32rr,
12605                                                X86::OR32ri, X86::OR32ri,
12606                                                false);
12607   case X86::ATOMXOR6432:
12608     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12609                                                X86::XOR32rr, X86::XOR32rr,
12610                                                X86::XOR32ri, X86::XOR32ri,
12611                                                false);
12612   case X86::ATOMNAND6432:
12613     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12614                                                X86::AND32rr, X86::AND32rr,
12615                                                X86::AND32ri, X86::AND32ri,
12616                                                true);
12617   case X86::ATOMADD6432:
12618     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12619                                                X86::ADD32rr, X86::ADC32rr,
12620                                                X86::ADD32ri, X86::ADC32ri,
12621                                                false);
12622   case X86::ATOMSUB6432:
12623     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12624                                                X86::SUB32rr, X86::SBB32rr,
12625                                                X86::SUB32ri, X86::SBB32ri,
12626                                                false);
12627   case X86::ATOMSWAP6432:
12628     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12629                                                X86::MOV32rr, X86::MOV32rr,
12630                                                X86::MOV32ri, X86::MOV32ri,
12631                                                false);
12632   case X86::VASTART_SAVE_XMM_REGS:
12633     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12634
12635   case X86::VAARG_64:
12636     return EmitVAARG64WithCustomInserter(MI, BB);
12637   }
12638 }
12639
12640 //===----------------------------------------------------------------------===//
12641 //                           X86 Optimization Hooks
12642 //===----------------------------------------------------------------------===//
12643
12644 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12645                                                        const APInt &Mask,
12646                                                        APInt &KnownZero,
12647                                                        APInt &KnownOne,
12648                                                        const SelectionDAG &DAG,
12649                                                        unsigned Depth) const {
12650   unsigned Opc = Op.getOpcode();
12651   assert((Opc >= ISD::BUILTIN_OP_END ||
12652           Opc == ISD::INTRINSIC_WO_CHAIN ||
12653           Opc == ISD::INTRINSIC_W_CHAIN ||
12654           Opc == ISD::INTRINSIC_VOID) &&
12655          "Should use MaskedValueIsZero if you don't know whether Op"
12656          " is a target node!");
12657
12658   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12659   switch (Opc) {
12660   default: break;
12661   case X86ISD::ADD:
12662   case X86ISD::SUB:
12663   case X86ISD::ADC:
12664   case X86ISD::SBB:
12665   case X86ISD::SMUL:
12666   case X86ISD::UMUL:
12667   case X86ISD::INC:
12668   case X86ISD::DEC:
12669   case X86ISD::OR:
12670   case X86ISD::XOR:
12671   case X86ISD::AND:
12672     // These nodes' second result is a boolean.
12673     if (Op.getResNo() == 0)
12674       break;
12675     // Fallthrough
12676   case X86ISD::SETCC:
12677     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12678                                        Mask.getBitWidth() - 1);
12679     break;
12680   case ISD::INTRINSIC_WO_CHAIN: {
12681     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12682     unsigned NumLoBits = 0;
12683     switch (IntId) {
12684     default: break;
12685     case Intrinsic::x86_sse_movmsk_ps:
12686     case Intrinsic::x86_avx_movmsk_ps_256:
12687     case Intrinsic::x86_sse2_movmsk_pd:
12688     case Intrinsic::x86_avx_movmsk_pd_256:
12689     case Intrinsic::x86_mmx_pmovmskb:
12690     case Intrinsic::x86_sse2_pmovmskb_128:
12691     case Intrinsic::x86_avx2_pmovmskb: {
12692       // High bits of movmskp{s|d}, pmovmskb are known zero.
12693       switch (IntId) {
12694         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12695         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12696         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12697         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12698         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12699         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12700         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12701         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12702       }
12703       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12704                                         Mask.getBitWidth() - NumLoBits);
12705       break;
12706     }
12707     }
12708     break;
12709   }
12710   }
12711 }
12712
12713 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12714                                                          unsigned Depth) const {
12715   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12716   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12717     return Op.getValueType().getScalarType().getSizeInBits();
12718
12719   // Fallback case.
12720   return 1;
12721 }
12722
12723 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12724 /// node is a GlobalAddress + offset.
12725 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12726                                        const GlobalValue* &GA,
12727                                        int64_t &Offset) const {
12728   if (N->getOpcode() == X86ISD::Wrapper) {
12729     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12730       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12731       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12732       return true;
12733     }
12734   }
12735   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12736 }
12737
12738 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12739 /// same as extracting the high 128-bit part of 256-bit vector and then
12740 /// inserting the result into the low part of a new 256-bit vector
12741 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12742   EVT VT = SVOp->getValueType(0);
12743   int NumElems = VT.getVectorNumElements();
12744
12745   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12746   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12747     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12748         SVOp->getMaskElt(j) >= 0)
12749       return false;
12750
12751   return true;
12752 }
12753
12754 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12755 /// same as extracting the low 128-bit part of 256-bit vector and then
12756 /// inserting the result into the high part of a new 256-bit vector
12757 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12758   EVT VT = SVOp->getValueType(0);
12759   int NumElems = VT.getVectorNumElements();
12760
12761   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12762   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12763     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12764         SVOp->getMaskElt(j) >= 0)
12765       return false;
12766
12767   return true;
12768 }
12769
12770 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12771 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12772                                         TargetLowering::DAGCombinerInfo &DCI,
12773                                         const X86Subtarget* Subtarget) {
12774   DebugLoc dl = N->getDebugLoc();
12775   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12776   SDValue V1 = SVOp->getOperand(0);
12777   SDValue V2 = SVOp->getOperand(1);
12778   EVT VT = SVOp->getValueType(0);
12779   int NumElems = VT.getVectorNumElements();
12780
12781   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12782       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12783     //
12784     //                   0,0,0,...
12785     //                      |
12786     //    V      UNDEF    BUILD_VECTOR    UNDEF
12787     //     \      /           \           /
12788     //  CONCAT_VECTOR         CONCAT_VECTOR
12789     //         \                  /
12790     //          \                /
12791     //          RESULT: V + zero extended
12792     //
12793     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12794         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12795         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12796       return SDValue();
12797
12798     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12799       return SDValue();
12800
12801     // To match the shuffle mask, the first half of the mask should
12802     // be exactly the first vector, and all the rest a splat with the
12803     // first element of the second one.
12804     for (int i = 0; i < NumElems/2; ++i)
12805       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12806           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12807         return SDValue();
12808
12809     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12810     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12811       SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12812       SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12813       SDValue ResNode =
12814         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12815                                 Ld->getMemoryVT(),
12816                                 Ld->getPointerInfo(),
12817                                 Ld->getAlignment(),
12818                                 false/*isVolatile*/, true/*ReadMem*/,
12819                                 false/*WriteMem*/);
12820       return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12821     } 
12822
12823     // Emit a zeroed vector and insert the desired subvector on its
12824     // first half.
12825     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12826     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12827                          DAG.getConstant(0, MVT::i32), DAG, dl);
12828     return DCI.CombineTo(N, InsV);
12829   }
12830
12831   //===--------------------------------------------------------------------===//
12832   // Combine some shuffles into subvector extracts and inserts:
12833   //
12834
12835   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12836   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12837     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12838                                     DAG, dl);
12839     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12840                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12841     return DCI.CombineTo(N, InsV);
12842   }
12843
12844   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12845   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12846     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12847     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12848                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12849     return DCI.CombineTo(N, InsV);
12850   }
12851
12852   return SDValue();
12853 }
12854
12855 /// PerformShuffleCombine - Performs several different shuffle combines.
12856 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12857                                      TargetLowering::DAGCombinerInfo &DCI,
12858                                      const X86Subtarget *Subtarget) {
12859   DebugLoc dl = N->getDebugLoc();
12860   EVT VT = N->getValueType(0);
12861
12862   // Don't create instructions with illegal types after legalize types has run.
12863   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12864   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12865     return SDValue();
12866
12867   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12868   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12869       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12870     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
12871
12872   // Only handle 128 wide vector from here on.
12873   if (VT.getSizeInBits() != 128)
12874     return SDValue();
12875
12876   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12877   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12878   // consecutive, non-overlapping, and in the right order.
12879   SmallVector<SDValue, 16> Elts;
12880   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12881     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12882
12883   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12884 }
12885
12886
12887 /// PerformTruncateCombine - Converts truncate operation to
12888 /// a sequence of vector shuffle operations.
12889 /// It is possible when we truncate 256-bit vector to 128-bit vector
12890
12891 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
12892                                                   DAGCombinerInfo &DCI) const {
12893   if (!DCI.isBeforeLegalizeOps())
12894     return SDValue();
12895
12896   if (!Subtarget->hasAVX()) return SDValue();
12897
12898   EVT VT = N->getValueType(0);
12899   SDValue Op = N->getOperand(0);
12900   EVT OpVT = Op.getValueType();
12901   DebugLoc dl = N->getDebugLoc();
12902
12903   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
12904
12905     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
12906                           DAG.getIntPtrConstant(0));
12907
12908     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
12909                           DAG.getIntPtrConstant(2));
12910
12911     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
12912     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
12913
12914     // PSHUFD
12915     int ShufMask1[] = {0, 2, 0, 0};
12916
12917     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT),
12918                                 ShufMask1);
12919     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT),
12920                                 ShufMask1);
12921
12922     // MOVLHPS
12923     int ShufMask2[] = {0, 1, 4, 5};
12924
12925     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
12926   }
12927   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
12928
12929     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
12930                           DAG.getIntPtrConstant(0));
12931
12932     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
12933                           DAG.getIntPtrConstant(4));
12934
12935     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
12936     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
12937
12938     // PSHUFB
12939     int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13, 
12940                       -1, -1, -1, -1, -1, -1, -1, -1};
12941
12942     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo,
12943                                 DAG.getUNDEF(MVT::v16i8),
12944                                 ShufMask1);
12945     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi,
12946                                 DAG.getUNDEF(MVT::v16i8),
12947                                 ShufMask1);
12948
12949     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
12950     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
12951
12952     // MOVLHPS
12953     int ShufMask2[] = {0, 1, 4, 5};
12954
12955     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
12956     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
12957   }
12958
12959   return SDValue();
12960 }
12961
12962 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12963 /// generation and convert it from being a bunch of shuffles and extracts
12964 /// to a simple store and scalar loads to extract the elements.
12965 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12966                                                 const TargetLowering &TLI) {
12967   SDValue InputVector = N->getOperand(0);
12968
12969   // Only operate on vectors of 4 elements, where the alternative shuffling
12970   // gets to be more expensive.
12971   if (InputVector.getValueType() != MVT::v4i32)
12972     return SDValue();
12973
12974   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12975   // single use which is a sign-extend or zero-extend, and all elements are
12976   // used.
12977   SmallVector<SDNode *, 4> Uses;
12978   unsigned ExtractedElements = 0;
12979   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12980        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12981     if (UI.getUse().getResNo() != InputVector.getResNo())
12982       return SDValue();
12983
12984     SDNode *Extract = *UI;
12985     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12986       return SDValue();
12987
12988     if (Extract->getValueType(0) != MVT::i32)
12989       return SDValue();
12990     if (!Extract->hasOneUse())
12991       return SDValue();
12992     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12993         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12994       return SDValue();
12995     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12996       return SDValue();
12997
12998     // Record which element was extracted.
12999     ExtractedElements |=
13000       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13001
13002     Uses.push_back(Extract);
13003   }
13004
13005   // If not all the elements were used, this may not be worthwhile.
13006   if (ExtractedElements != 15)
13007     return SDValue();
13008
13009   // Ok, we've now decided to do the transformation.
13010   DebugLoc dl = InputVector.getDebugLoc();
13011
13012   // Store the value to a temporary stack slot.
13013   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13014   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13015                             MachinePointerInfo(), false, false, 0);
13016
13017   // Replace each use (extract) with a load of the appropriate element.
13018   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13019        UE = Uses.end(); UI != UE; ++UI) {
13020     SDNode *Extract = *UI;
13021
13022     // cOMpute the element's address.
13023     SDValue Idx = Extract->getOperand(1);
13024     unsigned EltSize =
13025         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13026     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13027     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13028
13029     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13030                                      StackPtr, OffsetVal);
13031
13032     // Load the scalar.
13033     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13034                                      ScalarAddr, MachinePointerInfo(),
13035                                      false, false, false, 0);
13036
13037     // Replace the exact with the load.
13038     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13039   }
13040
13041   // The replacement was made in place; don't return anything.
13042   return SDValue();
13043 }
13044
13045 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13046 /// nodes.
13047 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13048                                     TargetLowering::DAGCombinerInfo &DCI,
13049                                     const X86Subtarget *Subtarget) {
13050   DebugLoc DL = N->getDebugLoc();
13051   SDValue Cond = N->getOperand(0);
13052   // Get the LHS/RHS of the select.
13053   SDValue LHS = N->getOperand(1);
13054   SDValue RHS = N->getOperand(2);
13055   EVT VT = LHS.getValueType();
13056
13057   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13058   // instructions match the semantics of the common C idiom x<y?x:y but not
13059   // x<=y?x:y, because of how they handle negative zero (which can be
13060   // ignored in unsafe-math mode).
13061   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13062       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13063       (Subtarget->hasSSE2() ||
13064        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13065     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13066
13067     unsigned Opcode = 0;
13068     // Check for x CC y ? x : y.
13069     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13070         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13071       switch (CC) {
13072       default: break;
13073       case ISD::SETULT:
13074         // Converting this to a min would handle NaNs incorrectly, and swapping
13075         // the operands would cause it to handle comparisons between positive
13076         // and negative zero incorrectly.
13077         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13078           if (!DAG.getTarget().Options.UnsafeFPMath &&
13079               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13080             break;
13081           std::swap(LHS, RHS);
13082         }
13083         Opcode = X86ISD::FMIN;
13084         break;
13085       case ISD::SETOLE:
13086         // Converting this to a min would handle comparisons between positive
13087         // and negative zero incorrectly.
13088         if (!DAG.getTarget().Options.UnsafeFPMath &&
13089             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13090           break;
13091         Opcode = X86ISD::FMIN;
13092         break;
13093       case ISD::SETULE:
13094         // Converting this to a min would handle both negative zeros and NaNs
13095         // incorrectly, but we can swap the operands to fix both.
13096         std::swap(LHS, RHS);
13097       case ISD::SETOLT:
13098       case ISD::SETLT:
13099       case ISD::SETLE:
13100         Opcode = X86ISD::FMIN;
13101         break;
13102
13103       case ISD::SETOGE:
13104         // Converting this to a max would handle comparisons between positive
13105         // and negative zero incorrectly.
13106         if (!DAG.getTarget().Options.UnsafeFPMath &&
13107             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13108           break;
13109         Opcode = X86ISD::FMAX;
13110         break;
13111       case ISD::SETUGT:
13112         // Converting this to a max would handle NaNs incorrectly, and swapping
13113         // the operands would cause it to handle comparisons between positive
13114         // and negative zero incorrectly.
13115         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13116           if (!DAG.getTarget().Options.UnsafeFPMath &&
13117               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13118             break;
13119           std::swap(LHS, RHS);
13120         }
13121         Opcode = X86ISD::FMAX;
13122         break;
13123       case ISD::SETUGE:
13124         // Converting this to a max would handle both negative zeros and NaNs
13125         // incorrectly, but we can swap the operands to fix both.
13126         std::swap(LHS, RHS);
13127       case ISD::SETOGT:
13128       case ISD::SETGT:
13129       case ISD::SETGE:
13130         Opcode = X86ISD::FMAX;
13131         break;
13132       }
13133     // Check for x CC y ? y : x -- a min/max with reversed arms.
13134     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13135                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13136       switch (CC) {
13137       default: break;
13138       case ISD::SETOGE:
13139         // Converting this to a min would handle comparisons between positive
13140         // and negative zero incorrectly, and swapping the operands would
13141         // cause it to handle NaNs incorrectly.
13142         if (!DAG.getTarget().Options.UnsafeFPMath &&
13143             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13144           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13145             break;
13146           std::swap(LHS, RHS);
13147         }
13148         Opcode = X86ISD::FMIN;
13149         break;
13150       case ISD::SETUGT:
13151         // Converting this to a min would handle NaNs incorrectly.
13152         if (!DAG.getTarget().Options.UnsafeFPMath &&
13153             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13154           break;
13155         Opcode = X86ISD::FMIN;
13156         break;
13157       case ISD::SETUGE:
13158         // Converting this to a min would handle both negative zeros and NaNs
13159         // incorrectly, but we can swap the operands to fix both.
13160         std::swap(LHS, RHS);
13161       case ISD::SETOGT:
13162       case ISD::SETGT:
13163       case ISD::SETGE:
13164         Opcode = X86ISD::FMIN;
13165         break;
13166
13167       case ISD::SETULT:
13168         // Converting this to a max would handle NaNs incorrectly.
13169         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13170           break;
13171         Opcode = X86ISD::FMAX;
13172         break;
13173       case ISD::SETOLE:
13174         // Converting this to a max would handle comparisons between positive
13175         // and negative zero incorrectly, and swapping the operands would
13176         // cause it to handle NaNs incorrectly.
13177         if (!DAG.getTarget().Options.UnsafeFPMath &&
13178             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13179           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13180             break;
13181           std::swap(LHS, RHS);
13182         }
13183         Opcode = X86ISD::FMAX;
13184         break;
13185       case ISD::SETULE:
13186         // Converting this to a max would handle both negative zeros and NaNs
13187         // incorrectly, but we can swap the operands to fix both.
13188         std::swap(LHS, RHS);
13189       case ISD::SETOLT:
13190       case ISD::SETLT:
13191       case ISD::SETLE:
13192         Opcode = X86ISD::FMAX;
13193         break;
13194       }
13195     }
13196
13197     if (Opcode)
13198       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13199   }
13200
13201   // If this is a select between two integer constants, try to do some
13202   // optimizations.
13203   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13204     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13205       // Don't do this for crazy integer types.
13206       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13207         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13208         // so that TrueC (the true value) is larger than FalseC.
13209         bool NeedsCondInvert = false;
13210
13211         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13212             // Efficiently invertible.
13213             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13214              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13215               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13216           NeedsCondInvert = true;
13217           std::swap(TrueC, FalseC);
13218         }
13219
13220         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13221         if (FalseC->getAPIntValue() == 0 &&
13222             TrueC->getAPIntValue().isPowerOf2()) {
13223           if (NeedsCondInvert) // Invert the condition if needed.
13224             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13225                                DAG.getConstant(1, Cond.getValueType()));
13226
13227           // Zero extend the condition if needed.
13228           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13229
13230           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13231           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13232                              DAG.getConstant(ShAmt, MVT::i8));
13233         }
13234
13235         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13236         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13237           if (NeedsCondInvert) // Invert the condition if needed.
13238             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13239                                DAG.getConstant(1, Cond.getValueType()));
13240
13241           // Zero extend the condition if needed.
13242           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13243                              FalseC->getValueType(0), Cond);
13244           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13245                              SDValue(FalseC, 0));
13246         }
13247
13248         // Optimize cases that will turn into an LEA instruction.  This requires
13249         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13250         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13251           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13252           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13253
13254           bool isFastMultiplier = false;
13255           if (Diff < 10) {
13256             switch ((unsigned char)Diff) {
13257               default: break;
13258               case 1:  // result = add base, cond
13259               case 2:  // result = lea base(    , cond*2)
13260               case 3:  // result = lea base(cond, cond*2)
13261               case 4:  // result = lea base(    , cond*4)
13262               case 5:  // result = lea base(cond, cond*4)
13263               case 8:  // result = lea base(    , cond*8)
13264               case 9:  // result = lea base(cond, cond*8)
13265                 isFastMultiplier = true;
13266                 break;
13267             }
13268           }
13269
13270           if (isFastMultiplier) {
13271             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13272             if (NeedsCondInvert) // Invert the condition if needed.
13273               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13274                                  DAG.getConstant(1, Cond.getValueType()));
13275
13276             // Zero extend the condition if needed.
13277             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13278                                Cond);
13279             // Scale the condition by the difference.
13280             if (Diff != 1)
13281               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13282                                  DAG.getConstant(Diff, Cond.getValueType()));
13283
13284             // Add the base if non-zero.
13285             if (FalseC->getAPIntValue() != 0)
13286               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13287                                  SDValue(FalseC, 0));
13288             return Cond;
13289           }
13290         }
13291       }
13292   }
13293
13294   // Canonicalize max and min:
13295   // (x > y) ? x : y -> (x >= y) ? x : y
13296   // (x < y) ? x : y -> (x <= y) ? x : y
13297   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13298   // the need for an extra compare
13299   // against zero. e.g.
13300   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13301   // subl   %esi, %edi
13302   // testl  %edi, %edi
13303   // movl   $0, %eax
13304   // cmovgl %edi, %eax
13305   // =>
13306   // xorl   %eax, %eax
13307   // subl   %esi, $edi
13308   // cmovsl %eax, %edi
13309   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13310       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13311       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13312     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13313     switch (CC) {
13314     default: break;
13315     case ISD::SETLT:
13316     case ISD::SETGT: {
13317       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13318       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13319                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13320       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13321     }
13322     }
13323   }
13324
13325   // If we know that this node is legal then we know that it is going to be
13326   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13327   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13328   // to simplify previous instructions.
13329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13330   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13331       !DCI.isBeforeLegalize() &&
13332       TLI.isOperationLegal(ISD::VSELECT, VT)) {
13333     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13334     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13335     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13336
13337     APInt KnownZero, KnownOne;
13338     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13339                                           DCI.isBeforeLegalizeOps());
13340     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13341         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13342       DCI.CommitTargetLoweringOpt(TLO);
13343   }
13344
13345   return SDValue();
13346 }
13347
13348 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13349 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13350                                   TargetLowering::DAGCombinerInfo &DCI) {
13351   DebugLoc DL = N->getDebugLoc();
13352
13353   // If the flag operand isn't dead, don't touch this CMOV.
13354   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13355     return SDValue();
13356
13357   SDValue FalseOp = N->getOperand(0);
13358   SDValue TrueOp = N->getOperand(1);
13359   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13360   SDValue Cond = N->getOperand(3);
13361   if (CC == X86::COND_E || CC == X86::COND_NE) {
13362     switch (Cond.getOpcode()) {
13363     default: break;
13364     case X86ISD::BSR:
13365     case X86ISD::BSF:
13366       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13367       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13368         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13369     }
13370   }
13371
13372   // If this is a select between two integer constants, try to do some
13373   // optimizations.  Note that the operands are ordered the opposite of SELECT
13374   // operands.
13375   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13376     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13377       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13378       // larger than FalseC (the false value).
13379       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13380         CC = X86::GetOppositeBranchCondition(CC);
13381         std::swap(TrueC, FalseC);
13382       }
13383
13384       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13385       // This is efficient for any integer data type (including i8/i16) and
13386       // shift amount.
13387       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13388         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13389                            DAG.getConstant(CC, MVT::i8), Cond);
13390
13391         // Zero extend the condition if needed.
13392         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13393
13394         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13395         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13396                            DAG.getConstant(ShAmt, MVT::i8));
13397         if (N->getNumValues() == 2)  // Dead flag value?
13398           return DCI.CombineTo(N, Cond, SDValue());
13399         return Cond;
13400       }
13401
13402       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13403       // for any integer data type, including i8/i16.
13404       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13405         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13406                            DAG.getConstant(CC, MVT::i8), Cond);
13407
13408         // Zero extend the condition if needed.
13409         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13410                            FalseC->getValueType(0), Cond);
13411         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13412                            SDValue(FalseC, 0));
13413
13414         if (N->getNumValues() == 2)  // Dead flag value?
13415           return DCI.CombineTo(N, Cond, SDValue());
13416         return Cond;
13417       }
13418
13419       // Optimize cases that will turn into an LEA instruction.  This requires
13420       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13421       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13422         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13423         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13424
13425         bool isFastMultiplier = false;
13426         if (Diff < 10) {
13427           switch ((unsigned char)Diff) {
13428           default: break;
13429           case 1:  // result = add base, cond
13430           case 2:  // result = lea base(    , cond*2)
13431           case 3:  // result = lea base(cond, cond*2)
13432           case 4:  // result = lea base(    , cond*4)
13433           case 5:  // result = lea base(cond, cond*4)
13434           case 8:  // result = lea base(    , cond*8)
13435           case 9:  // result = lea base(cond, cond*8)
13436             isFastMultiplier = true;
13437             break;
13438           }
13439         }
13440
13441         if (isFastMultiplier) {
13442           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13443           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13444                              DAG.getConstant(CC, MVT::i8), Cond);
13445           // Zero extend the condition if needed.
13446           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13447                              Cond);
13448           // Scale the condition by the difference.
13449           if (Diff != 1)
13450             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13451                                DAG.getConstant(Diff, Cond.getValueType()));
13452
13453           // Add the base if non-zero.
13454           if (FalseC->getAPIntValue() != 0)
13455             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13456                                SDValue(FalseC, 0));
13457           if (N->getNumValues() == 2)  // Dead flag value?
13458             return DCI.CombineTo(N, Cond, SDValue());
13459           return Cond;
13460         }
13461       }
13462     }
13463   }
13464   return SDValue();
13465 }
13466
13467
13468 /// PerformMulCombine - Optimize a single multiply with constant into two
13469 /// in order to implement it with two cheaper instructions, e.g.
13470 /// LEA + SHL, LEA + LEA.
13471 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13472                                  TargetLowering::DAGCombinerInfo &DCI) {
13473   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13474     return SDValue();
13475
13476   EVT VT = N->getValueType(0);
13477   if (VT != MVT::i64)
13478     return SDValue();
13479
13480   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13481   if (!C)
13482     return SDValue();
13483   uint64_t MulAmt = C->getZExtValue();
13484   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13485     return SDValue();
13486
13487   uint64_t MulAmt1 = 0;
13488   uint64_t MulAmt2 = 0;
13489   if ((MulAmt % 9) == 0) {
13490     MulAmt1 = 9;
13491     MulAmt2 = MulAmt / 9;
13492   } else if ((MulAmt % 5) == 0) {
13493     MulAmt1 = 5;
13494     MulAmt2 = MulAmt / 5;
13495   } else if ((MulAmt % 3) == 0) {
13496     MulAmt1 = 3;
13497     MulAmt2 = MulAmt / 3;
13498   }
13499   if (MulAmt2 &&
13500       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13501     DebugLoc DL = N->getDebugLoc();
13502
13503     if (isPowerOf2_64(MulAmt2) &&
13504         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13505       // If second multiplifer is pow2, issue it first. We want the multiply by
13506       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13507       // is an add.
13508       std::swap(MulAmt1, MulAmt2);
13509
13510     SDValue NewMul;
13511     if (isPowerOf2_64(MulAmt1))
13512       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13513                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13514     else
13515       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13516                            DAG.getConstant(MulAmt1, VT));
13517
13518     if (isPowerOf2_64(MulAmt2))
13519       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13520                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13521     else
13522       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13523                            DAG.getConstant(MulAmt2, VT));
13524
13525     // Do not add new nodes to DAG combiner worklist.
13526     DCI.CombineTo(N, NewMul, false);
13527   }
13528   return SDValue();
13529 }
13530
13531 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13532   SDValue N0 = N->getOperand(0);
13533   SDValue N1 = N->getOperand(1);
13534   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13535   EVT VT = N0.getValueType();
13536
13537   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13538   // since the result of setcc_c is all zero's or all ones.
13539   if (VT.isInteger() && !VT.isVector() &&
13540       N1C && N0.getOpcode() == ISD::AND &&
13541       N0.getOperand(1).getOpcode() == ISD::Constant) {
13542     SDValue N00 = N0.getOperand(0);
13543     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13544         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13545           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13546          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13547       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13548       APInt ShAmt = N1C->getAPIntValue();
13549       Mask = Mask.shl(ShAmt);
13550       if (Mask != 0)
13551         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13552                            N00, DAG.getConstant(Mask, VT));
13553     }
13554   }
13555
13556
13557   // Hardware support for vector shifts is sparse which makes us scalarize the
13558   // vector operations in many cases. Also, on sandybridge ADD is faster than
13559   // shl.
13560   // (shl V, 1) -> add V,V
13561   if (isSplatVector(N1.getNode())) {
13562     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13563     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13564     // We shift all of the values by one. In many cases we do not have
13565     // hardware support for this operation. This is better expressed as an ADD
13566     // of two values.
13567     if (N1C && (1 == N1C->getZExtValue())) {
13568       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13569     }
13570   }
13571
13572   return SDValue();
13573 }
13574
13575 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13576 ///                       when possible.
13577 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13578                                    TargetLowering::DAGCombinerInfo &DCI,
13579                                    const X86Subtarget *Subtarget) {
13580   EVT VT = N->getValueType(0);
13581   if (N->getOpcode() == ISD::SHL) {
13582     SDValue V = PerformSHLCombine(N, DAG);
13583     if (V.getNode()) return V;
13584   }
13585
13586   // On X86 with SSE2 support, we can transform this to a vector shift if
13587   // all elements are shifted by the same amount.  We can't do this in legalize
13588   // because the a constant vector is typically transformed to a constant pool
13589   // so we have no knowledge of the shift amount.
13590   if (!Subtarget->hasSSE2())
13591     return SDValue();
13592
13593   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13594       (!Subtarget->hasAVX2() ||
13595        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13596     return SDValue();
13597
13598   SDValue ShAmtOp = N->getOperand(1);
13599   EVT EltVT = VT.getVectorElementType();
13600   DebugLoc DL = N->getDebugLoc();
13601   SDValue BaseShAmt = SDValue();
13602   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13603     unsigned NumElts = VT.getVectorNumElements();
13604     unsigned i = 0;
13605     for (; i != NumElts; ++i) {
13606       SDValue Arg = ShAmtOp.getOperand(i);
13607       if (Arg.getOpcode() == ISD::UNDEF) continue;
13608       BaseShAmt = Arg;
13609       break;
13610     }
13611     // Handle the case where the build_vector is all undef
13612     // FIXME: Should DAG allow this?
13613     if (i == NumElts)
13614       return SDValue();
13615
13616     for (; i != NumElts; ++i) {
13617       SDValue Arg = ShAmtOp.getOperand(i);
13618       if (Arg.getOpcode() == ISD::UNDEF) continue;
13619       if (Arg != BaseShAmt) {
13620         return SDValue();
13621       }
13622     }
13623   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13624              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13625     SDValue InVec = ShAmtOp.getOperand(0);
13626     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13627       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13628       unsigned i = 0;
13629       for (; i != NumElts; ++i) {
13630         SDValue Arg = InVec.getOperand(i);
13631         if (Arg.getOpcode() == ISD::UNDEF) continue;
13632         BaseShAmt = Arg;
13633         break;
13634       }
13635     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13636        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13637          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13638          if (C->getZExtValue() == SplatIdx)
13639            BaseShAmt = InVec.getOperand(1);
13640        }
13641     }
13642     if (BaseShAmt.getNode() == 0) {
13643       // Don't create instructions with illegal types after legalize
13644       // types has run.
13645       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13646           !DCI.isBeforeLegalize())
13647         return SDValue();
13648
13649       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13650                               DAG.getIntPtrConstant(0));
13651     }
13652   } else
13653     return SDValue();
13654
13655   // The shift amount is an i32.
13656   if (EltVT.bitsGT(MVT::i32))
13657     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13658   else if (EltVT.bitsLT(MVT::i32))
13659     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13660
13661   // The shift amount is identical so we can do a vector shift.
13662   SDValue  ValOp = N->getOperand(0);
13663   switch (N->getOpcode()) {
13664   default:
13665     llvm_unreachable("Unknown shift opcode!");
13666   case ISD::SHL:
13667     switch (VT.getSimpleVT().SimpleTy) {
13668     default: return SDValue();
13669     case MVT::v2i64:
13670     case MVT::v4i32:
13671     case MVT::v8i16:
13672     case MVT::v4i64:
13673     case MVT::v8i32:
13674     case MVT::v16i16:
13675       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13676     }
13677   case ISD::SRA:
13678     switch (VT.getSimpleVT().SimpleTy) {
13679     default: return SDValue();
13680     case MVT::v4i32:
13681     case MVT::v8i16:
13682     case MVT::v8i32:
13683     case MVT::v16i16:
13684       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
13685     }
13686   case ISD::SRL:
13687     switch (VT.getSimpleVT().SimpleTy) {
13688     default: return SDValue();
13689     case MVT::v2i64:
13690     case MVT::v4i32:
13691     case MVT::v8i16:
13692     case MVT::v4i64:
13693     case MVT::v8i32:
13694     case MVT::v16i16:
13695       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
13696     }
13697   }
13698 }
13699
13700
13701 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13702 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13703 // and friends.  Likewise for OR -> CMPNEQSS.
13704 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13705                             TargetLowering::DAGCombinerInfo &DCI,
13706                             const X86Subtarget *Subtarget) {
13707   unsigned opcode;
13708
13709   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13710   // we're requiring SSE2 for both.
13711   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13712     SDValue N0 = N->getOperand(0);
13713     SDValue N1 = N->getOperand(1);
13714     SDValue CMP0 = N0->getOperand(1);
13715     SDValue CMP1 = N1->getOperand(1);
13716     DebugLoc DL = N->getDebugLoc();
13717
13718     // The SETCCs should both refer to the same CMP.
13719     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13720       return SDValue();
13721
13722     SDValue CMP00 = CMP0->getOperand(0);
13723     SDValue CMP01 = CMP0->getOperand(1);
13724     EVT     VT    = CMP00.getValueType();
13725
13726     if (VT == MVT::f32 || VT == MVT::f64) {
13727       bool ExpectingFlags = false;
13728       // Check for any users that want flags:
13729       for (SDNode::use_iterator UI = N->use_begin(),
13730              UE = N->use_end();
13731            !ExpectingFlags && UI != UE; ++UI)
13732         switch (UI->getOpcode()) {
13733         default:
13734         case ISD::BR_CC:
13735         case ISD::BRCOND:
13736         case ISD::SELECT:
13737           ExpectingFlags = true;
13738           break;
13739         case ISD::CopyToReg:
13740         case ISD::SIGN_EXTEND:
13741         case ISD::ZERO_EXTEND:
13742         case ISD::ANY_EXTEND:
13743           break;
13744         }
13745
13746       if (!ExpectingFlags) {
13747         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13748         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13749
13750         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13751           X86::CondCode tmp = cc0;
13752           cc0 = cc1;
13753           cc1 = tmp;
13754         }
13755
13756         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13757             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13758           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13759           X86ISD::NodeType NTOperator = is64BitFP ?
13760             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13761           // FIXME: need symbolic constants for these magic numbers.
13762           // See X86ATTInstPrinter.cpp:printSSECC().
13763           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13764           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13765                                               DAG.getConstant(x86cc, MVT::i8));
13766           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13767                                               OnesOrZeroesF);
13768           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13769                                       DAG.getConstant(1, MVT::i32));
13770           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13771           return OneBitOfTruth;
13772         }
13773       }
13774     }
13775   }
13776   return SDValue();
13777 }
13778
13779 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13780 /// so it can be folded inside ANDNP.
13781 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13782   EVT VT = N->getValueType(0);
13783
13784   // Match direct AllOnes for 128 and 256-bit vectors
13785   if (ISD::isBuildVectorAllOnes(N))
13786     return true;
13787
13788   // Look through a bit convert.
13789   if (N->getOpcode() == ISD::BITCAST)
13790     N = N->getOperand(0).getNode();
13791
13792   // Sometimes the operand may come from a insert_subvector building a 256-bit
13793   // allones vector
13794   if (VT.getSizeInBits() == 256 &&
13795       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13796     SDValue V1 = N->getOperand(0);
13797     SDValue V2 = N->getOperand(1);
13798
13799     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13800         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13801         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13802         ISD::isBuildVectorAllOnes(V2.getNode()))
13803       return true;
13804   }
13805
13806   return false;
13807 }
13808
13809 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13810                                  TargetLowering::DAGCombinerInfo &DCI,
13811                                  const X86Subtarget *Subtarget) {
13812   if (DCI.isBeforeLegalizeOps())
13813     return SDValue();
13814
13815   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13816   if (R.getNode())
13817     return R;
13818
13819   EVT VT = N->getValueType(0);
13820
13821   // Create ANDN, BLSI, and BLSR instructions
13822   // BLSI is X & (-X)
13823   // BLSR is X & (X-1)
13824   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13825     SDValue N0 = N->getOperand(0);
13826     SDValue N1 = N->getOperand(1);
13827     DebugLoc DL = N->getDebugLoc();
13828
13829     // Check LHS for not
13830     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13831       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13832     // Check RHS for not
13833     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13834       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13835
13836     // Check LHS for neg
13837     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13838         isZero(N0.getOperand(0)))
13839       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13840
13841     // Check RHS for neg
13842     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13843         isZero(N1.getOperand(0)))
13844       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13845
13846     // Check LHS for X-1
13847     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13848         isAllOnes(N0.getOperand(1)))
13849       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13850
13851     // Check RHS for X-1
13852     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13853         isAllOnes(N1.getOperand(1)))
13854       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13855
13856     return SDValue();
13857   }
13858
13859   // Want to form ANDNP nodes:
13860   // 1) In the hopes of then easily combining them with OR and AND nodes
13861   //    to form PBLEND/PSIGN.
13862   // 2) To match ANDN packed intrinsics
13863   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13864     return SDValue();
13865
13866   SDValue N0 = N->getOperand(0);
13867   SDValue N1 = N->getOperand(1);
13868   DebugLoc DL = N->getDebugLoc();
13869
13870   // Check LHS for vnot
13871   if (N0.getOpcode() == ISD::XOR &&
13872       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13873       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13874     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13875
13876   // Check RHS for vnot
13877   if (N1.getOpcode() == ISD::XOR &&
13878       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13879       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13880     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13881
13882   return SDValue();
13883 }
13884
13885 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13886                                 TargetLowering::DAGCombinerInfo &DCI,
13887                                 const X86Subtarget *Subtarget) {
13888   if (DCI.isBeforeLegalizeOps())
13889     return SDValue();
13890
13891   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13892   if (R.getNode())
13893     return R;
13894
13895   EVT VT = N->getValueType(0);
13896
13897   SDValue N0 = N->getOperand(0);
13898   SDValue N1 = N->getOperand(1);
13899
13900   // look for psign/blend
13901   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13902     if (!Subtarget->hasSSSE3() ||
13903         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13904       return SDValue();
13905
13906     // Canonicalize pandn to RHS
13907     if (N0.getOpcode() == X86ISD::ANDNP)
13908       std::swap(N0, N1);
13909     // or (and (m, y), (pandn m, x))
13910     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13911       SDValue Mask = N1.getOperand(0);
13912       SDValue X    = N1.getOperand(1);
13913       SDValue Y;
13914       if (N0.getOperand(0) == Mask)
13915         Y = N0.getOperand(1);
13916       if (N0.getOperand(1) == Mask)
13917         Y = N0.getOperand(0);
13918
13919       // Check to see if the mask appeared in both the AND and ANDNP and
13920       if (!Y.getNode())
13921         return SDValue();
13922
13923       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13924       if (Mask.getOpcode() != ISD::BITCAST ||
13925           X.getOpcode() != ISD::BITCAST ||
13926           Y.getOpcode() != ISD::BITCAST)
13927         return SDValue();
13928
13929       // Look through mask bitcast.
13930       Mask = Mask.getOperand(0);
13931       EVT MaskVT = Mask.getValueType();
13932
13933       // Validate that the Mask operand is a vector sra node.
13934       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13935       // there is no psrai.b
13936       if (Mask.getOpcode() != X86ISD::VSRAI)
13937         return SDValue();
13938
13939       // Check that the SRA is all signbits.
13940       SDValue SraC = Mask.getOperand(1);
13941       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13942       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13943       if ((SraAmt + 1) != EltBits)
13944         return SDValue();
13945
13946       DebugLoc DL = N->getDebugLoc();
13947
13948       // Now we know we at least have a plendvb with the mask val.  See if
13949       // we can form a psignb/w/d.
13950       // psign = x.type == y.type == mask.type && y = sub(0, x);
13951       X = X.getOperand(0);
13952       Y = Y.getOperand(0);
13953       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13954           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13955           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
13956         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
13957                "Unsupported VT for PSIGN");
13958         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
13959         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13960       }
13961       // PBLENDVB only available on SSE 4.1
13962       if (!Subtarget->hasSSE41())
13963         return SDValue();
13964
13965       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13966
13967       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13968       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13969       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13970       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13971       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13972     }
13973   }
13974
13975   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13976     return SDValue();
13977
13978   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13979   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13980     std::swap(N0, N1);
13981   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13982     return SDValue();
13983   if (!N0.hasOneUse() || !N1.hasOneUse())
13984     return SDValue();
13985
13986   SDValue ShAmt0 = N0.getOperand(1);
13987   if (ShAmt0.getValueType() != MVT::i8)
13988     return SDValue();
13989   SDValue ShAmt1 = N1.getOperand(1);
13990   if (ShAmt1.getValueType() != MVT::i8)
13991     return SDValue();
13992   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13993     ShAmt0 = ShAmt0.getOperand(0);
13994   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13995     ShAmt1 = ShAmt1.getOperand(0);
13996
13997   DebugLoc DL = N->getDebugLoc();
13998   unsigned Opc = X86ISD::SHLD;
13999   SDValue Op0 = N0.getOperand(0);
14000   SDValue Op1 = N1.getOperand(0);
14001   if (ShAmt0.getOpcode() == ISD::SUB) {
14002     Opc = X86ISD::SHRD;
14003     std::swap(Op0, Op1);
14004     std::swap(ShAmt0, ShAmt1);
14005   }
14006
14007   unsigned Bits = VT.getSizeInBits();
14008   if (ShAmt1.getOpcode() == ISD::SUB) {
14009     SDValue Sum = ShAmt1.getOperand(0);
14010     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14011       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14012       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14013         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14014       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14015         return DAG.getNode(Opc, DL, VT,
14016                            Op0, Op1,
14017                            DAG.getNode(ISD::TRUNCATE, DL,
14018                                        MVT::i8, ShAmt0));
14019     }
14020   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14021     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14022     if (ShAmt0C &&
14023         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14024       return DAG.getNode(Opc, DL, VT,
14025                          N0.getOperand(0), N1.getOperand(0),
14026                          DAG.getNode(ISD::TRUNCATE, DL,
14027                                        MVT::i8, ShAmt0));
14028   }
14029
14030   return SDValue();
14031 }
14032
14033 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14034 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14035                                  TargetLowering::DAGCombinerInfo &DCI,
14036                                  const X86Subtarget *Subtarget) {
14037   if (DCI.isBeforeLegalizeOps())
14038     return SDValue();
14039
14040   EVT VT = N->getValueType(0);
14041
14042   if (VT != MVT::i32 && VT != MVT::i64)
14043     return SDValue();
14044
14045   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14046
14047   // Create BLSMSK instructions by finding X ^ (X-1)
14048   SDValue N0 = N->getOperand(0);
14049   SDValue N1 = N->getOperand(1);
14050   DebugLoc DL = N->getDebugLoc();
14051
14052   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14053       isAllOnes(N0.getOperand(1)))
14054     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14055
14056   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14057       isAllOnes(N1.getOperand(1)))
14058     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14059
14060   return SDValue();
14061 }
14062
14063 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14064 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14065                                    const X86Subtarget *Subtarget) {
14066   LoadSDNode *Ld = cast<LoadSDNode>(N);
14067   EVT RegVT = Ld->getValueType(0);
14068   EVT MemVT = Ld->getMemoryVT();
14069   DebugLoc dl = Ld->getDebugLoc();
14070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14071
14072   ISD::LoadExtType Ext = Ld->getExtensionType();
14073
14074   // If this is a vector EXT Load then attempt to optimize it using a
14075   // shuffle. We need SSE4 for the shuffles.
14076   // TODO: It is possible to support ZExt by zeroing the undef values
14077   // during the shuffle phase or after the shuffle.
14078   if (RegVT.isVector() && RegVT.isInteger() &&
14079       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14080     assert(MemVT != RegVT && "Cannot extend to the same type");
14081     assert(MemVT.isVector() && "Must load a vector from memory");
14082
14083     unsigned NumElems = RegVT.getVectorNumElements();
14084     unsigned RegSz = RegVT.getSizeInBits();
14085     unsigned MemSz = MemVT.getSizeInBits();
14086     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14087     // All sizes must be a power of two
14088     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14089
14090     // Attempt to load the original value using a single load op.
14091     // Find a scalar type which is equal to the loaded word size.
14092     MVT SclrLoadTy = MVT::i8;
14093     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14094          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14095       MVT Tp = (MVT::SimpleValueType)tp;
14096       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14097         SclrLoadTy = Tp;
14098         break;
14099       }
14100     }
14101
14102     // Proceed if a load word is found.
14103     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14104
14105     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14106       RegSz/SclrLoadTy.getSizeInBits());
14107
14108     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14109                                   RegSz/MemVT.getScalarType().getSizeInBits());
14110     // Can't shuffle using an illegal type.
14111     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14112
14113     // Perform a single load.
14114     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14115                                   Ld->getBasePtr(),
14116                                   Ld->getPointerInfo(), Ld->isVolatile(),
14117                                   Ld->isNonTemporal(), Ld->isInvariant(),
14118                                   Ld->getAlignment());
14119
14120     // Insert the word loaded into a vector.
14121     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14122       LoadUnitVecVT, ScalarLoad);
14123
14124     // Bitcast the loaded value to a vector of the original element type, in
14125     // the size of the target vector type.
14126     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14127                                     ScalarInVector);
14128     unsigned SizeRatio = RegSz/MemSz;
14129
14130     // Redistribute the loaded elements into the different locations.
14131     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14132     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14133
14134     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14135                                 DAG.getUNDEF(SlicedVec.getValueType()),
14136                                 ShuffleVec.data());
14137
14138     // Bitcast to the requested type.
14139     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14140     // Replace the original load with the new sequence
14141     // and return the new chain.
14142     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14143     return SDValue(ScalarLoad.getNode(), 1);
14144   }
14145
14146   return SDValue();
14147 }
14148
14149 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14150 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14151                                    const X86Subtarget *Subtarget) {
14152   StoreSDNode *St = cast<StoreSDNode>(N);
14153   EVT VT = St->getValue().getValueType();
14154   EVT StVT = St->getMemoryVT();
14155   DebugLoc dl = St->getDebugLoc();
14156   SDValue StoredVal = St->getOperand(1);
14157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14158
14159   // If we are saving a concatenation of two XMM registers, perform two stores.
14160   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14161   // 128-bit ones. If in the future the cost becomes only one memory access the
14162   // first version would be better.
14163   if (VT.getSizeInBits() == 256 &&
14164     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14165     StoredVal.getNumOperands() == 2) {
14166
14167     SDValue Value0 = StoredVal.getOperand(0);
14168     SDValue Value1 = StoredVal.getOperand(1);
14169
14170     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14171     SDValue Ptr0 = St->getBasePtr();
14172     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14173
14174     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14175                                 St->getPointerInfo(), St->isVolatile(),
14176                                 St->isNonTemporal(), St->getAlignment());
14177     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14178                                 St->getPointerInfo(), St->isVolatile(),
14179                                 St->isNonTemporal(), St->getAlignment());
14180     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14181   }
14182
14183   // Optimize trunc store (of multiple scalars) to shuffle and store.
14184   // First, pack all of the elements in one place. Next, store to memory
14185   // in fewer chunks.
14186   if (St->isTruncatingStore() && VT.isVector()) {
14187     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14188     unsigned NumElems = VT.getVectorNumElements();
14189     assert(StVT != VT && "Cannot truncate to the same type");
14190     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14191     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14192
14193     // From, To sizes and ElemCount must be pow of two
14194     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14195     // We are going to use the original vector elt for storing.
14196     // Accumulated smaller vector elements must be a multiple of the store size.
14197     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14198
14199     unsigned SizeRatio  = FromSz / ToSz;
14200
14201     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14202
14203     // Create a type on which we perform the shuffle
14204     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14205             StVT.getScalarType(), NumElems*SizeRatio);
14206
14207     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14208
14209     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14210     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14211     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14212
14213     // Can't shuffle using an illegal type
14214     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14215
14216     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14217                                 DAG.getUNDEF(WideVec.getValueType()),
14218                                 ShuffleVec.data());
14219     // At this point all of the data is stored at the bottom of the
14220     // register. We now need to save it to mem.
14221
14222     // Find the largest store unit
14223     MVT StoreType = MVT::i8;
14224     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14225          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14226       MVT Tp = (MVT::SimpleValueType)tp;
14227       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14228         StoreType = Tp;
14229     }
14230
14231     // Bitcast the original vector into a vector of store-size units
14232     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14233             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14234     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14235     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14236     SmallVector<SDValue, 8> Chains;
14237     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14238                                         TLI.getPointerTy());
14239     SDValue Ptr = St->getBasePtr();
14240
14241     // Perform one or more big stores into memory.
14242     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14243       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14244                                    StoreType, ShuffWide,
14245                                    DAG.getIntPtrConstant(i));
14246       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14247                                 St->getPointerInfo(), St->isVolatile(),
14248                                 St->isNonTemporal(), St->getAlignment());
14249       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14250       Chains.push_back(Ch);
14251     }
14252
14253     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14254                                Chains.size());
14255   }
14256
14257
14258   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14259   // the FP state in cases where an emms may be missing.
14260   // A preferable solution to the general problem is to figure out the right
14261   // places to insert EMMS.  This qualifies as a quick hack.
14262
14263   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14264   if (VT.getSizeInBits() != 64)
14265     return SDValue();
14266
14267   const Function *F = DAG.getMachineFunction().getFunction();
14268   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14269   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14270                      && Subtarget->hasSSE2();
14271   if ((VT.isVector() ||
14272        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14273       isa<LoadSDNode>(St->getValue()) &&
14274       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14275       St->getChain().hasOneUse() && !St->isVolatile()) {
14276     SDNode* LdVal = St->getValue().getNode();
14277     LoadSDNode *Ld = 0;
14278     int TokenFactorIndex = -1;
14279     SmallVector<SDValue, 8> Ops;
14280     SDNode* ChainVal = St->getChain().getNode();
14281     // Must be a store of a load.  We currently handle two cases:  the load
14282     // is a direct child, and it's under an intervening TokenFactor.  It is
14283     // possible to dig deeper under nested TokenFactors.
14284     if (ChainVal == LdVal)
14285       Ld = cast<LoadSDNode>(St->getChain());
14286     else if (St->getValue().hasOneUse() &&
14287              ChainVal->getOpcode() == ISD::TokenFactor) {
14288       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14289         if (ChainVal->getOperand(i).getNode() == LdVal) {
14290           TokenFactorIndex = i;
14291           Ld = cast<LoadSDNode>(St->getValue());
14292         } else
14293           Ops.push_back(ChainVal->getOperand(i));
14294       }
14295     }
14296
14297     if (!Ld || !ISD::isNormalLoad(Ld))
14298       return SDValue();
14299
14300     // If this is not the MMX case, i.e. we are just turning i64 load/store
14301     // into f64 load/store, avoid the transformation if there are multiple
14302     // uses of the loaded value.
14303     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14304       return SDValue();
14305
14306     DebugLoc LdDL = Ld->getDebugLoc();
14307     DebugLoc StDL = N->getDebugLoc();
14308     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14309     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14310     // pair instead.
14311     if (Subtarget->is64Bit() || F64IsLegal) {
14312       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14313       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14314                                   Ld->getPointerInfo(), Ld->isVolatile(),
14315                                   Ld->isNonTemporal(), Ld->isInvariant(),
14316                                   Ld->getAlignment());
14317       SDValue NewChain = NewLd.getValue(1);
14318       if (TokenFactorIndex != -1) {
14319         Ops.push_back(NewChain);
14320         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14321                                Ops.size());
14322       }
14323       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14324                           St->getPointerInfo(),
14325                           St->isVolatile(), St->isNonTemporal(),
14326                           St->getAlignment());
14327     }
14328
14329     // Otherwise, lower to two pairs of 32-bit loads / stores.
14330     SDValue LoAddr = Ld->getBasePtr();
14331     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14332                                  DAG.getConstant(4, MVT::i32));
14333
14334     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14335                                Ld->getPointerInfo(),
14336                                Ld->isVolatile(), Ld->isNonTemporal(),
14337                                Ld->isInvariant(), Ld->getAlignment());
14338     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14339                                Ld->getPointerInfo().getWithOffset(4),
14340                                Ld->isVolatile(), Ld->isNonTemporal(),
14341                                Ld->isInvariant(),
14342                                MinAlign(Ld->getAlignment(), 4));
14343
14344     SDValue NewChain = LoLd.getValue(1);
14345     if (TokenFactorIndex != -1) {
14346       Ops.push_back(LoLd);
14347       Ops.push_back(HiLd);
14348       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14349                              Ops.size());
14350     }
14351
14352     LoAddr = St->getBasePtr();
14353     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14354                          DAG.getConstant(4, MVT::i32));
14355
14356     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14357                                 St->getPointerInfo(),
14358                                 St->isVolatile(), St->isNonTemporal(),
14359                                 St->getAlignment());
14360     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14361                                 St->getPointerInfo().getWithOffset(4),
14362                                 St->isVolatile(),
14363                                 St->isNonTemporal(),
14364                                 MinAlign(St->getAlignment(), 4));
14365     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14366   }
14367   return SDValue();
14368 }
14369
14370 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14371 /// and return the operands for the horizontal operation in LHS and RHS.  A
14372 /// horizontal operation performs the binary operation on successive elements
14373 /// of its first operand, then on successive elements of its second operand,
14374 /// returning the resulting values in a vector.  For example, if
14375 ///   A = < float a0, float a1, float a2, float a3 >
14376 /// and
14377 ///   B = < float b0, float b1, float b2, float b3 >
14378 /// then the result of doing a horizontal operation on A and B is
14379 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14380 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14381 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14382 /// set to A, RHS to B, and the routine returns 'true'.
14383 /// Note that the binary operation should have the property that if one of the
14384 /// operands is UNDEF then the result is UNDEF.
14385 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14386   // Look for the following pattern: if
14387   //   A = < float a0, float a1, float a2, float a3 >
14388   //   B = < float b0, float b1, float b2, float b3 >
14389   // and
14390   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14391   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14392   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14393   // which is A horizontal-op B.
14394
14395   // At least one of the operands should be a vector shuffle.
14396   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14397       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14398     return false;
14399
14400   EVT VT = LHS.getValueType();
14401
14402   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14403          "Unsupported vector type for horizontal add/sub");
14404
14405   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14406   // operate independently on 128-bit lanes.
14407   unsigned NumElts = VT.getVectorNumElements();
14408   unsigned NumLanes = VT.getSizeInBits()/128;
14409   unsigned NumLaneElts = NumElts / NumLanes;
14410   assert((NumLaneElts % 2 == 0) &&
14411          "Vector type should have an even number of elements in each lane");
14412   unsigned HalfLaneElts = NumLaneElts/2;
14413
14414   // View LHS in the form
14415   //   LHS = VECTOR_SHUFFLE A, B, LMask
14416   // If LHS is not a shuffle then pretend it is the shuffle
14417   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14418   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14419   // type VT.
14420   SDValue A, B;
14421   SmallVector<int, 16> LMask(NumElts);
14422   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14423     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14424       A = LHS.getOperand(0);
14425     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14426       B = LHS.getOperand(1);
14427     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14428     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14429   } else {
14430     if (LHS.getOpcode() != ISD::UNDEF)
14431       A = LHS;
14432     for (unsigned i = 0; i != NumElts; ++i)
14433       LMask[i] = i;
14434   }
14435
14436   // Likewise, view RHS in the form
14437   //   RHS = VECTOR_SHUFFLE C, D, RMask
14438   SDValue C, D;
14439   SmallVector<int, 16> RMask(NumElts);
14440   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14441     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14442       C = RHS.getOperand(0);
14443     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14444       D = RHS.getOperand(1);
14445     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14446     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14447   } else {
14448     if (RHS.getOpcode() != ISD::UNDEF)
14449       C = RHS;
14450     for (unsigned i = 0; i != NumElts; ++i)
14451       RMask[i] = i;
14452   }
14453
14454   // Check that the shuffles are both shuffling the same vectors.
14455   if (!(A == C && B == D) && !(A == D && B == C))
14456     return false;
14457
14458   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14459   if (!A.getNode() && !B.getNode())
14460     return false;
14461
14462   // If A and B occur in reverse order in RHS, then "swap" them (which means
14463   // rewriting the mask).
14464   if (A != C)
14465     CommuteVectorShuffleMask(RMask, NumElts);
14466
14467   // At this point LHS and RHS are equivalent to
14468   //   LHS = VECTOR_SHUFFLE A, B, LMask
14469   //   RHS = VECTOR_SHUFFLE A, B, RMask
14470   // Check that the masks correspond to performing a horizontal operation.
14471   for (unsigned i = 0; i != NumElts; ++i) {
14472     int LIdx = LMask[i], RIdx = RMask[i];
14473
14474     // Ignore any UNDEF components.
14475     if (LIdx < 0 || RIdx < 0 ||
14476         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14477         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14478       continue;
14479
14480     // Check that successive elements are being operated on.  If not, this is
14481     // not a horizontal operation.
14482     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14483     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14484     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14485     if (!(LIdx == Index && RIdx == Index + 1) &&
14486         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14487       return false;
14488   }
14489
14490   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14491   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14492   return true;
14493 }
14494
14495 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14496 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14497                                   const X86Subtarget *Subtarget) {
14498   EVT VT = N->getValueType(0);
14499   SDValue LHS = N->getOperand(0);
14500   SDValue RHS = N->getOperand(1);
14501
14502   // Try to synthesize horizontal adds from adds of shuffles.
14503   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14504        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14505       isHorizontalBinOp(LHS, RHS, true))
14506     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14507   return SDValue();
14508 }
14509
14510 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14511 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14512                                   const X86Subtarget *Subtarget) {
14513   EVT VT = N->getValueType(0);
14514   SDValue LHS = N->getOperand(0);
14515   SDValue RHS = N->getOperand(1);
14516
14517   // Try to synthesize horizontal subs from subs of shuffles.
14518   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14519        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14520       isHorizontalBinOp(LHS, RHS, false))
14521     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14522   return SDValue();
14523 }
14524
14525 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14526 /// X86ISD::FXOR nodes.
14527 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14528   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14529   // F[X]OR(0.0, x) -> x
14530   // F[X]OR(x, 0.0) -> x
14531   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14532     if (C->getValueAPF().isPosZero())
14533       return N->getOperand(1);
14534   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14535     if (C->getValueAPF().isPosZero())
14536       return N->getOperand(0);
14537   return SDValue();
14538 }
14539
14540 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14541 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14542   // FAND(0.0, x) -> 0.0
14543   // FAND(x, 0.0) -> 0.0
14544   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14545     if (C->getValueAPF().isPosZero())
14546       return N->getOperand(0);
14547   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14548     if (C->getValueAPF().isPosZero())
14549       return N->getOperand(1);
14550   return SDValue();
14551 }
14552
14553 static SDValue PerformBTCombine(SDNode *N,
14554                                 SelectionDAG &DAG,
14555                                 TargetLowering::DAGCombinerInfo &DCI) {
14556   // BT ignores high bits in the bit index operand.
14557   SDValue Op1 = N->getOperand(1);
14558   if (Op1.hasOneUse()) {
14559     unsigned BitWidth = Op1.getValueSizeInBits();
14560     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14561     APInt KnownZero, KnownOne;
14562     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14563                                           !DCI.isBeforeLegalizeOps());
14564     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14565     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14566         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14567       DCI.CommitTargetLoweringOpt(TLO);
14568   }
14569   return SDValue();
14570 }
14571
14572 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14573   SDValue Op = N->getOperand(0);
14574   if (Op.getOpcode() == ISD::BITCAST)
14575     Op = Op.getOperand(0);
14576   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14577   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14578       VT.getVectorElementType().getSizeInBits() ==
14579       OpVT.getVectorElementType().getSizeInBits()) {
14580     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14581   }
14582   return SDValue();
14583 }
14584
14585 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14586                                   TargetLowering::DAGCombinerInfo &DCI,
14587                                   const X86Subtarget *Subtarget) {
14588   if (!DCI.isBeforeLegalizeOps())
14589     return SDValue();
14590
14591   if (!Subtarget->hasAVX()) return SDValue();
14592
14593    // Optimize vectors in AVX mode
14594    // Sign extend  v8i16 to v8i32 and
14595    //              v4i32 to v4i64
14596    //
14597    // Divide input vector into two parts
14598    // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14599    // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14600    // concat the vectors to original VT
14601
14602   EVT VT = N->getValueType(0);
14603   SDValue Op = N->getOperand(0);
14604   EVT OpVT = Op.getValueType();
14605   DebugLoc dl = N->getDebugLoc();
14606
14607   if (((VT == MVT::v4i64) && (OpVT == MVT::v4i32)) ||
14608     ((VT == MVT::v8i32) && (OpVT == MVT::v8i16))) {
14609
14610     unsigned NumElems = OpVT.getVectorNumElements();
14611     SmallVector<int,8> ShufMask1(NumElems, -1);
14612     for (unsigned i=0; i< NumElems/2; i++) ShufMask1[i] = i;
14613
14614     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14615                                 ShufMask1.data());
14616
14617     SmallVector<int,8> ShufMask2(NumElems, -1);
14618     for (unsigned i=0; i< NumElems/2; i++) ShufMask2[i] = i+NumElems/2;
14619
14620     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14621                                 ShufMask2.data());
14622
14623     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 
14624       VT.getVectorNumElements()/2);
14625     
14626     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 
14627     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
14628
14629     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14630   }
14631   return SDValue();
14632 }
14633
14634 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
14635                                   const X86Subtarget *Subtarget) {
14636   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14637   //           (and (i32 x86isd::setcc_carry), 1)
14638   // This eliminates the zext. This transformation is necessary because
14639   // ISD::SETCC is always legalized to i8.
14640   DebugLoc dl = N->getDebugLoc();
14641   SDValue N0 = N->getOperand(0);
14642   EVT VT = N->getValueType(0);
14643   EVT OpVT = N0.getValueType();
14644
14645   if (N0.getOpcode() == ISD::AND &&
14646       N0.hasOneUse() &&
14647       N0.getOperand(0).hasOneUse()) {
14648     SDValue N00 = N0.getOperand(0);
14649     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14650       return SDValue();
14651     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14652     if (!C || C->getZExtValue() != 1)
14653       return SDValue();
14654     return DAG.getNode(ISD::AND, dl, VT,
14655                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14656                                    N00.getOperand(0), N00.getOperand(1)),
14657                        DAG.getConstant(1, VT));
14658   }
14659   // Optimize vectors in AVX mode:
14660   //
14661   //   v8i16 -> v8i32
14662   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14663   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14664   //   Concat upper and lower parts.
14665   //
14666   //   v4i32 -> v4i64
14667   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14668   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14669   //   Concat upper and lower parts.
14670   //
14671   if (Subtarget->hasAVX()) {
14672
14673     if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16))  ||
14674       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
14675
14676       SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
14677       SDValue OpLo = getTargetShuffleNode(X86ISD::UNPCKL, dl, OpVT, N0, ZeroVec, DAG);
14678       SDValue OpHi = getTargetShuffleNode(X86ISD::UNPCKH, dl, OpVT, N0, ZeroVec, DAG);
14679
14680       EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 
14681         VT.getVectorNumElements()/2);
14682
14683       OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14684       OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14685
14686       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14687     }
14688   }
14689
14690
14691   return SDValue();
14692 }
14693
14694 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14695 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14696   unsigned X86CC = N->getConstantOperandVal(0);
14697   SDValue EFLAG = N->getOperand(1);
14698   DebugLoc DL = N->getDebugLoc();
14699
14700   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14701   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14702   // cases.
14703   if (X86CC == X86::COND_B)
14704     return DAG.getNode(ISD::AND, DL, MVT::i8,
14705                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14706                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14707                        DAG.getConstant(1, MVT::i8));
14708
14709   return SDValue();
14710 }
14711
14712 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14713                                         const X86TargetLowering *XTLI) {
14714   SDValue Op0 = N->getOperand(0);
14715   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14716   // a 32-bit target where SSE doesn't support i64->FP operations.
14717   if (Op0.getOpcode() == ISD::LOAD) {
14718     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14719     EVT VT = Ld->getValueType(0);
14720     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14721         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14722         !XTLI->getSubtarget()->is64Bit() &&
14723         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14724       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14725                                           Ld->getChain(), Op0, DAG);
14726       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14727       return FILDChain;
14728     }
14729   }
14730   return SDValue();
14731 }
14732
14733 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14734 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14735                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14736   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14737   // the result is either zero or one (depending on the input carry bit).
14738   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14739   if (X86::isZeroNode(N->getOperand(0)) &&
14740       X86::isZeroNode(N->getOperand(1)) &&
14741       // We don't have a good way to replace an EFLAGS use, so only do this when
14742       // dead right now.
14743       SDValue(N, 1).use_empty()) {
14744     DebugLoc DL = N->getDebugLoc();
14745     EVT VT = N->getValueType(0);
14746     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14747     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14748                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14749                                            DAG.getConstant(X86::COND_B,MVT::i8),
14750                                            N->getOperand(2)),
14751                                DAG.getConstant(1, VT));
14752     return DCI.CombineTo(N, Res1, CarryOut);
14753   }
14754
14755   return SDValue();
14756 }
14757
14758 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14759 //      (add Y, (setne X, 0)) -> sbb -1, Y
14760 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14761 //      (sub (setne X, 0), Y) -> adc -1, Y
14762 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14763   DebugLoc DL = N->getDebugLoc();
14764
14765   // Look through ZExts.
14766   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14767   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14768     return SDValue();
14769
14770   SDValue SetCC = Ext.getOperand(0);
14771   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14772     return SDValue();
14773
14774   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14775   if (CC != X86::COND_E && CC != X86::COND_NE)
14776     return SDValue();
14777
14778   SDValue Cmp = SetCC.getOperand(1);
14779   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14780       !X86::isZeroNode(Cmp.getOperand(1)) ||
14781       !Cmp.getOperand(0).getValueType().isInteger())
14782     return SDValue();
14783
14784   SDValue CmpOp0 = Cmp.getOperand(0);
14785   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14786                                DAG.getConstant(1, CmpOp0.getValueType()));
14787
14788   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14789   if (CC == X86::COND_NE)
14790     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14791                        DL, OtherVal.getValueType(), OtherVal,
14792                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14793   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14794                      DL, OtherVal.getValueType(), OtherVal,
14795                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14796 }
14797
14798 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14799 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14800                                  const X86Subtarget *Subtarget) {
14801   EVT VT = N->getValueType(0);
14802   SDValue Op0 = N->getOperand(0);
14803   SDValue Op1 = N->getOperand(1);
14804
14805   // Try to synthesize horizontal adds from adds of shuffles.
14806   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14807        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14808       isHorizontalBinOp(Op0, Op1, true))
14809     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14810
14811   return OptimizeConditionalInDecrement(N, DAG);
14812 }
14813
14814 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14815                                  const X86Subtarget *Subtarget) {
14816   SDValue Op0 = N->getOperand(0);
14817   SDValue Op1 = N->getOperand(1);
14818
14819   // X86 can't encode an immediate LHS of a sub. See if we can push the
14820   // negation into a preceding instruction.
14821   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14822     // If the RHS of the sub is a XOR with one use and a constant, invert the
14823     // immediate. Then add one to the LHS of the sub so we can turn
14824     // X-Y -> X+~Y+1, saving one register.
14825     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14826         isa<ConstantSDNode>(Op1.getOperand(1))) {
14827       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14828       EVT VT = Op0.getValueType();
14829       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14830                                    Op1.getOperand(0),
14831                                    DAG.getConstant(~XorC, VT));
14832       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14833                          DAG.getConstant(C->getAPIntValue()+1, VT));
14834     }
14835   }
14836
14837   // Try to synthesize horizontal adds from adds of shuffles.
14838   EVT VT = N->getValueType(0);
14839   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14840        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14841       isHorizontalBinOp(Op0, Op1, true))
14842     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14843
14844   return OptimizeConditionalInDecrement(N, DAG);
14845 }
14846
14847 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14848                                              DAGCombinerInfo &DCI) const {
14849   SelectionDAG &DAG = DCI.DAG;
14850   switch (N->getOpcode()) {
14851   default: break;
14852   case ISD::EXTRACT_VECTOR_ELT:
14853     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14854   case ISD::VSELECT:
14855   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
14856   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14857   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14858   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14859   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14860   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14861   case ISD::SHL:
14862   case ISD::SRA:
14863   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
14864   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14865   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14866   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14867   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14868   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14869   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14870   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14871   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14872   case X86ISD::FXOR:
14873   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14874   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14875   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14876   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14877   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, Subtarget);
14878   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
14879   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
14880   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14881   case X86ISD::SHUFP:       // Handle all target specific shuffles
14882   case X86ISD::PALIGN:
14883   case X86ISD::UNPCKH:
14884   case X86ISD::UNPCKL:
14885   case X86ISD::MOVHLPS:
14886   case X86ISD::MOVLHPS:
14887   case X86ISD::PSHUFD:
14888   case X86ISD::PSHUFHW:
14889   case X86ISD::PSHUFLW:
14890   case X86ISD::MOVSS:
14891   case X86ISD::MOVSD:
14892   case X86ISD::VPERMILP:
14893   case X86ISD::VPERM2X128:
14894   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14895   }
14896
14897   return SDValue();
14898 }
14899
14900 /// isTypeDesirableForOp - Return true if the target has native support for
14901 /// the specified value type and it is 'desirable' to use the type for the
14902 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14903 /// instruction encodings are longer and some i16 instructions are slow.
14904 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14905   if (!isTypeLegal(VT))
14906     return false;
14907   if (VT != MVT::i16)
14908     return true;
14909
14910   switch (Opc) {
14911   default:
14912     return true;
14913   case ISD::LOAD:
14914   case ISD::SIGN_EXTEND:
14915   case ISD::ZERO_EXTEND:
14916   case ISD::ANY_EXTEND:
14917   case ISD::SHL:
14918   case ISD::SRL:
14919   case ISD::SUB:
14920   case ISD::ADD:
14921   case ISD::MUL:
14922   case ISD::AND:
14923   case ISD::OR:
14924   case ISD::XOR:
14925     return false;
14926   }
14927 }
14928
14929 /// IsDesirableToPromoteOp - This method query the target whether it is
14930 /// beneficial for dag combiner to promote the specified node. If true, it
14931 /// should return the desired promotion type by reference.
14932 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14933   EVT VT = Op.getValueType();
14934   if (VT != MVT::i16)
14935     return false;
14936
14937   bool Promote = false;
14938   bool Commute = false;
14939   switch (Op.getOpcode()) {
14940   default: break;
14941   case ISD::LOAD: {
14942     LoadSDNode *LD = cast<LoadSDNode>(Op);
14943     // If the non-extending load has a single use and it's not live out, then it
14944     // might be folded.
14945     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14946                                                      Op.hasOneUse()*/) {
14947       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14948              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14949         // The only case where we'd want to promote LOAD (rather then it being
14950         // promoted as an operand is when it's only use is liveout.
14951         if (UI->getOpcode() != ISD::CopyToReg)
14952           return false;
14953       }
14954     }
14955     Promote = true;
14956     break;
14957   }
14958   case ISD::SIGN_EXTEND:
14959   case ISD::ZERO_EXTEND:
14960   case ISD::ANY_EXTEND:
14961     Promote = true;
14962     break;
14963   case ISD::SHL:
14964   case ISD::SRL: {
14965     SDValue N0 = Op.getOperand(0);
14966     // Look out for (store (shl (load), x)).
14967     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14968       return false;
14969     Promote = true;
14970     break;
14971   }
14972   case ISD::ADD:
14973   case ISD::MUL:
14974   case ISD::AND:
14975   case ISD::OR:
14976   case ISD::XOR:
14977     Commute = true;
14978     // fallthrough
14979   case ISD::SUB: {
14980     SDValue N0 = Op.getOperand(0);
14981     SDValue N1 = Op.getOperand(1);
14982     if (!Commute && MayFoldLoad(N1))
14983       return false;
14984     // Avoid disabling potential load folding opportunities.
14985     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14986       return false;
14987     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14988       return false;
14989     Promote = true;
14990   }
14991   }
14992
14993   PVT = MVT::i32;
14994   return Promote;
14995 }
14996
14997 //===----------------------------------------------------------------------===//
14998 //                           X86 Inline Assembly Support
14999 //===----------------------------------------------------------------------===//
15000
15001 namespace {
15002   // Helper to match a string separated by whitespace.
15003   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15004     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15005
15006     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15007       StringRef piece(*args[i]);
15008       if (!s.startswith(piece)) // Check if the piece matches.
15009         return false;
15010
15011       s = s.substr(piece.size());
15012       StringRef::size_type pos = s.find_first_not_of(" \t");
15013       if (pos == 0) // We matched a prefix.
15014         return false;
15015
15016       s = s.substr(pos);
15017     }
15018
15019     return s.empty();
15020   }
15021   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15022 }
15023
15024 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15025   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15026
15027   std::string AsmStr = IA->getAsmString();
15028
15029   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15030   if (!Ty || Ty->getBitWidth() % 16 != 0)
15031     return false;
15032
15033   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15034   SmallVector<StringRef, 4> AsmPieces;
15035   SplitString(AsmStr, AsmPieces, ";\n");
15036
15037   switch (AsmPieces.size()) {
15038   default: return false;
15039   case 1:
15040     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15041     // we will turn this bswap into something that will be lowered to logical
15042     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15043     // lower so don't worry about this.
15044     // bswap $0
15045     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15046         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15047         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15048         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15049         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15050         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15051       // No need to check constraints, nothing other than the equivalent of
15052       // "=r,0" would be valid here.
15053       return IntrinsicLowering::LowerToByteSwap(CI);
15054     }
15055
15056     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15057     if (CI->getType()->isIntegerTy(16) &&
15058         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15059         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15060          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15061       AsmPieces.clear();
15062       const std::string &ConstraintsStr = IA->getConstraintString();
15063       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15064       std::sort(AsmPieces.begin(), AsmPieces.end());
15065       if (AsmPieces.size() == 4 &&
15066           AsmPieces[0] == "~{cc}" &&
15067           AsmPieces[1] == "~{dirflag}" &&
15068           AsmPieces[2] == "~{flags}" &&
15069           AsmPieces[3] == "~{fpsr}")
15070       return IntrinsicLowering::LowerToByteSwap(CI);
15071     }
15072     break;
15073   case 3:
15074     if (CI->getType()->isIntegerTy(32) &&
15075         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15076         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15077         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15078         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15079       AsmPieces.clear();
15080       const std::string &ConstraintsStr = IA->getConstraintString();
15081       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15082       std::sort(AsmPieces.begin(), AsmPieces.end());
15083       if (AsmPieces.size() == 4 &&
15084           AsmPieces[0] == "~{cc}" &&
15085           AsmPieces[1] == "~{dirflag}" &&
15086           AsmPieces[2] == "~{flags}" &&
15087           AsmPieces[3] == "~{fpsr}")
15088         return IntrinsicLowering::LowerToByteSwap(CI);
15089     }
15090
15091     if (CI->getType()->isIntegerTy(64)) {
15092       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15093       if (Constraints.size() >= 2 &&
15094           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15095           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15096         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15097         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15098             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15099             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15100           return IntrinsicLowering::LowerToByteSwap(CI);
15101       }
15102     }
15103     break;
15104   }
15105   return false;
15106 }
15107
15108
15109
15110 /// getConstraintType - Given a constraint letter, return the type of
15111 /// constraint it is for this target.
15112 X86TargetLowering::ConstraintType
15113 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15114   if (Constraint.size() == 1) {
15115     switch (Constraint[0]) {
15116     case 'R':
15117     case 'q':
15118     case 'Q':
15119     case 'f':
15120     case 't':
15121     case 'u':
15122     case 'y':
15123     case 'x':
15124     case 'Y':
15125     case 'l':
15126       return C_RegisterClass;
15127     case 'a':
15128     case 'b':
15129     case 'c':
15130     case 'd':
15131     case 'S':
15132     case 'D':
15133     case 'A':
15134       return C_Register;
15135     case 'I':
15136     case 'J':
15137     case 'K':
15138     case 'L':
15139     case 'M':
15140     case 'N':
15141     case 'G':
15142     case 'C':
15143     case 'e':
15144     case 'Z':
15145       return C_Other;
15146     default:
15147       break;
15148     }
15149   }
15150   return TargetLowering::getConstraintType(Constraint);
15151 }
15152
15153 /// Examine constraint type and operand type and determine a weight value.
15154 /// This object must already have been set up with the operand type
15155 /// and the current alternative constraint selected.
15156 TargetLowering::ConstraintWeight
15157   X86TargetLowering::getSingleConstraintMatchWeight(
15158     AsmOperandInfo &info, const char *constraint) const {
15159   ConstraintWeight weight = CW_Invalid;
15160   Value *CallOperandVal = info.CallOperandVal;
15161     // If we don't have a value, we can't do a match,
15162     // but allow it at the lowest weight.
15163   if (CallOperandVal == NULL)
15164     return CW_Default;
15165   Type *type = CallOperandVal->getType();
15166   // Look at the constraint type.
15167   switch (*constraint) {
15168   default:
15169     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15170   case 'R':
15171   case 'q':
15172   case 'Q':
15173   case 'a':
15174   case 'b':
15175   case 'c':
15176   case 'd':
15177   case 'S':
15178   case 'D':
15179   case 'A':
15180     if (CallOperandVal->getType()->isIntegerTy())
15181       weight = CW_SpecificReg;
15182     break;
15183   case 'f':
15184   case 't':
15185   case 'u':
15186       if (type->isFloatingPointTy())
15187         weight = CW_SpecificReg;
15188       break;
15189   case 'y':
15190       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15191         weight = CW_SpecificReg;
15192       break;
15193   case 'x':
15194   case 'Y':
15195     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15196         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15197       weight = CW_Register;
15198     break;
15199   case 'I':
15200     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15201       if (C->getZExtValue() <= 31)
15202         weight = CW_Constant;
15203     }
15204     break;
15205   case 'J':
15206     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15207       if (C->getZExtValue() <= 63)
15208         weight = CW_Constant;
15209     }
15210     break;
15211   case 'K':
15212     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15213       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15214         weight = CW_Constant;
15215     }
15216     break;
15217   case 'L':
15218     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15219       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15220         weight = CW_Constant;
15221     }
15222     break;
15223   case 'M':
15224     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15225       if (C->getZExtValue() <= 3)
15226         weight = CW_Constant;
15227     }
15228     break;
15229   case 'N':
15230     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15231       if (C->getZExtValue() <= 0xff)
15232         weight = CW_Constant;
15233     }
15234     break;
15235   case 'G':
15236   case 'C':
15237     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15238       weight = CW_Constant;
15239     }
15240     break;
15241   case 'e':
15242     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15243       if ((C->getSExtValue() >= -0x80000000LL) &&
15244           (C->getSExtValue() <= 0x7fffffffLL))
15245         weight = CW_Constant;
15246     }
15247     break;
15248   case 'Z':
15249     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15250       if (C->getZExtValue() <= 0xffffffff)
15251         weight = CW_Constant;
15252     }
15253     break;
15254   }
15255   return weight;
15256 }
15257
15258 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15259 /// with another that has more specific requirements based on the type of the
15260 /// corresponding operand.
15261 const char *X86TargetLowering::
15262 LowerXConstraint(EVT ConstraintVT) const {
15263   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15264   // 'f' like normal targets.
15265   if (ConstraintVT.isFloatingPoint()) {
15266     if (Subtarget->hasSSE2())
15267       return "Y";
15268     if (Subtarget->hasSSE1())
15269       return "x";
15270   }
15271
15272   return TargetLowering::LowerXConstraint(ConstraintVT);
15273 }
15274
15275 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15276 /// vector.  If it is invalid, don't add anything to Ops.
15277 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15278                                                      std::string &Constraint,
15279                                                      std::vector<SDValue>&Ops,
15280                                                      SelectionDAG &DAG) const {
15281   SDValue Result(0, 0);
15282
15283   // Only support length 1 constraints for now.
15284   if (Constraint.length() > 1) return;
15285
15286   char ConstraintLetter = Constraint[0];
15287   switch (ConstraintLetter) {
15288   default: break;
15289   case 'I':
15290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15291       if (C->getZExtValue() <= 31) {
15292         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15293         break;
15294       }
15295     }
15296     return;
15297   case 'J':
15298     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15299       if (C->getZExtValue() <= 63) {
15300         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15301         break;
15302       }
15303     }
15304     return;
15305   case 'K':
15306     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15307       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15308         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15309         break;
15310       }
15311     }
15312     return;
15313   case 'N':
15314     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15315       if (C->getZExtValue() <= 255) {
15316         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15317         break;
15318       }
15319     }
15320     return;
15321   case 'e': {
15322     // 32-bit signed value
15323     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15324       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15325                                            C->getSExtValue())) {
15326         // Widen to 64 bits here to get it sign extended.
15327         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15328         break;
15329       }
15330     // FIXME gcc accepts some relocatable values here too, but only in certain
15331     // memory models; it's complicated.
15332     }
15333     return;
15334   }
15335   case 'Z': {
15336     // 32-bit unsigned value
15337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15338       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15339                                            C->getZExtValue())) {
15340         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15341         break;
15342       }
15343     }
15344     // FIXME gcc accepts some relocatable values here too, but only in certain
15345     // memory models; it's complicated.
15346     return;
15347   }
15348   case 'i': {
15349     // Literal immediates are always ok.
15350     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15351       // Widen to 64 bits here to get it sign extended.
15352       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15353       break;
15354     }
15355
15356     // In any sort of PIC mode addresses need to be computed at runtime by
15357     // adding in a register or some sort of table lookup.  These can't
15358     // be used as immediates.
15359     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15360       return;
15361
15362     // If we are in non-pic codegen mode, we allow the address of a global (with
15363     // an optional displacement) to be used with 'i'.
15364     GlobalAddressSDNode *GA = 0;
15365     int64_t Offset = 0;
15366
15367     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15368     while (1) {
15369       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15370         Offset += GA->getOffset();
15371         break;
15372       } else if (Op.getOpcode() == ISD::ADD) {
15373         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15374           Offset += C->getZExtValue();
15375           Op = Op.getOperand(0);
15376           continue;
15377         }
15378       } else if (Op.getOpcode() == ISD::SUB) {
15379         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15380           Offset += -C->getZExtValue();
15381           Op = Op.getOperand(0);
15382           continue;
15383         }
15384       }
15385
15386       // Otherwise, this isn't something we can handle, reject it.
15387       return;
15388     }
15389
15390     const GlobalValue *GV = GA->getGlobal();
15391     // If we require an extra load to get this address, as in PIC mode, we
15392     // can't accept it.
15393     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15394                                                         getTargetMachine())))
15395       return;
15396
15397     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15398                                         GA->getValueType(0), Offset);
15399     break;
15400   }
15401   }
15402
15403   if (Result.getNode()) {
15404     Ops.push_back(Result);
15405     return;
15406   }
15407   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15408 }
15409
15410 std::pair<unsigned, const TargetRegisterClass*>
15411 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15412                                                 EVT VT) const {
15413   // First, see if this is a constraint that directly corresponds to an LLVM
15414   // register class.
15415   if (Constraint.size() == 1) {
15416     // GCC Constraint Letters
15417     switch (Constraint[0]) {
15418     default: break;
15419       // TODO: Slight differences here in allocation order and leaving
15420       // RIP in the class. Do they matter any more here than they do
15421       // in the normal allocation?
15422     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15423       if (Subtarget->is64Bit()) {
15424         if (VT == MVT::i32 || VT == MVT::f32)
15425           return std::make_pair(0U, X86::GR32RegisterClass);
15426         else if (VT == MVT::i16)
15427           return std::make_pair(0U, X86::GR16RegisterClass);
15428         else if (VT == MVT::i8 || VT == MVT::i1)
15429           return std::make_pair(0U, X86::GR8RegisterClass);
15430         else if (VT == MVT::i64 || VT == MVT::f64)
15431           return std::make_pair(0U, X86::GR64RegisterClass);
15432         break;
15433       }
15434       // 32-bit fallthrough
15435     case 'Q':   // Q_REGS
15436       if (VT == MVT::i32 || VT == MVT::f32)
15437         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15438       else if (VT == MVT::i16)
15439         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15440       else if (VT == MVT::i8 || VT == MVT::i1)
15441         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15442       else if (VT == MVT::i64)
15443         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15444       break;
15445     case 'r':   // GENERAL_REGS
15446     case 'l':   // INDEX_REGS
15447       if (VT == MVT::i8 || VT == MVT::i1)
15448         return std::make_pair(0U, X86::GR8RegisterClass);
15449       if (VT == MVT::i16)
15450         return std::make_pair(0U, X86::GR16RegisterClass);
15451       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15452         return std::make_pair(0U, X86::GR32RegisterClass);
15453       return std::make_pair(0U, X86::GR64RegisterClass);
15454     case 'R':   // LEGACY_REGS
15455       if (VT == MVT::i8 || VT == MVT::i1)
15456         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15457       if (VT == MVT::i16)
15458         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15459       if (VT == MVT::i32 || !Subtarget->is64Bit())
15460         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15461       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15462     case 'f':  // FP Stack registers.
15463       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15464       // value to the correct fpstack register class.
15465       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15466         return std::make_pair(0U, X86::RFP32RegisterClass);
15467       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15468         return std::make_pair(0U, X86::RFP64RegisterClass);
15469       return std::make_pair(0U, X86::RFP80RegisterClass);
15470     case 'y':   // MMX_REGS if MMX allowed.
15471       if (!Subtarget->hasMMX()) break;
15472       return std::make_pair(0U, X86::VR64RegisterClass);
15473     case 'Y':   // SSE_REGS if SSE2 allowed
15474       if (!Subtarget->hasSSE2()) break;
15475       // FALL THROUGH.
15476     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15477       if (!Subtarget->hasSSE1()) break;
15478
15479       switch (VT.getSimpleVT().SimpleTy) {
15480       default: break;
15481       // Scalar SSE types.
15482       case MVT::f32:
15483       case MVT::i32:
15484         return std::make_pair(0U, X86::FR32RegisterClass);
15485       case MVT::f64:
15486       case MVT::i64:
15487         return std::make_pair(0U, X86::FR64RegisterClass);
15488       // Vector types.
15489       case MVT::v16i8:
15490       case MVT::v8i16:
15491       case MVT::v4i32:
15492       case MVT::v2i64:
15493       case MVT::v4f32:
15494       case MVT::v2f64:
15495         return std::make_pair(0U, X86::VR128RegisterClass);
15496       // AVX types.
15497       case MVT::v32i8:
15498       case MVT::v16i16:
15499       case MVT::v8i32:
15500       case MVT::v4i64:
15501       case MVT::v8f32:
15502       case MVT::v4f64:
15503         return std::make_pair(0U, X86::VR256RegisterClass);
15504         
15505       }
15506       break;
15507     }
15508   }
15509
15510   // Use the default implementation in TargetLowering to convert the register
15511   // constraint into a member of a register class.
15512   std::pair<unsigned, const TargetRegisterClass*> Res;
15513   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15514
15515   // Not found as a standard register?
15516   if (Res.second == 0) {
15517     // Map st(0) -> st(7) -> ST0
15518     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15519         tolower(Constraint[1]) == 's' &&
15520         tolower(Constraint[2]) == 't' &&
15521         Constraint[3] == '(' &&
15522         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15523         Constraint[5] == ')' &&
15524         Constraint[6] == '}') {
15525
15526       Res.first = X86::ST0+Constraint[4]-'0';
15527       Res.second = X86::RFP80RegisterClass;
15528       return Res;
15529     }
15530
15531     // GCC allows "st(0)" to be called just plain "st".
15532     if (StringRef("{st}").equals_lower(Constraint)) {
15533       Res.first = X86::ST0;
15534       Res.second = X86::RFP80RegisterClass;
15535       return Res;
15536     }
15537
15538     // flags -> EFLAGS
15539     if (StringRef("{flags}").equals_lower(Constraint)) {
15540       Res.first = X86::EFLAGS;
15541       Res.second = X86::CCRRegisterClass;
15542       return Res;
15543     }
15544
15545     // 'A' means EAX + EDX.
15546     if (Constraint == "A") {
15547       Res.first = X86::EAX;
15548       Res.second = X86::GR32_ADRegisterClass;
15549       return Res;
15550     }
15551     return Res;
15552   }
15553
15554   // Otherwise, check to see if this is a register class of the wrong value
15555   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15556   // turn into {ax},{dx}.
15557   if (Res.second->hasType(VT))
15558     return Res;   // Correct type already, nothing to do.
15559
15560   // All of the single-register GCC register classes map their values onto
15561   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15562   // really want an 8-bit or 32-bit register, map to the appropriate register
15563   // class and return the appropriate register.
15564   if (Res.second == X86::GR16RegisterClass) {
15565     if (VT == MVT::i8) {
15566       unsigned DestReg = 0;
15567       switch (Res.first) {
15568       default: break;
15569       case X86::AX: DestReg = X86::AL; break;
15570       case X86::DX: DestReg = X86::DL; break;
15571       case X86::CX: DestReg = X86::CL; break;
15572       case X86::BX: DestReg = X86::BL; break;
15573       }
15574       if (DestReg) {
15575         Res.first = DestReg;
15576         Res.second = X86::GR8RegisterClass;
15577       }
15578     } else if (VT == MVT::i32) {
15579       unsigned DestReg = 0;
15580       switch (Res.first) {
15581       default: break;
15582       case X86::AX: DestReg = X86::EAX; break;
15583       case X86::DX: DestReg = X86::EDX; break;
15584       case X86::CX: DestReg = X86::ECX; break;
15585       case X86::BX: DestReg = X86::EBX; break;
15586       case X86::SI: DestReg = X86::ESI; break;
15587       case X86::DI: DestReg = X86::EDI; break;
15588       case X86::BP: DestReg = X86::EBP; break;
15589       case X86::SP: DestReg = X86::ESP; break;
15590       }
15591       if (DestReg) {
15592         Res.first = DestReg;
15593         Res.second = X86::GR32RegisterClass;
15594       }
15595     } else if (VT == MVT::i64) {
15596       unsigned DestReg = 0;
15597       switch (Res.first) {
15598       default: break;
15599       case X86::AX: DestReg = X86::RAX; break;
15600       case X86::DX: DestReg = X86::RDX; break;
15601       case X86::CX: DestReg = X86::RCX; break;
15602       case X86::BX: DestReg = X86::RBX; break;
15603       case X86::SI: DestReg = X86::RSI; break;
15604       case X86::DI: DestReg = X86::RDI; break;
15605       case X86::BP: DestReg = X86::RBP; break;
15606       case X86::SP: DestReg = X86::RSP; break;
15607       }
15608       if (DestReg) {
15609         Res.first = DestReg;
15610         Res.second = X86::GR64RegisterClass;
15611       }
15612     }
15613   } else if (Res.second == X86::FR32RegisterClass ||
15614              Res.second == X86::FR64RegisterClass ||
15615              Res.second == X86::VR128RegisterClass) {
15616     // Handle references to XMM physical registers that got mapped into the
15617     // wrong class.  This can happen with constraints like {xmm0} where the
15618     // target independent register mapper will just pick the first match it can
15619     // find, ignoring the required type.
15620     if (VT == MVT::f32)
15621       Res.second = X86::FR32RegisterClass;
15622     else if (VT == MVT::f64)
15623       Res.second = X86::FR64RegisterClass;
15624     else if (X86::VR128RegisterClass->hasType(VT))
15625       Res.second = X86::VR128RegisterClass;
15626   }
15627
15628   return Res;
15629 }