Don't try to match 'unpackl/h v, v' for 32xi8 and 16xi16 when only AVX1 is supported...
[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/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.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 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt();
172   X86ScalarSSEf32 = Subtarget->hasXMM();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
185
186   // For 64-bit since we have so many registers use the ILP scheduler, for
187   // 32-bit code use the register pressure specific scheduling.
188   if (Subtarget->is64Bit())
189     setSchedulingPreference(Sched::ILP);
190   else
191     setSchedulingPreference(Sched::RegPressure);
192   setStackPointerRegisterToSaveRestore(X86StackPtr);
193
194   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195     // Setup Windows compiler runtime calls.
196     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198     setLibcallName(RTLIB::SREM_I64, "_allrem");
199     setLibcallName(RTLIB::UREM_I64, "_aullrem");
200     setLibcallName(RTLIB::MUL_I64, "_allmul");
201     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210   }
211
212   if (Subtarget->isTargetDarwin()) {
213     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214     setUseUnderscoreSetJmp(false);
215     setUseUnderscoreLongJmp(false);
216   } else if (Subtarget->isTargetMingw()) {
217     // MS runtime is weird: it exports _setjmp, but longjmp!
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(false);
220   } else {
221     setUseUnderscoreSetJmp(true);
222     setUseUnderscoreLongJmp(true);
223   }
224
225   // Set up the register classes.
226   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229   if (Subtarget->is64Bit())
230     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
231
232   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
233
234   // We don't accept any truncstore of integer registers.
235   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
241
242   // SETOEQ and SETUNE require checking two conditions.
243   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
249
250   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
251   // operation.
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
255
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
259   } else if (!TM.Options.UseSoftFloat) {
260     // We have an algorithm for SSE2->double, and we turn this into a
261     // 64-bit FILD followed by conditional FADD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
263     // We have an algorithm for SSE2, and we turn this into a 64-bit
264     // FILD for other targets.
265     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
266   }
267
268   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
269   // this operation.
270   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
272
273   if (!TM.Options.UseSoftFloat) {
274     // SSE has no i16 to fp conversion, only i32
275     if (X86ScalarSSEf32) {
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
277       // f32 and f64 cases are Legal, f80 case is not
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     } else {
280       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
282     }
283   } else {
284     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
286   }
287
288   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
289   // are Legal, f80 is custom lowered.
290   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
291   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
292
293   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
294   // this operation.
295   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
297
298   if (X86ScalarSSEf32) {
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
300     // f32 and f64 cases are Legal, f80 case is not
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   } else {
303     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
305   }
306
307   // Handle FP_TO_UINT by promoting the destination to a larger signed
308   // conversion.
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
312
313   if (Subtarget->is64Bit()) {
314     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
316   } else if (!TM.Options.UseSoftFloat) {
317     // Since AVX is a superset of SSE3, only check for SSE here.
318     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319       // Expand FP_TO_UINT into a select.
320       // FIXME: We would like to use a Custom expander here eventually to do
321       // the optimal thing for SSE vs. the default expansion in the legalizer.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323     else
324       // With SSE3 we can use fisttpll to convert to a signed i64; without
325       // SSE, we're stuck with a fistpll.
326       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0, e = 4; i != e; ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Expand);
382   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i16  , Expand);
383   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
384   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i64  , Expand);
385   if (Subtarget->hasBMI()) {
386     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
387   } else {
388     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
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   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i8   , Expand);
396   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i16  , Expand);
397   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
398   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i64  , Expand);
399   if (Subtarget->hasLZCNT()) {
400     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
401   } else {
402     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
403     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
404     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
405     if (Subtarget->is64Bit())
406       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
407   }
408
409   if (Subtarget->hasPOPCNT()) {
410     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
411   } else {
412     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
413     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
414     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
415     if (Subtarget->is64Bit())
416       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
417   }
418
419   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
420   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
421
422   // These should be promoted to a larger select which is supported.
423   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
424   // X86 wants to expand cmov itself.
425   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
426   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
427   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
428   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
429   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
430   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
431   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
432   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
433   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
434   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
435   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
436   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
437   if (Subtarget->is64Bit()) {
438     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
439     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
440   }
441   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
442
443   // Darwin ABI issue.
444   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
445   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
446   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
447   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
448   if (Subtarget->is64Bit())
449     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
450   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
451   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
454     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
455     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
456     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
457     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
458   }
459   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
460   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
461   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
462   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
463   if (Subtarget->is64Bit()) {
464     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
465     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
466     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
467   }
468
469   if (Subtarget->hasXMM())
470     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
471
472   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
473   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
474
475   // On X86 and X86-64, atomic operations are lowered to locked instructions.
476   // Locked instructions, in turn, have implicit fence semantics (all memory
477   // operations are flushed before issuing the locked instruction, and they
478   // are not buffered), so we can fold away the common pattern of
479   // fence-atomic-fence.
480   setShouldFoldAtomicFences(true);
481
482   // Expand certain atomics
483   for (unsigned i = 0, e = 4; i != e; ++i) {
484     MVT VT = IntVTs[i];
485     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
487     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
488   }
489
490   if (!Subtarget->is64Bit()) {
491     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
492     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
493     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
495     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
496     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
498     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
499   }
500
501   if (Subtarget->hasCmpxchg16b()) {
502     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
503   }
504
505   // FIXME - use subtarget debug flags
506   if (!Subtarget->isTargetDarwin() &&
507       !Subtarget->isTargetELF() &&
508       !Subtarget->isTargetCygMing()) {
509     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
510   }
511
512   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
513   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
514   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
515   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
516   if (Subtarget->is64Bit()) {
517     setExceptionPointerRegister(X86::RAX);
518     setExceptionSelectorRegister(X86::RDX);
519   } else {
520     setExceptionPointerRegister(X86::EAX);
521     setExceptionSelectorRegister(X86::EDX);
522   }
523   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
524   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
525
526   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
527   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
528
529   setOperationAction(ISD::TRAP, MVT::Other, Legal);
530
531   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
532   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
533   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
534   if (Subtarget->is64Bit()) {
535     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
536     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
537   } else {
538     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
539     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
540   }
541
542   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
543   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
544
545   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
546     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
547                        MVT::i64 : MVT::i32, Custom);
548   else if (TM.Options.EnableSegmentedStacks)
549     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
550                        MVT::i64 : MVT::i32, Custom);
551   else
552     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
553                        MVT::i64 : MVT::i32, Expand);
554
555   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
556     // f32 and f64 use SSE.
557     // Set up the FP register classes.
558     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
559     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
560
561     // Use ANDPD to simulate FABS.
562     setOperationAction(ISD::FABS , MVT::f64, Custom);
563     setOperationAction(ISD::FABS , MVT::f32, Custom);
564
565     // Use XORP to simulate FNEG.
566     setOperationAction(ISD::FNEG , MVT::f64, Custom);
567     setOperationAction(ISD::FNEG , MVT::f32, Custom);
568
569     // Use ANDPD and ORPD to simulate FCOPYSIGN.
570     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
571     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572
573     // Lower this to FGETSIGNx86 plus an AND.
574     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
575     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!TM.Options.UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!TM.Options.UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!TM.Options.UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // We don't support FMA.
646   setOperationAction(ISD::FMA, MVT::f64, Expand);
647   setOperationAction(ISD::FMA, MVT::f32, Expand);
648
649   // Long double always uses X87.
650   if (!TM.Options.UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!TM.Options.UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673
674     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
675     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
676     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
677     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
678     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
679     setOperationAction(ISD::FMA, MVT::f80, Expand);
680   }
681
682   // Always use a library call for pow.
683   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
684   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
685   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
686
687   setOperationAction(ISD::FLOG, MVT::f80, Expand);
688   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
689   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
690   setOperationAction(ISD::FEXP, MVT::f80, Expand);
691   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
692
693   // First set operation action for all vector types to either promote
694   // (for widening) or expand (for scalarization). Then we will selectively
695   // turn on ones that can be effectively codegen'd.
696   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
697        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
698     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
713     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
715     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
716     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
750     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
755     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
756          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
757       setTruncStoreAction((MVT::SimpleValueType)VT,
758                           (MVT::SimpleValueType)InnerVT, Expand);
759     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
760     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
761     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
762   }
763
764   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
765   // with -msoft-float, disable use of MMX as well.
766   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
767     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
768     // No operations on x86mmx supported, everything uses intrinsics.
769   }
770
771   // MMX-sized vectors (other than x86mmx) are expected to be expanded
772   // into smaller operations.
773   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
774   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
775   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
776   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
777   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
778   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
779   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
780   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
781   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
782   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
783   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
784   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
785   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
786   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
787   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
788   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
789   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
790   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
791   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
792   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
793   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
794   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
795   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
796   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
797   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
798   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
799   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
800   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
801   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
802
803   if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
804     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
805
806     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
807     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
808     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
809     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
810     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
811     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
812     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
813     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
814     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
815     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
816     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
817     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
818   }
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
821     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
822
823     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
824     // registers cannot be used even for integer operations.
825     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
826     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
827     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
828     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
829
830     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
831     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
832     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
833     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
834     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
835     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
836     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
837     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
838     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
839     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
840     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
846
847     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
848     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
849     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
850     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
851
852     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
853     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
854     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
855     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
857
858     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
859     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
860     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
861     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
862     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
863
864     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
865     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
866       EVT VT = (MVT::SimpleValueType)i;
867       // Do not attempt to custom lower non-power-of-2 vectors
868       if (!isPowerOf2_32(VT.getVectorNumElements()))
869         continue;
870       // Do not attempt to custom lower non-128-bit vectors
871       if (!VT.is128BitVector())
872         continue;
873       setOperationAction(ISD::BUILD_VECTOR,
874                          VT.getSimpleVT().SimpleTy, Custom);
875       setOperationAction(ISD::VECTOR_SHUFFLE,
876                          VT.getSimpleVT().SimpleTy, Custom);
877       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
878                          VT.getSimpleVT().SimpleTy, Custom);
879     }
880
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
882     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
884     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
885     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
886     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
887
888     if (Subtarget->is64Bit()) {
889       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
891     }
892
893     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
894     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
895       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
896       EVT VT = SVT;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    SVT, Promote);
903       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
904       setOperationAction(ISD::OR,     SVT, Promote);
905       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    SVT, Promote);
907       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   SVT, Promote);
909       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, SVT, Promote);
911       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
912     }
913
914     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924   }
925
926   if (Subtarget->hasSSE41orAVX()) {
927     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
928     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
929     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
930     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
931     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
932     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
933     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
934     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
935     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
936     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
937
938     // FIXME: Do we need to handle scalar-to-vector here?
939     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
940
941     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
942     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
943     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
944     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
945     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
946
947     // i8 and i16 vectors are custom , because the source register and source
948     // source memory operand types are not the same width.  f32 vectors are
949     // custom since the immediate controlling the insert encodes additional
950     // information.
951     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
952     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
953     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
954     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
955
956     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
957     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
959     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
960
961     // FIXME: these should be Legal but thats only for the case where
962     // the index is constant.  For now custom expand to deal with that
963     if (Subtarget->is64Bit()) {
964       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
965       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
966     }
967   }
968
969   if (Subtarget->hasXMMInt()) {
970     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
971     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
972
973     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
974     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
975
976     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
977     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
978
979     if (Subtarget->hasAVX2()) {
980       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
981       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
982
983       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
984       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
985
986       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
987     } else {
988       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
989       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
990
991       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
992       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
993
994       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
995     }
996   }
997
998   if (Subtarget->hasSSE42orAVX())
999     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1000
1001   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1002     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
1003     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1004     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
1005     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
1006     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
1007     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
1008
1009     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1010     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1011     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1012
1013     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1014     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1015     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1016     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1017     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1018     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1019
1020     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1021     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1022     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1023     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1025     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1026
1027     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1028     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1029     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1030
1031     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1032     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1033     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1034     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1035     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1036     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1037
1038     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1039     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1040
1041     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1042     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1043
1044     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1045     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1046
1047     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1048     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1049     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1050     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1051
1052     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1053     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1054     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1057     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1058     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1059     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1060
1061     if (Subtarget->hasAVX2()) {
1062       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1063       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1064       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1065       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1066
1067       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1068       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1069       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1070       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1071
1072       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1073       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1074       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1075       // Don't lower v32i8 because there is no 128-bit byte mul
1076
1077       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1078
1079       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1080       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1081
1082       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1083       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1084
1085       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1086     } else {
1087       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1088       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1089       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1090       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1091
1092       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1093       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1094       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1095       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1096
1097       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1098       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1099       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1100       // Don't lower v32i8 because there is no 128-bit byte mul
1101
1102       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1103       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1104
1105       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1107
1108       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1109     }
1110
1111     // Custom lower several nodes for 256-bit types.
1112     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1113                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1114       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1115       EVT VT = SVT;
1116
1117       // Extract subvector is special because the value type
1118       // (result) is 128-bit but the source is 256-bit wide.
1119       if (VT.is128BitVector())
1120         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1121
1122       // Do not attempt to custom lower other non-256-bit vectors
1123       if (!VT.is256BitVector())
1124         continue;
1125
1126       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1127       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1128       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1129       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1130       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1131       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1132     }
1133
1134     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1135     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1136       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1137       EVT VT = SVT;
1138
1139       // Do not attempt to promote non-256-bit vectors
1140       if (!VT.is256BitVector())
1141         continue;
1142
1143       setOperationAction(ISD::AND,    SVT, Promote);
1144       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1145       setOperationAction(ISD::OR,     SVT, Promote);
1146       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1147       setOperationAction(ISD::XOR,    SVT, Promote);
1148       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1149       setOperationAction(ISD::LOAD,   SVT, Promote);
1150       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1151       setOperationAction(ISD::SELECT, SVT, Promote);
1152       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1153     }
1154   }
1155
1156   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1157   // of this type with custom code.
1158   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1159          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1160     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1161   }
1162
1163   // We want to custom lower some of our intrinsics.
1164   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1165
1166
1167   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1168   // handle type legalization for these operations here.
1169   //
1170   // FIXME: We really should do custom legalization for addition and
1171   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1172   // than generic legalization for 64-bit multiplication-with-overflow, though.
1173   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1174     // Add/Sub/Mul with overflow operations are custom lowered.
1175     MVT VT = IntVTs[i];
1176     setOperationAction(ISD::SADDO, VT, Custom);
1177     setOperationAction(ISD::UADDO, VT, Custom);
1178     setOperationAction(ISD::SSUBO, VT, Custom);
1179     setOperationAction(ISD::USUBO, VT, Custom);
1180     setOperationAction(ISD::SMULO, VT, Custom);
1181     setOperationAction(ISD::UMULO, VT, Custom);
1182   }
1183
1184   // There are no 8-bit 3-address imul/mul instructions
1185   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1186   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1187
1188   if (!Subtarget->is64Bit()) {
1189     // These libcalls are not available in 32-bit.
1190     setLibcallName(RTLIB::SHL_I128, 0);
1191     setLibcallName(RTLIB::SRL_I128, 0);
1192     setLibcallName(RTLIB::SRA_I128, 0);
1193   }
1194
1195   // We have target-specific dag combine patterns for the following nodes:
1196   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1197   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1198   setTargetDAGCombine(ISD::BUILD_VECTOR);
1199   setTargetDAGCombine(ISD::VSELECT);
1200   setTargetDAGCombine(ISD::SELECT);
1201   setTargetDAGCombine(ISD::SHL);
1202   setTargetDAGCombine(ISD::SRA);
1203   setTargetDAGCombine(ISD::SRL);
1204   setTargetDAGCombine(ISD::OR);
1205   setTargetDAGCombine(ISD::AND);
1206   setTargetDAGCombine(ISD::ADD);
1207   setTargetDAGCombine(ISD::FADD);
1208   setTargetDAGCombine(ISD::FSUB);
1209   setTargetDAGCombine(ISD::SUB);
1210   setTargetDAGCombine(ISD::LOAD);
1211   setTargetDAGCombine(ISD::STORE);
1212   setTargetDAGCombine(ISD::ZERO_EXTEND);
1213   setTargetDAGCombine(ISD::SINT_TO_FP);
1214   if (Subtarget->is64Bit())
1215     setTargetDAGCombine(ISD::MUL);
1216   if (Subtarget->hasBMI())
1217     setTargetDAGCombine(ISD::XOR);
1218
1219   computeRegisterProperties();
1220
1221   // On Darwin, -Os means optimize for size without hurting performance,
1222   // do not reduce the limit.
1223   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1224   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1225   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1226   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1227   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1228   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1229   setPrefLoopAlignment(4); // 2^4 bytes.
1230   benefitFromCodePlacementOpt = true;
1231
1232   setPrefFunctionAlignment(4); // 2^4 bytes.
1233 }
1234
1235
1236 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1237   if (!VT.isVector()) return MVT::i8;
1238   return VT.changeVectorElementTypeToInteger();
1239 }
1240
1241
1242 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1243 /// the desired ByVal argument alignment.
1244 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1245   if (MaxAlign == 16)
1246     return;
1247   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1248     if (VTy->getBitWidth() == 128)
1249       MaxAlign = 16;
1250   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1251     unsigned EltAlign = 0;
1252     getMaxByValAlign(ATy->getElementType(), EltAlign);
1253     if (EltAlign > MaxAlign)
1254       MaxAlign = EltAlign;
1255   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1256     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1257       unsigned EltAlign = 0;
1258       getMaxByValAlign(STy->getElementType(i), EltAlign);
1259       if (EltAlign > MaxAlign)
1260         MaxAlign = EltAlign;
1261       if (MaxAlign == 16)
1262         break;
1263     }
1264   }
1265   return;
1266 }
1267
1268 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1269 /// function arguments in the caller parameter area. For X86, aggregates
1270 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1271 /// are at 4-byte boundaries.
1272 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1273   if (Subtarget->is64Bit()) {
1274     // Max of 8 and alignment of type.
1275     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1276     if (TyAlign > 8)
1277       return TyAlign;
1278     return 8;
1279   }
1280
1281   unsigned Align = 4;
1282   if (Subtarget->hasXMM())
1283     getMaxByValAlign(Ty, Align);
1284   return Align;
1285 }
1286
1287 /// getOptimalMemOpType - Returns the target specific optimal type for load
1288 /// and store operations as a result of memset, memcpy, and memmove
1289 /// lowering. If DstAlign is zero that means it's safe to destination
1290 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1291 /// means there isn't a need to check it against alignment requirement,
1292 /// probably because the source does not need to be loaded. If
1293 /// 'IsZeroVal' is true, that means it's safe to return a
1294 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1295 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1296 /// constant so it does not need to be loaded.
1297 /// It returns EVT::Other if the type should be determined using generic
1298 /// target-independent logic.
1299 EVT
1300 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1301                                        unsigned DstAlign, unsigned SrcAlign,
1302                                        bool IsZeroVal,
1303                                        bool MemcpyStrSrc,
1304                                        MachineFunction &MF) const {
1305   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1306   // linux.  This is because the stack realignment code can't handle certain
1307   // cases like PR2962.  This should be removed when PR2962 is fixed.
1308   const Function *F = MF.getFunction();
1309   if (IsZeroVal &&
1310       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1311     if (Size >= 16 &&
1312         (Subtarget->isUnalignedMemAccessFast() ||
1313          ((DstAlign == 0 || DstAlign >= 16) &&
1314           (SrcAlign == 0 || SrcAlign >= 16))) &&
1315         Subtarget->getStackAlignment() >= 16) {
1316       if (Subtarget->hasAVX() &&
1317           Subtarget->getStackAlignment() >= 32)
1318         return MVT::v8f32;
1319       if (Subtarget->hasXMMInt())
1320         return MVT::v4i32;
1321       if (Subtarget->hasXMM())
1322         return MVT::v4f32;
1323     } else if (!MemcpyStrSrc && Size >= 8 &&
1324                !Subtarget->is64Bit() &&
1325                Subtarget->getStackAlignment() >= 8 &&
1326                Subtarget->hasXMMInt()) {
1327       // Do not use f64 to lower memcpy if source is string constant. It's
1328       // better to use i32 to avoid the loads.
1329       return MVT::f64;
1330     }
1331   }
1332   if (Subtarget->is64Bit() && Size >= 8)
1333     return MVT::i64;
1334   return MVT::i32;
1335 }
1336
1337 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1338 /// current function.  The returned value is a member of the
1339 /// MachineJumpTableInfo::JTEntryKind enum.
1340 unsigned X86TargetLowering::getJumpTableEncoding() const {
1341   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1342   // symbol.
1343   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1344       Subtarget->isPICStyleGOT())
1345     return MachineJumpTableInfo::EK_Custom32;
1346
1347   // Otherwise, use the normal jump table encoding heuristics.
1348   return TargetLowering::getJumpTableEncoding();
1349 }
1350
1351 const MCExpr *
1352 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1353                                              const MachineBasicBlock *MBB,
1354                                              unsigned uid,MCContext &Ctx) const{
1355   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1356          Subtarget->isPICStyleGOT());
1357   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1358   // entries.
1359   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1360                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1361 }
1362
1363 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1364 /// jumptable.
1365 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1366                                                     SelectionDAG &DAG) const {
1367   if (!Subtarget->is64Bit())
1368     // This doesn't have DebugLoc associated with it, but is not really the
1369     // same as a Register.
1370     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1371   return Table;
1372 }
1373
1374 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1375 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1376 /// MCExpr.
1377 const MCExpr *X86TargetLowering::
1378 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1379                              MCContext &Ctx) const {
1380   // X86-64 uses RIP relative addressing based on the jump table label.
1381   if (Subtarget->isPICStyleRIPRel())
1382     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1383
1384   // Otherwise, the reference is relative to the PIC base.
1385   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1386 }
1387
1388 // FIXME: Why this routine is here? Move to RegInfo!
1389 std::pair<const TargetRegisterClass*, uint8_t>
1390 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1391   const TargetRegisterClass *RRC = 0;
1392   uint8_t Cost = 1;
1393   switch (VT.getSimpleVT().SimpleTy) {
1394   default:
1395     return TargetLowering::findRepresentativeClass(VT);
1396   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1397     RRC = (Subtarget->is64Bit()
1398            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1399     break;
1400   case MVT::x86mmx:
1401     RRC = X86::VR64RegisterClass;
1402     break;
1403   case MVT::f32: case MVT::f64:
1404   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1405   case MVT::v4f32: case MVT::v2f64:
1406   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1407   case MVT::v4f64:
1408     RRC = X86::VR128RegisterClass;
1409     break;
1410   }
1411   return std::make_pair(RRC, Cost);
1412 }
1413
1414 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1415                                                unsigned &Offset) const {
1416   if (!Subtarget->isTargetLinux())
1417     return false;
1418
1419   if (Subtarget->is64Bit()) {
1420     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1421     Offset = 0x28;
1422     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1423       AddressSpace = 256;
1424     else
1425       AddressSpace = 257;
1426   } else {
1427     // %gs:0x14 on i386
1428     Offset = 0x14;
1429     AddressSpace = 256;
1430   }
1431   return true;
1432 }
1433
1434
1435 //===----------------------------------------------------------------------===//
1436 //               Return Value Calling Convention Implementation
1437 //===----------------------------------------------------------------------===//
1438
1439 #include "X86GenCallingConv.inc"
1440
1441 bool
1442 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1443                                   MachineFunction &MF, bool isVarArg,
1444                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1445                         LLVMContext &Context) const {
1446   SmallVector<CCValAssign, 16> RVLocs;
1447   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448                  RVLocs, Context);
1449   return CCInfo.CheckReturn(Outs, RetCC_X86);
1450 }
1451
1452 SDValue
1453 X86TargetLowering::LowerReturn(SDValue Chain,
1454                                CallingConv::ID CallConv, bool isVarArg,
1455                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1456                                const SmallVectorImpl<SDValue> &OutVals,
1457                                DebugLoc dl, SelectionDAG &DAG) const {
1458   MachineFunction &MF = DAG.getMachineFunction();
1459   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1460
1461   SmallVector<CCValAssign, 16> RVLocs;
1462   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1463                  RVLocs, *DAG.getContext());
1464   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1465
1466   // Add the regs to the liveout set for the function.
1467   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1468   for (unsigned i = 0; i != RVLocs.size(); ++i)
1469     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1470       MRI.addLiveOut(RVLocs[i].getLocReg());
1471
1472   SDValue Flag;
1473
1474   SmallVector<SDValue, 6> RetOps;
1475   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1476   // Operand #1 = Bytes To Pop
1477   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1478                    MVT::i16));
1479
1480   // Copy the result values into the output registers.
1481   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1482     CCValAssign &VA = RVLocs[i];
1483     assert(VA.isRegLoc() && "Can only return in registers!");
1484     SDValue ValToCopy = OutVals[i];
1485     EVT ValVT = ValToCopy.getValueType();
1486
1487     // If this is x86-64, and we disabled SSE, we can't return FP values,
1488     // or SSE or MMX vectors.
1489     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1490          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1491           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1492       report_fatal_error("SSE register return with SSE disabled");
1493     }
1494     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1495     // llvm-gcc has never done it right and no one has noticed, so this
1496     // should be OK for now.
1497     if (ValVT == MVT::f64 &&
1498         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1499       report_fatal_error("SSE2 register return with SSE2 disabled");
1500
1501     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1502     // the RET instruction and handled by the FP Stackifier.
1503     if (VA.getLocReg() == X86::ST0 ||
1504         VA.getLocReg() == X86::ST1) {
1505       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1506       // change the value to the FP stack register class.
1507       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1508         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1509       RetOps.push_back(ValToCopy);
1510       // Don't emit a copytoreg.
1511       continue;
1512     }
1513
1514     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1515     // which is returned in RAX / RDX.
1516     if (Subtarget->is64Bit()) {
1517       if (ValVT == MVT::x86mmx) {
1518         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1519           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1520           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1521                                   ValToCopy);
1522           // If we don't have SSE2 available, convert to v4f32 so the generated
1523           // register is legal.
1524           if (!Subtarget->hasXMMInt())
1525             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1526         }
1527       }
1528     }
1529
1530     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1531     Flag = Chain.getValue(1);
1532   }
1533
1534   // The x86-64 ABI for returning structs by value requires that we copy
1535   // the sret argument into %rax for the return. We saved the argument into
1536   // a virtual register in the entry block, so now we copy the value out
1537   // and into %rax.
1538   if (Subtarget->is64Bit() &&
1539       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1540     MachineFunction &MF = DAG.getMachineFunction();
1541     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1542     unsigned Reg = FuncInfo->getSRetReturnReg();
1543     assert(Reg &&
1544            "SRetReturnReg should have been set in LowerFormalArguments().");
1545     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1546
1547     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1548     Flag = Chain.getValue(1);
1549
1550     // RAX now acts like a return value.
1551     MRI.addLiveOut(X86::RAX);
1552   }
1553
1554   RetOps[0] = Chain;  // Update chain.
1555
1556   // Add the flag if we have it.
1557   if (Flag.getNode())
1558     RetOps.push_back(Flag);
1559
1560   return DAG.getNode(X86ISD::RET_FLAG, dl,
1561                      MVT::Other, &RetOps[0], RetOps.size());
1562 }
1563
1564 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1565   if (N->getNumValues() != 1)
1566     return false;
1567   if (!N->hasNUsesOfValue(1, 0))
1568     return false;
1569
1570   SDNode *Copy = *N->use_begin();
1571   if (Copy->getOpcode() != ISD::CopyToReg &&
1572       Copy->getOpcode() != ISD::FP_EXTEND)
1573     return false;
1574
1575   bool HasRet = false;
1576   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1577        UI != UE; ++UI) {
1578     if (UI->getOpcode() != X86ISD::RET_FLAG)
1579       return false;
1580     HasRet = true;
1581   }
1582
1583   return HasRet;
1584 }
1585
1586 EVT
1587 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1588                                             ISD::NodeType ExtendKind) const {
1589   MVT ReturnMVT;
1590   // TODO: Is this also valid on 32-bit?
1591   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1592     ReturnMVT = MVT::i8;
1593   else
1594     ReturnMVT = MVT::i32;
1595
1596   EVT MinVT = getRegisterType(Context, ReturnMVT);
1597   return VT.bitsLT(MinVT) ? MinVT : VT;
1598 }
1599
1600 /// LowerCallResult - Lower the result values of a call into the
1601 /// appropriate copies out of appropriate physical registers.
1602 ///
1603 SDValue
1604 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1605                                    CallingConv::ID CallConv, bool isVarArg,
1606                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1607                                    DebugLoc dl, SelectionDAG &DAG,
1608                                    SmallVectorImpl<SDValue> &InVals) const {
1609
1610   // Assign locations to each value returned by this call.
1611   SmallVector<CCValAssign, 16> RVLocs;
1612   bool Is64Bit = Subtarget->is64Bit();
1613   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1614                  getTargetMachine(), RVLocs, *DAG.getContext());
1615   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1616
1617   // Copy all of the result registers out of their specified physreg.
1618   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1619     CCValAssign &VA = RVLocs[i];
1620     EVT CopyVT = VA.getValVT();
1621
1622     // If this is x86-64, and we disabled SSE, we can't return FP values
1623     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1624         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1625       report_fatal_error("SSE register return with SSE disabled");
1626     }
1627
1628     SDValue Val;
1629
1630     // If this is a call to a function that returns an fp value on the floating
1631     // point stack, we must guarantee the the value is popped from the stack, so
1632     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1633     // if the return value is not used. We use the FpPOP_RETVAL instruction
1634     // instead.
1635     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1636       // If we prefer to use the value in xmm registers, copy it out as f80 and
1637       // use a truncate to move it from fp stack reg to xmm reg.
1638       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1639       SDValue Ops[] = { Chain, InFlag };
1640       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1641                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1642       Val = Chain.getValue(0);
1643
1644       // Round the f80 to the right size, which also moves it to the appropriate
1645       // xmm register.
1646       if (CopyVT != VA.getValVT())
1647         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1648                           // This truncation won't change the value.
1649                           DAG.getIntPtrConstant(1));
1650     } else {
1651       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1652                                  CopyVT, InFlag).getValue(1);
1653       Val = Chain.getValue(0);
1654     }
1655     InFlag = Chain.getValue(2);
1656     InVals.push_back(Val);
1657   }
1658
1659   return Chain;
1660 }
1661
1662
1663 //===----------------------------------------------------------------------===//
1664 //                C & StdCall & Fast Calling Convention implementation
1665 //===----------------------------------------------------------------------===//
1666 //  StdCall calling convention seems to be standard for many Windows' API
1667 //  routines and around. It differs from C calling convention just a little:
1668 //  callee should clean up the stack, not caller. Symbols should be also
1669 //  decorated in some fancy way :) It doesn't support any vector arguments.
1670 //  For info on fast calling convention see Fast Calling Convention (tail call)
1671 //  implementation LowerX86_32FastCCCallTo.
1672
1673 /// CallIsStructReturn - Determines whether a call uses struct return
1674 /// semantics.
1675 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1676   if (Outs.empty())
1677     return false;
1678
1679   return Outs[0].Flags.isSRet();
1680 }
1681
1682 /// ArgsAreStructReturn - Determines whether a function uses struct
1683 /// return semantics.
1684 static bool
1685 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1686   if (Ins.empty())
1687     return false;
1688
1689   return Ins[0].Flags.isSRet();
1690 }
1691
1692 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1693 /// by "Src" to address "Dst" with size and alignment information specified by
1694 /// the specific parameter attribute. The copy will be passed as a byval
1695 /// function parameter.
1696 static SDValue
1697 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1698                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1699                           DebugLoc dl) {
1700   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1701
1702   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1703                        /*isVolatile*/false, /*AlwaysInline=*/true,
1704                        MachinePointerInfo(), MachinePointerInfo());
1705 }
1706
1707 /// IsTailCallConvention - Return true if the calling convention is one that
1708 /// supports tail call optimization.
1709 static bool IsTailCallConvention(CallingConv::ID CC) {
1710   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1711 }
1712
1713 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1714   if (!CI->isTailCall())
1715     return false;
1716
1717   CallSite CS(CI);
1718   CallingConv::ID CalleeCC = CS.getCallingConv();
1719   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1720     return false;
1721
1722   return true;
1723 }
1724
1725 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1726 /// a tailcall target by changing its ABI.
1727 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1728                                    bool GuaranteedTailCallOpt) {
1729   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1730 }
1731
1732 SDValue
1733 X86TargetLowering::LowerMemArgument(SDValue Chain,
1734                                     CallingConv::ID CallConv,
1735                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1736                                     DebugLoc dl, SelectionDAG &DAG,
1737                                     const CCValAssign &VA,
1738                                     MachineFrameInfo *MFI,
1739                                     unsigned i) const {
1740   // Create the nodes corresponding to a load from this parameter slot.
1741   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1742   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1743                               getTargetMachine().Options.GuaranteedTailCallOpt);
1744   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1745   EVT ValVT;
1746
1747   // If value is passed by pointer we have address passed instead of the value
1748   // itself.
1749   if (VA.getLocInfo() == CCValAssign::Indirect)
1750     ValVT = VA.getLocVT();
1751   else
1752     ValVT = VA.getValVT();
1753
1754   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1755   // changed with more analysis.
1756   // In case of tail call optimization mark all arguments mutable. Since they
1757   // could be overwritten by lowering of arguments in case of a tail call.
1758   if (Flags.isByVal()) {
1759     unsigned Bytes = Flags.getByValSize();
1760     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1761     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1762     return DAG.getFrameIndex(FI, getPointerTy());
1763   } else {
1764     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1765                                     VA.getLocMemOffset(), isImmutable);
1766     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1767     return DAG.getLoad(ValVT, dl, Chain, FIN,
1768                        MachinePointerInfo::getFixedStack(FI),
1769                        false, false, false, 0);
1770   }
1771 }
1772
1773 SDValue
1774 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1775                                         CallingConv::ID CallConv,
1776                                         bool isVarArg,
1777                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1778                                         DebugLoc dl,
1779                                         SelectionDAG &DAG,
1780                                         SmallVectorImpl<SDValue> &InVals)
1781                                           const {
1782   MachineFunction &MF = DAG.getMachineFunction();
1783   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1784
1785   const Function* Fn = MF.getFunction();
1786   if (Fn->hasExternalLinkage() &&
1787       Subtarget->isTargetCygMing() &&
1788       Fn->getName() == "main")
1789     FuncInfo->setForceFramePointer(true);
1790
1791   MachineFrameInfo *MFI = MF.getFrameInfo();
1792   bool Is64Bit = Subtarget->is64Bit();
1793   bool IsWin64 = Subtarget->isTargetWin64();
1794
1795   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1796          "Var args not supported with calling convention fastcc or ghc");
1797
1798   // Assign locations to all of the incoming arguments.
1799   SmallVector<CCValAssign, 16> ArgLocs;
1800   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1801                  ArgLocs, *DAG.getContext());
1802
1803   // Allocate shadow area for Win64
1804   if (IsWin64) {
1805     CCInfo.AllocateStack(32, 8);
1806   }
1807
1808   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1809
1810   unsigned LastVal = ~0U;
1811   SDValue ArgValue;
1812   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1813     CCValAssign &VA = ArgLocs[i];
1814     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1815     // places.
1816     assert(VA.getValNo() != LastVal &&
1817            "Don't support value assigned to multiple locs yet");
1818     (void)LastVal;
1819     LastVal = VA.getValNo();
1820
1821     if (VA.isRegLoc()) {
1822       EVT RegVT = VA.getLocVT();
1823       TargetRegisterClass *RC = NULL;
1824       if (RegVT == MVT::i32)
1825         RC = X86::GR32RegisterClass;
1826       else if (Is64Bit && RegVT == MVT::i64)
1827         RC = X86::GR64RegisterClass;
1828       else if (RegVT == MVT::f32)
1829         RC = X86::FR32RegisterClass;
1830       else if (RegVT == MVT::f64)
1831         RC = X86::FR64RegisterClass;
1832       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1833         RC = X86::VR256RegisterClass;
1834       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1835         RC = X86::VR128RegisterClass;
1836       else if (RegVT == MVT::x86mmx)
1837         RC = X86::VR64RegisterClass;
1838       else
1839         llvm_unreachable("Unknown argument type!");
1840
1841       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1842       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1843
1844       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1845       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1846       // right size.
1847       if (VA.getLocInfo() == CCValAssign::SExt)
1848         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1849                                DAG.getValueType(VA.getValVT()));
1850       else if (VA.getLocInfo() == CCValAssign::ZExt)
1851         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1852                                DAG.getValueType(VA.getValVT()));
1853       else if (VA.getLocInfo() == CCValAssign::BCvt)
1854         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1855
1856       if (VA.isExtInLoc()) {
1857         // Handle MMX values passed in XMM regs.
1858         if (RegVT.isVector()) {
1859           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1860                                  ArgValue);
1861         } else
1862           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1863       }
1864     } else {
1865       assert(VA.isMemLoc());
1866       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1867     }
1868
1869     // If value is passed via pointer - do a load.
1870     if (VA.getLocInfo() == CCValAssign::Indirect)
1871       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1872                              MachinePointerInfo(), false, false, false, 0);
1873
1874     InVals.push_back(ArgValue);
1875   }
1876
1877   // The x86-64 ABI for returning structs by value requires that we copy
1878   // the sret argument into %rax for the return. Save the argument into
1879   // a virtual register so that we can access it from the return points.
1880   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1881     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1882     unsigned Reg = FuncInfo->getSRetReturnReg();
1883     if (!Reg) {
1884       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1885       FuncInfo->setSRetReturnReg(Reg);
1886     }
1887     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1888     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1889   }
1890
1891   unsigned StackSize = CCInfo.getNextStackOffset();
1892   // Align stack specially for tail calls.
1893   if (FuncIsMadeTailCallSafe(CallConv,
1894                              MF.getTarget().Options.GuaranteedTailCallOpt))
1895     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1896
1897   // If the function takes variable number of arguments, make a frame index for
1898   // the start of the first vararg value... for expansion of llvm.va_start.
1899   if (isVarArg) {
1900     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1901                     CallConv != CallingConv::X86_ThisCall)) {
1902       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1903     }
1904     if (Is64Bit) {
1905       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1906
1907       // FIXME: We should really autogenerate these arrays
1908       static const unsigned GPR64ArgRegsWin64[] = {
1909         X86::RCX, X86::RDX, X86::R8,  X86::R9
1910       };
1911       static const unsigned GPR64ArgRegs64Bit[] = {
1912         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1913       };
1914       static const unsigned XMMArgRegs64Bit[] = {
1915         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1916         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1917       };
1918       const unsigned *GPR64ArgRegs;
1919       unsigned NumXMMRegs = 0;
1920
1921       if (IsWin64) {
1922         // The XMM registers which might contain var arg parameters are shadowed
1923         // in their paired GPR.  So we only need to save the GPR to their home
1924         // slots.
1925         TotalNumIntRegs = 4;
1926         GPR64ArgRegs = GPR64ArgRegsWin64;
1927       } else {
1928         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1929         GPR64ArgRegs = GPR64ArgRegs64Bit;
1930
1931         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1932       }
1933       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1934                                                        TotalNumIntRegs);
1935
1936       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1937       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1938              "SSE register cannot be used when SSE is disabled!");
1939       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1940                NoImplicitFloatOps) &&
1941              "SSE register cannot be used when SSE is disabled!");
1942       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1943           !Subtarget->hasXMM())
1944         // Kernel mode asks for SSE to be disabled, so don't push them
1945         // on the stack.
1946         TotalNumXMMRegs = 0;
1947
1948       if (IsWin64) {
1949         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1950         // Get to the caller-allocated home save location.  Add 8 to account
1951         // for the return address.
1952         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1953         FuncInfo->setRegSaveFrameIndex(
1954           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1955         // Fixup to set vararg frame on shadow area (4 x i64).
1956         if (NumIntRegs < 4)
1957           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1958       } else {
1959         // For X86-64, if there are vararg parameters that are passed via
1960         // registers, then we must store them to their spots on the stack so they
1961         // may be loaded by deferencing the result of va_next.
1962         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1963         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1964         FuncInfo->setRegSaveFrameIndex(
1965           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1966                                false));
1967       }
1968
1969       // Store the integer parameter registers.
1970       SmallVector<SDValue, 8> MemOps;
1971       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1972                                         getPointerTy());
1973       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1974       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1975         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1976                                   DAG.getIntPtrConstant(Offset));
1977         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1978                                      X86::GR64RegisterClass);
1979         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1980         SDValue Store =
1981           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1982                        MachinePointerInfo::getFixedStack(
1983                          FuncInfo->getRegSaveFrameIndex(), Offset),
1984                        false, false, 0);
1985         MemOps.push_back(Store);
1986         Offset += 8;
1987       }
1988
1989       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1990         // Now store the XMM (fp + vector) parameter registers.
1991         SmallVector<SDValue, 11> SaveXMMOps;
1992         SaveXMMOps.push_back(Chain);
1993
1994         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1995         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1996         SaveXMMOps.push_back(ALVal);
1997
1998         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1999                                FuncInfo->getRegSaveFrameIndex()));
2000         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2001                                FuncInfo->getVarArgsFPOffset()));
2002
2003         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2004           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2005                                        X86::VR128RegisterClass);
2006           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2007           SaveXMMOps.push_back(Val);
2008         }
2009         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2010                                      MVT::Other,
2011                                      &SaveXMMOps[0], SaveXMMOps.size()));
2012       }
2013
2014       if (!MemOps.empty())
2015         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2016                             &MemOps[0], MemOps.size());
2017     }
2018   }
2019
2020   // Some CCs need callee pop.
2021   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2022                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2023     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2024   } else {
2025     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2026     // If this is an sret function, the return should pop the hidden pointer.
2027     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2028       FuncInfo->setBytesToPopOnReturn(4);
2029   }
2030
2031   if (!Is64Bit) {
2032     // RegSaveFrameIndex is X86-64 only.
2033     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2034     if (CallConv == CallingConv::X86_FastCall ||
2035         CallConv == CallingConv::X86_ThisCall)
2036       // fastcc functions can't have varargs.
2037       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2038   }
2039
2040   FuncInfo->setArgumentStackSize(StackSize);
2041
2042   return Chain;
2043 }
2044
2045 SDValue
2046 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2047                                     SDValue StackPtr, SDValue Arg,
2048                                     DebugLoc dl, SelectionDAG &DAG,
2049                                     const CCValAssign &VA,
2050                                     ISD::ArgFlagsTy Flags) const {
2051   unsigned LocMemOffset = VA.getLocMemOffset();
2052   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2053   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2054   if (Flags.isByVal())
2055     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2056
2057   return DAG.getStore(Chain, dl, Arg, PtrOff,
2058                       MachinePointerInfo::getStack(LocMemOffset),
2059                       false, false, 0);
2060 }
2061
2062 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2063 /// optimization is performed and it is required.
2064 SDValue
2065 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2066                                            SDValue &OutRetAddr, SDValue Chain,
2067                                            bool IsTailCall, bool Is64Bit,
2068                                            int FPDiff, DebugLoc dl) const {
2069   // Adjust the Return address stack slot.
2070   EVT VT = getPointerTy();
2071   OutRetAddr = getReturnAddressFrameIndex(DAG);
2072
2073   // Load the "old" Return address.
2074   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2075                            false, false, false, 0);
2076   return SDValue(OutRetAddr.getNode(), 1);
2077 }
2078
2079 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2080 /// optimization is performed and it is required (FPDiff!=0).
2081 static SDValue
2082 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2083                          SDValue Chain, SDValue RetAddrFrIdx,
2084                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2085   // Store the return address to the appropriate stack slot.
2086   if (!FPDiff) return Chain;
2087   // Calculate the new stack slot for the return address.
2088   int SlotSize = Is64Bit ? 8 : 4;
2089   int NewReturnAddrFI =
2090     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2091   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2092   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2093   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2094                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2095                        false, false, 0);
2096   return Chain;
2097 }
2098
2099 SDValue
2100 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2101                              CallingConv::ID CallConv, bool isVarArg,
2102                              bool &isTailCall,
2103                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2104                              const SmallVectorImpl<SDValue> &OutVals,
2105                              const SmallVectorImpl<ISD::InputArg> &Ins,
2106                              DebugLoc dl, SelectionDAG &DAG,
2107                              SmallVectorImpl<SDValue> &InVals) const {
2108   MachineFunction &MF = DAG.getMachineFunction();
2109   bool Is64Bit        = Subtarget->is64Bit();
2110   bool IsWin64        = Subtarget->isTargetWin64();
2111   bool IsStructRet    = CallIsStructReturn(Outs);
2112   bool IsSibcall      = false;
2113
2114   if (isTailCall) {
2115     // Check if it's really possible to do a tail call.
2116     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2117                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2118                                                    Outs, OutVals, Ins, DAG);
2119
2120     // Sibcalls are automatically detected tailcalls which do not require
2121     // ABI changes.
2122     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2123       IsSibcall = true;
2124
2125     if (isTailCall)
2126       ++NumTailCalls;
2127   }
2128
2129   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2130          "Var args not supported with calling convention fastcc or ghc");
2131
2132   // Analyze operands of the call, assigning locations to each operand.
2133   SmallVector<CCValAssign, 16> ArgLocs;
2134   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2135                  ArgLocs, *DAG.getContext());
2136
2137   // Allocate shadow area for Win64
2138   if (IsWin64) {
2139     CCInfo.AllocateStack(32, 8);
2140   }
2141
2142   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2143
2144   // Get a count of how many bytes are to be pushed on the stack.
2145   unsigned NumBytes = CCInfo.getNextStackOffset();
2146   if (IsSibcall)
2147     // This is a sibcall. The memory operands are available in caller's
2148     // own caller's stack.
2149     NumBytes = 0;
2150   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2151            IsTailCallConvention(CallConv))
2152     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2153
2154   int FPDiff = 0;
2155   if (isTailCall && !IsSibcall) {
2156     // Lower arguments at fp - stackoffset + fpdiff.
2157     unsigned NumBytesCallerPushed =
2158       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2159     FPDiff = NumBytesCallerPushed - NumBytes;
2160
2161     // Set the delta of movement of the returnaddr stackslot.
2162     // But only set if delta is greater than previous delta.
2163     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2164       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2165   }
2166
2167   if (!IsSibcall)
2168     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2169
2170   SDValue RetAddrFrIdx;
2171   // Load return address for tail calls.
2172   if (isTailCall && FPDiff)
2173     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2174                                     Is64Bit, FPDiff, dl);
2175
2176   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2177   SmallVector<SDValue, 8> MemOpChains;
2178   SDValue StackPtr;
2179
2180   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2181   // of tail call optimization arguments are handle later.
2182   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2183     CCValAssign &VA = ArgLocs[i];
2184     EVT RegVT = VA.getLocVT();
2185     SDValue Arg = OutVals[i];
2186     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2187     bool isByVal = Flags.isByVal();
2188
2189     // Promote the value if needed.
2190     switch (VA.getLocInfo()) {
2191     default: llvm_unreachable("Unknown loc info!");
2192     case CCValAssign::Full: break;
2193     case CCValAssign::SExt:
2194       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2195       break;
2196     case CCValAssign::ZExt:
2197       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2198       break;
2199     case CCValAssign::AExt:
2200       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2201         // Special case: passing MMX values in XMM registers.
2202         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2203         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2204         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2205       } else
2206         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2207       break;
2208     case CCValAssign::BCvt:
2209       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2210       break;
2211     case CCValAssign::Indirect: {
2212       // Store the argument.
2213       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2214       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2215       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2216                            MachinePointerInfo::getFixedStack(FI),
2217                            false, false, 0);
2218       Arg = SpillSlot;
2219       break;
2220     }
2221     }
2222
2223     if (VA.isRegLoc()) {
2224       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2225       if (isVarArg && IsWin64) {
2226         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2227         // shadow reg if callee is a varargs function.
2228         unsigned ShadowReg = 0;
2229         switch (VA.getLocReg()) {
2230         case X86::XMM0: ShadowReg = X86::RCX; break;
2231         case X86::XMM1: ShadowReg = X86::RDX; break;
2232         case X86::XMM2: ShadowReg = X86::R8; break;
2233         case X86::XMM3: ShadowReg = X86::R9; break;
2234         }
2235         if (ShadowReg)
2236           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2237       }
2238     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2239       assert(VA.isMemLoc());
2240       if (StackPtr.getNode() == 0)
2241         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2242       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2243                                              dl, DAG, VA, Flags));
2244     }
2245   }
2246
2247   if (!MemOpChains.empty())
2248     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2249                         &MemOpChains[0], MemOpChains.size());
2250
2251   // Build a sequence of copy-to-reg nodes chained together with token chain
2252   // and flag operands which copy the outgoing args into registers.
2253   SDValue InFlag;
2254   // Tail call byval lowering might overwrite argument registers so in case of
2255   // tail call optimization the copies to registers are lowered later.
2256   if (!isTailCall)
2257     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2258       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2259                                RegsToPass[i].second, InFlag);
2260       InFlag = Chain.getValue(1);
2261     }
2262
2263   if (Subtarget->isPICStyleGOT()) {
2264     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2265     // GOT pointer.
2266     if (!isTailCall) {
2267       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2268                                DAG.getNode(X86ISD::GlobalBaseReg,
2269                                            DebugLoc(), getPointerTy()),
2270                                InFlag);
2271       InFlag = Chain.getValue(1);
2272     } else {
2273       // If we are tail calling and generating PIC/GOT style code load the
2274       // address of the callee into ECX. The value in ecx is used as target of
2275       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2276       // for tail calls on PIC/GOT architectures. Normally we would just put the
2277       // address of GOT into ebx and then call target@PLT. But for tail calls
2278       // ebx would be restored (since ebx is callee saved) before jumping to the
2279       // target@PLT.
2280
2281       // Note: The actual moving to ECX is done further down.
2282       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2283       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2284           !G->getGlobal()->hasProtectedVisibility())
2285         Callee = LowerGlobalAddress(Callee, DAG);
2286       else if (isa<ExternalSymbolSDNode>(Callee))
2287         Callee = LowerExternalSymbol(Callee, DAG);
2288     }
2289   }
2290
2291   if (Is64Bit && isVarArg && !IsWin64) {
2292     // From AMD64 ABI document:
2293     // For calls that may call functions that use varargs or stdargs
2294     // (prototype-less calls or calls to functions containing ellipsis (...) in
2295     // the declaration) %al is used as hidden argument to specify the number
2296     // of SSE registers used. The contents of %al do not need to match exactly
2297     // the number of registers, but must be an ubound on the number of SSE
2298     // registers used and is in the range 0 - 8 inclusive.
2299
2300     // Count the number of XMM registers allocated.
2301     static const unsigned XMMArgRegs[] = {
2302       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2303       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2304     };
2305     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2306     assert((Subtarget->hasXMM() || !NumXMMRegs)
2307            && "SSE registers cannot be used when SSE is disabled");
2308
2309     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2310                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2311     InFlag = Chain.getValue(1);
2312   }
2313
2314
2315   // For tail calls lower the arguments to the 'real' stack slot.
2316   if (isTailCall) {
2317     // Force all the incoming stack arguments to be loaded from the stack
2318     // before any new outgoing arguments are stored to the stack, because the
2319     // outgoing stack slots may alias the incoming argument stack slots, and
2320     // the alias isn't otherwise explicit. This is slightly more conservative
2321     // than necessary, because it means that each store effectively depends
2322     // on every argument instead of just those arguments it would clobber.
2323     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2324
2325     SmallVector<SDValue, 8> MemOpChains2;
2326     SDValue FIN;
2327     int FI = 0;
2328     // Do not flag preceding copytoreg stuff together with the following stuff.
2329     InFlag = SDValue();
2330     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2331       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2332         CCValAssign &VA = ArgLocs[i];
2333         if (VA.isRegLoc())
2334           continue;
2335         assert(VA.isMemLoc());
2336         SDValue Arg = OutVals[i];
2337         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2338         // Create frame index.
2339         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2340         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2341         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2342         FIN = DAG.getFrameIndex(FI, getPointerTy());
2343
2344         if (Flags.isByVal()) {
2345           // Copy relative to framepointer.
2346           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2347           if (StackPtr.getNode() == 0)
2348             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2349                                           getPointerTy());
2350           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2351
2352           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2353                                                            ArgChain,
2354                                                            Flags, DAG, dl));
2355         } else {
2356           // Store relative to framepointer.
2357           MemOpChains2.push_back(
2358             DAG.getStore(ArgChain, dl, Arg, FIN,
2359                          MachinePointerInfo::getFixedStack(FI),
2360                          false, false, 0));
2361         }
2362       }
2363     }
2364
2365     if (!MemOpChains2.empty())
2366       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2367                           &MemOpChains2[0], MemOpChains2.size());
2368
2369     // Copy arguments to their registers.
2370     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2371       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2372                                RegsToPass[i].second, InFlag);
2373       InFlag = Chain.getValue(1);
2374     }
2375     InFlag =SDValue();
2376
2377     // Store the return address to the appropriate stack slot.
2378     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2379                                      FPDiff, dl);
2380   }
2381
2382   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2383     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2384     // In the 64-bit large code model, we have to make all calls
2385     // through a register, since the call instruction's 32-bit
2386     // pc-relative offset may not be large enough to hold the whole
2387     // address.
2388   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2389     // If the callee is a GlobalAddress node (quite common, every direct call
2390     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2391     // it.
2392
2393     // We should use extra load for direct calls to dllimported functions in
2394     // non-JIT mode.
2395     const GlobalValue *GV = G->getGlobal();
2396     if (!GV->hasDLLImportLinkage()) {
2397       unsigned char OpFlags = 0;
2398       bool ExtraLoad = false;
2399       unsigned WrapperKind = ISD::DELETED_NODE;
2400
2401       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2402       // external symbols most go through the PLT in PIC mode.  If the symbol
2403       // has hidden or protected visibility, or if it is static or local, then
2404       // we don't need to use the PLT - we can directly call it.
2405       if (Subtarget->isTargetELF() &&
2406           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2407           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2408         OpFlags = X86II::MO_PLT;
2409       } else if (Subtarget->isPICStyleStubAny() &&
2410                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2411                  (!Subtarget->getTargetTriple().isMacOSX() ||
2412                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2413         // PC-relative references to external symbols should go through $stub,
2414         // unless we're building with the leopard linker or later, which
2415         // automatically synthesizes these stubs.
2416         OpFlags = X86II::MO_DARWIN_STUB;
2417       } else if (Subtarget->isPICStyleRIPRel() &&
2418                  isa<Function>(GV) &&
2419                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2420         // If the function is marked as non-lazy, generate an indirect call
2421         // which loads from the GOT directly. This avoids runtime overhead
2422         // at the cost of eager binding (and one extra byte of encoding).
2423         OpFlags = X86II::MO_GOTPCREL;
2424         WrapperKind = X86ISD::WrapperRIP;
2425         ExtraLoad = true;
2426       }
2427
2428       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2429                                           G->getOffset(), OpFlags);
2430
2431       // Add a wrapper if needed.
2432       if (WrapperKind != ISD::DELETED_NODE)
2433         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2434       // Add extra indirection if needed.
2435       if (ExtraLoad)
2436         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2437                              MachinePointerInfo::getGOT(),
2438                              false, false, false, 0);
2439     }
2440   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2441     unsigned char OpFlags = 0;
2442
2443     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2444     // external symbols should go through the PLT.
2445     if (Subtarget->isTargetELF() &&
2446         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2447       OpFlags = X86II::MO_PLT;
2448     } else if (Subtarget->isPICStyleStubAny() &&
2449                (!Subtarget->getTargetTriple().isMacOSX() ||
2450                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2451       // PC-relative references to external symbols should go through $stub,
2452       // unless we're building with the leopard linker or later, which
2453       // automatically synthesizes these stubs.
2454       OpFlags = X86II::MO_DARWIN_STUB;
2455     }
2456
2457     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2458                                          OpFlags);
2459   }
2460
2461   // Returns a chain & a flag for retval copy to use.
2462   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2463   SmallVector<SDValue, 8> Ops;
2464
2465   if (!IsSibcall && isTailCall) {
2466     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2467                            DAG.getIntPtrConstant(0, true), InFlag);
2468     InFlag = Chain.getValue(1);
2469   }
2470
2471   Ops.push_back(Chain);
2472   Ops.push_back(Callee);
2473
2474   if (isTailCall)
2475     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2476
2477   // Add argument registers to the end of the list so that they are known live
2478   // into the call.
2479   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2480     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2481                                   RegsToPass[i].second.getValueType()));
2482
2483   // Add an implicit use GOT pointer in EBX.
2484   if (!isTailCall && Subtarget->isPICStyleGOT())
2485     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2486
2487   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2488   if (Is64Bit && isVarArg && !IsWin64)
2489     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2490
2491   if (InFlag.getNode())
2492     Ops.push_back(InFlag);
2493
2494   if (isTailCall) {
2495     // We used to do:
2496     //// If this is the first return lowered for this function, add the regs
2497     //// to the liveout set for the function.
2498     // This isn't right, although it's probably harmless on x86; liveouts
2499     // should be computed from returns not tail calls.  Consider a void
2500     // function making a tail call to a function returning int.
2501     return DAG.getNode(X86ISD::TC_RETURN, dl,
2502                        NodeTys, &Ops[0], Ops.size());
2503   }
2504
2505   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2506   InFlag = Chain.getValue(1);
2507
2508   // Create the CALLSEQ_END node.
2509   unsigned NumBytesForCalleeToPush;
2510   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2511                        getTargetMachine().Options.GuaranteedTailCallOpt))
2512     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2513   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2514     // If this is a call to a struct-return function, the callee
2515     // pops the hidden struct pointer, so we have to push it back.
2516     // This is common for Darwin/X86, Linux & Mingw32 targets.
2517     NumBytesForCalleeToPush = 4;
2518   else
2519     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2520
2521   // Returns a flag for retval copy to use.
2522   if (!IsSibcall) {
2523     Chain = DAG.getCALLSEQ_END(Chain,
2524                                DAG.getIntPtrConstant(NumBytes, true),
2525                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2526                                                      true),
2527                                InFlag);
2528     InFlag = Chain.getValue(1);
2529   }
2530
2531   // Handle result values, copying them out of physregs into vregs that we
2532   // return.
2533   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2534                          Ins, dl, DAG, InVals);
2535 }
2536
2537
2538 //===----------------------------------------------------------------------===//
2539 //                Fast Calling Convention (tail call) implementation
2540 //===----------------------------------------------------------------------===//
2541
2542 //  Like std call, callee cleans arguments, convention except that ECX is
2543 //  reserved for storing the tail called function address. Only 2 registers are
2544 //  free for argument passing (inreg). Tail call optimization is performed
2545 //  provided:
2546 //                * tailcallopt is enabled
2547 //                * caller/callee are fastcc
2548 //  On X86_64 architecture with GOT-style position independent code only local
2549 //  (within module) calls are supported at the moment.
2550 //  To keep the stack aligned according to platform abi the function
2551 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2552 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2553 //  If a tail called function callee has more arguments than the caller the
2554 //  caller needs to make sure that there is room to move the RETADDR to. This is
2555 //  achieved by reserving an area the size of the argument delta right after the
2556 //  original REtADDR, but before the saved framepointer or the spilled registers
2557 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2558 //  stack layout:
2559 //    arg1
2560 //    arg2
2561 //    RETADDR
2562 //    [ new RETADDR
2563 //      move area ]
2564 //    (possible EBP)
2565 //    ESI
2566 //    EDI
2567 //    local1 ..
2568
2569 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2570 /// for a 16 byte align requirement.
2571 unsigned
2572 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2573                                                SelectionDAG& DAG) const {
2574   MachineFunction &MF = DAG.getMachineFunction();
2575   const TargetMachine &TM = MF.getTarget();
2576   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2577   unsigned StackAlignment = TFI.getStackAlignment();
2578   uint64_t AlignMask = StackAlignment - 1;
2579   int64_t Offset = StackSize;
2580   uint64_t SlotSize = TD->getPointerSize();
2581   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2582     // Number smaller than 12 so just add the difference.
2583     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2584   } else {
2585     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2586     Offset = ((~AlignMask) & Offset) + StackAlignment +
2587       (StackAlignment-SlotSize);
2588   }
2589   return Offset;
2590 }
2591
2592 /// MatchingStackOffset - Return true if the given stack call argument is
2593 /// already available in the same position (relatively) of the caller's
2594 /// incoming argument stack.
2595 static
2596 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2597                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2598                          const X86InstrInfo *TII) {
2599   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2600   int FI = INT_MAX;
2601   if (Arg.getOpcode() == ISD::CopyFromReg) {
2602     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2603     if (!TargetRegisterInfo::isVirtualRegister(VR))
2604       return false;
2605     MachineInstr *Def = MRI->getVRegDef(VR);
2606     if (!Def)
2607       return false;
2608     if (!Flags.isByVal()) {
2609       if (!TII->isLoadFromStackSlot(Def, FI))
2610         return false;
2611     } else {
2612       unsigned Opcode = Def->getOpcode();
2613       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2614           Def->getOperand(1).isFI()) {
2615         FI = Def->getOperand(1).getIndex();
2616         Bytes = Flags.getByValSize();
2617       } else
2618         return false;
2619     }
2620   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2621     if (Flags.isByVal())
2622       // ByVal argument is passed in as a pointer but it's now being
2623       // dereferenced. e.g.
2624       // define @foo(%struct.X* %A) {
2625       //   tail call @bar(%struct.X* byval %A)
2626       // }
2627       return false;
2628     SDValue Ptr = Ld->getBasePtr();
2629     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2630     if (!FINode)
2631       return false;
2632     FI = FINode->getIndex();
2633   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2634     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2635     FI = FINode->getIndex();
2636     Bytes = Flags.getByValSize();
2637   } else
2638     return false;
2639
2640   assert(FI != INT_MAX);
2641   if (!MFI->isFixedObjectIndex(FI))
2642     return false;
2643   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2644 }
2645
2646 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2647 /// for tail call optimization. Targets which want to do tail call
2648 /// optimization should implement this function.
2649 bool
2650 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2651                                                      CallingConv::ID CalleeCC,
2652                                                      bool isVarArg,
2653                                                      bool isCalleeStructRet,
2654                                                      bool isCallerStructRet,
2655                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2656                                     const SmallVectorImpl<SDValue> &OutVals,
2657                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2658                                                      SelectionDAG& DAG) const {
2659   if (!IsTailCallConvention(CalleeCC) &&
2660       CalleeCC != CallingConv::C)
2661     return false;
2662
2663   // If -tailcallopt is specified, make fastcc functions tail-callable.
2664   const MachineFunction &MF = DAG.getMachineFunction();
2665   const Function *CallerF = DAG.getMachineFunction().getFunction();
2666   CallingConv::ID CallerCC = CallerF->getCallingConv();
2667   bool CCMatch = CallerCC == CalleeCC;
2668
2669   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2670     if (IsTailCallConvention(CalleeCC) && CCMatch)
2671       return true;
2672     return false;
2673   }
2674
2675   // Look for obvious safe cases to perform tail call optimization that do not
2676   // require ABI changes. This is what gcc calls sibcall.
2677
2678   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2679   // emit a special epilogue.
2680   if (RegInfo->needsStackRealignment(MF))
2681     return false;
2682
2683   // Also avoid sibcall optimization if either caller or callee uses struct
2684   // return semantics.
2685   if (isCalleeStructRet || isCallerStructRet)
2686     return false;
2687
2688   // An stdcall caller is expected to clean up its arguments; the callee
2689   // isn't going to do that.
2690   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2691     return false;
2692
2693   // Do not sibcall optimize vararg calls unless all arguments are passed via
2694   // registers.
2695   if (isVarArg && !Outs.empty()) {
2696
2697     // Optimizing for varargs on Win64 is unlikely to be safe without
2698     // additional testing.
2699     if (Subtarget->isTargetWin64())
2700       return false;
2701
2702     SmallVector<CCValAssign, 16> ArgLocs;
2703     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2704                    getTargetMachine(), ArgLocs, *DAG.getContext());
2705
2706     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2707     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2708       if (!ArgLocs[i].isRegLoc())
2709         return false;
2710   }
2711
2712   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2713   // Therefore if it's not used by the call it is not safe to optimize this into
2714   // a sibcall.
2715   bool Unused = false;
2716   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2717     if (!Ins[i].Used) {
2718       Unused = true;
2719       break;
2720     }
2721   }
2722   if (Unused) {
2723     SmallVector<CCValAssign, 16> RVLocs;
2724     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2725                    getTargetMachine(), RVLocs, *DAG.getContext());
2726     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2727     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2728       CCValAssign &VA = RVLocs[i];
2729       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2730         return false;
2731     }
2732   }
2733
2734   // If the calling conventions do not match, then we'd better make sure the
2735   // results are returned in the same way as what the caller expects.
2736   if (!CCMatch) {
2737     SmallVector<CCValAssign, 16> RVLocs1;
2738     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2739                     getTargetMachine(), RVLocs1, *DAG.getContext());
2740     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2741
2742     SmallVector<CCValAssign, 16> RVLocs2;
2743     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2744                     getTargetMachine(), RVLocs2, *DAG.getContext());
2745     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2746
2747     if (RVLocs1.size() != RVLocs2.size())
2748       return false;
2749     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2750       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2751         return false;
2752       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2753         return false;
2754       if (RVLocs1[i].isRegLoc()) {
2755         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2756           return false;
2757       } else {
2758         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2759           return false;
2760       }
2761     }
2762   }
2763
2764   // If the callee takes no arguments then go on to check the results of the
2765   // call.
2766   if (!Outs.empty()) {
2767     // Check if stack adjustment is needed. For now, do not do this if any
2768     // argument is passed on the stack.
2769     SmallVector<CCValAssign, 16> ArgLocs;
2770     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2771                    getTargetMachine(), ArgLocs, *DAG.getContext());
2772
2773     // Allocate shadow area for Win64
2774     if (Subtarget->isTargetWin64()) {
2775       CCInfo.AllocateStack(32, 8);
2776     }
2777
2778     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2779     if (CCInfo.getNextStackOffset()) {
2780       MachineFunction &MF = DAG.getMachineFunction();
2781       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2782         return false;
2783
2784       // Check if the arguments are already laid out in the right way as
2785       // the caller's fixed stack objects.
2786       MachineFrameInfo *MFI = MF.getFrameInfo();
2787       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2788       const X86InstrInfo *TII =
2789         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2790       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791         CCValAssign &VA = ArgLocs[i];
2792         SDValue Arg = OutVals[i];
2793         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2794         if (VA.getLocInfo() == CCValAssign::Indirect)
2795           return false;
2796         if (!VA.isRegLoc()) {
2797           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2798                                    MFI, MRI, TII))
2799             return false;
2800         }
2801       }
2802     }
2803
2804     // If the tailcall address may be in a register, then make sure it's
2805     // possible to register allocate for it. In 32-bit, the call address can
2806     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2807     // callee-saved registers are restored. These happen to be the same
2808     // registers used to pass 'inreg' arguments so watch out for those.
2809     if (!Subtarget->is64Bit() &&
2810         !isa<GlobalAddressSDNode>(Callee) &&
2811         !isa<ExternalSymbolSDNode>(Callee)) {
2812       unsigned NumInRegs = 0;
2813       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2814         CCValAssign &VA = ArgLocs[i];
2815         if (!VA.isRegLoc())
2816           continue;
2817         unsigned Reg = VA.getLocReg();
2818         switch (Reg) {
2819         default: break;
2820         case X86::EAX: case X86::EDX: case X86::ECX:
2821           if (++NumInRegs == 3)
2822             return false;
2823           break;
2824         }
2825       }
2826     }
2827   }
2828
2829   return true;
2830 }
2831
2832 FastISel *
2833 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2834   return X86::createFastISel(funcInfo);
2835 }
2836
2837
2838 //===----------------------------------------------------------------------===//
2839 //                           Other Lowering Hooks
2840 //===----------------------------------------------------------------------===//
2841
2842 static bool MayFoldLoad(SDValue Op) {
2843   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2844 }
2845
2846 static bool MayFoldIntoStore(SDValue Op) {
2847   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2848 }
2849
2850 static bool isTargetShuffle(unsigned Opcode) {
2851   switch(Opcode) {
2852   default: return false;
2853   case X86ISD::PSHUFD:
2854   case X86ISD::PSHUFHW:
2855   case X86ISD::PSHUFLW:
2856   case X86ISD::SHUFPD:
2857   case X86ISD::PALIGN:
2858   case X86ISD::SHUFPS:
2859   case X86ISD::MOVLHPS:
2860   case X86ISD::MOVLHPD:
2861   case X86ISD::MOVHLPS:
2862   case X86ISD::MOVLPS:
2863   case X86ISD::MOVLPD:
2864   case X86ISD::MOVSHDUP:
2865   case X86ISD::MOVSLDUP:
2866   case X86ISD::MOVDDUP:
2867   case X86ISD::MOVSS:
2868   case X86ISD::MOVSD:
2869   case X86ISD::UNPCKL:
2870   case X86ISD::UNPCKH:
2871   case X86ISD::VPERMILP:
2872   case X86ISD::VPERM2X128:
2873     return true;
2874   }
2875   return false;
2876 }
2877
2878 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2879                                                SDValue V1, SelectionDAG &DAG) {
2880   switch(Opc) {
2881   default: llvm_unreachable("Unknown x86 shuffle node");
2882   case X86ISD::MOVSHDUP:
2883   case X86ISD::MOVSLDUP:
2884   case X86ISD::MOVDDUP:
2885     return DAG.getNode(Opc, dl, VT, V1);
2886   }
2887
2888   return SDValue();
2889 }
2890
2891 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2892                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2893   switch(Opc) {
2894   default: llvm_unreachable("Unknown x86 shuffle node");
2895   case X86ISD::PSHUFD:
2896   case X86ISD::PSHUFHW:
2897   case X86ISD::PSHUFLW:
2898   case X86ISD::VPERMILP:
2899     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2900   }
2901
2902   return SDValue();
2903 }
2904
2905 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2906                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2907   switch(Opc) {
2908   default: llvm_unreachable("Unknown x86 shuffle node");
2909   case X86ISD::PALIGN:
2910   case X86ISD::SHUFPD:
2911   case X86ISD::SHUFPS:
2912   case X86ISD::VPERM2X128:
2913     return DAG.getNode(Opc, dl, VT, V1, V2,
2914                        DAG.getConstant(TargetMask, MVT::i8));
2915   }
2916   return SDValue();
2917 }
2918
2919 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2920                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2921   switch(Opc) {
2922   default: llvm_unreachable("Unknown x86 shuffle node");
2923   case X86ISD::MOVLHPS:
2924   case X86ISD::MOVLHPD:
2925   case X86ISD::MOVHLPS:
2926   case X86ISD::MOVLPS:
2927   case X86ISD::MOVLPD:
2928   case X86ISD::MOVSS:
2929   case X86ISD::MOVSD:
2930   case X86ISD::UNPCKL:
2931   case X86ISD::UNPCKH:
2932     return DAG.getNode(Opc, dl, VT, V1, V2);
2933   }
2934   return SDValue();
2935 }
2936
2937 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2940   int ReturnAddrIndex = FuncInfo->getRAIndex();
2941
2942   if (ReturnAddrIndex == 0) {
2943     // Set up a frame object for the return address.
2944     uint64_t SlotSize = TD->getPointerSize();
2945     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2946                                                            false);
2947     FuncInfo->setRAIndex(ReturnAddrIndex);
2948   }
2949
2950   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2951 }
2952
2953
2954 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2955                                        bool hasSymbolicDisplacement) {
2956   // Offset should fit into 32 bit immediate field.
2957   if (!isInt<32>(Offset))
2958     return false;
2959
2960   // If we don't have a symbolic displacement - we don't have any extra
2961   // restrictions.
2962   if (!hasSymbolicDisplacement)
2963     return true;
2964
2965   // FIXME: Some tweaks might be needed for medium code model.
2966   if (M != CodeModel::Small && M != CodeModel::Kernel)
2967     return false;
2968
2969   // For small code model we assume that latest object is 16MB before end of 31
2970   // bits boundary. We may also accept pretty large negative constants knowing
2971   // that all objects are in the positive half of address space.
2972   if (M == CodeModel::Small && Offset < 16*1024*1024)
2973     return true;
2974
2975   // For kernel code model we know that all object resist in the negative half
2976   // of 32bits address space. We may not accept negative offsets, since they may
2977   // be just off and we may accept pretty large positive ones.
2978   if (M == CodeModel::Kernel && Offset > 0)
2979     return true;
2980
2981   return false;
2982 }
2983
2984 /// isCalleePop - Determines whether the callee is required to pop its
2985 /// own arguments. Callee pop is necessary to support tail calls.
2986 bool X86::isCalleePop(CallingConv::ID CallingConv,
2987                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2988   if (IsVarArg)
2989     return false;
2990
2991   switch (CallingConv) {
2992   default:
2993     return false;
2994   case CallingConv::X86_StdCall:
2995     return !is64Bit;
2996   case CallingConv::X86_FastCall:
2997     return !is64Bit;
2998   case CallingConv::X86_ThisCall:
2999     return !is64Bit;
3000   case CallingConv::Fast:
3001     return TailCallOpt;
3002   case CallingConv::GHC:
3003     return TailCallOpt;
3004   }
3005 }
3006
3007 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3008 /// specific condition code, returning the condition code and the LHS/RHS of the
3009 /// comparison to make.
3010 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3011                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3012   if (!isFP) {
3013     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3014       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3015         // X > -1   -> X == 0, jump !sign.
3016         RHS = DAG.getConstant(0, RHS.getValueType());
3017         return X86::COND_NS;
3018       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3019         // X < 0   -> X == 0, jump on sign.
3020         return X86::COND_S;
3021       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3022         // X < 1   -> X <= 0
3023         RHS = DAG.getConstant(0, RHS.getValueType());
3024         return X86::COND_LE;
3025       }
3026     }
3027
3028     switch (SetCCOpcode) {
3029     default: llvm_unreachable("Invalid integer condition!");
3030     case ISD::SETEQ:  return X86::COND_E;
3031     case ISD::SETGT:  return X86::COND_G;
3032     case ISD::SETGE:  return X86::COND_GE;
3033     case ISD::SETLT:  return X86::COND_L;
3034     case ISD::SETLE:  return X86::COND_LE;
3035     case ISD::SETNE:  return X86::COND_NE;
3036     case ISD::SETULT: return X86::COND_B;
3037     case ISD::SETUGT: return X86::COND_A;
3038     case ISD::SETULE: return X86::COND_BE;
3039     case ISD::SETUGE: return X86::COND_AE;
3040     }
3041   }
3042
3043   // First determine if it is required or is profitable to flip the operands.
3044
3045   // If LHS is a foldable load, but RHS is not, flip the condition.
3046   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3047       !ISD::isNON_EXTLoad(RHS.getNode())) {
3048     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3049     std::swap(LHS, RHS);
3050   }
3051
3052   switch (SetCCOpcode) {
3053   default: break;
3054   case ISD::SETOLT:
3055   case ISD::SETOLE:
3056   case ISD::SETUGT:
3057   case ISD::SETUGE:
3058     std::swap(LHS, RHS);
3059     break;
3060   }
3061
3062   // On a floating point condition, the flags are set as follows:
3063   // ZF  PF  CF   op
3064   //  0 | 0 | 0 | X > Y
3065   //  0 | 0 | 1 | X < Y
3066   //  1 | 0 | 0 | X == Y
3067   //  1 | 1 | 1 | unordered
3068   switch (SetCCOpcode) {
3069   default: llvm_unreachable("Condcode should be pre-legalized away");
3070   case ISD::SETUEQ:
3071   case ISD::SETEQ:   return X86::COND_E;
3072   case ISD::SETOLT:              // flipped
3073   case ISD::SETOGT:
3074   case ISD::SETGT:   return X86::COND_A;
3075   case ISD::SETOLE:              // flipped
3076   case ISD::SETOGE:
3077   case ISD::SETGE:   return X86::COND_AE;
3078   case ISD::SETUGT:              // flipped
3079   case ISD::SETULT:
3080   case ISD::SETLT:   return X86::COND_B;
3081   case ISD::SETUGE:              // flipped
3082   case ISD::SETULE:
3083   case ISD::SETLE:   return X86::COND_BE;
3084   case ISD::SETONE:
3085   case ISD::SETNE:   return X86::COND_NE;
3086   case ISD::SETUO:   return X86::COND_P;
3087   case ISD::SETO:    return X86::COND_NP;
3088   case ISD::SETOEQ:
3089   case ISD::SETUNE:  return X86::COND_INVALID;
3090   }
3091 }
3092
3093 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3094 /// code. Current x86 isa includes the following FP cmov instructions:
3095 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3096 static bool hasFPCMov(unsigned X86CC) {
3097   switch (X86CC) {
3098   default:
3099     return false;
3100   case X86::COND_B:
3101   case X86::COND_BE:
3102   case X86::COND_E:
3103   case X86::COND_P:
3104   case X86::COND_A:
3105   case X86::COND_AE:
3106   case X86::COND_NE:
3107   case X86::COND_NP:
3108     return true;
3109   }
3110 }
3111
3112 /// isFPImmLegal - Returns true if the target can instruction select the
3113 /// specified FP immediate natively. If false, the legalizer will
3114 /// materialize the FP immediate as a load from a constant pool.
3115 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3116   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3117     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3118       return true;
3119   }
3120   return false;
3121 }
3122
3123 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3124 /// the specified range (L, H].
3125 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3126   return (Val < 0) || (Val >= Low && Val < Hi);
3127 }
3128
3129 /// isUndefOrInRange - Return true if every element in Mask, begining
3130 /// from position Pos and ending in Pos+Size, falls within the specified
3131 /// range (L, L+Pos]. or is undef.
3132 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3133                              int Pos, int Size, int Low, int Hi) {
3134   for (int i = Pos, e = Pos+Size; i != e; ++i)
3135     if (!isUndefOrInRange(Mask[i], Low, Hi))
3136       return false;
3137   return true;
3138 }
3139
3140 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3141 /// specified value.
3142 static bool isUndefOrEqual(int Val, int CmpVal) {
3143   if (Val < 0 || Val == CmpVal)
3144     return true;
3145   return false;
3146 }
3147
3148 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3149 /// from position Pos and ending in Pos+Size, falls within the specified
3150 /// sequential range (L, L+Pos]. or is undef.
3151 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3152                                        int Pos, int Size, int Low) {
3153   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3154     if (!isUndefOrEqual(Mask[i], Low))
3155       return false;
3156   return true;
3157 }
3158
3159 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3160 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3161 /// the second operand.
3162 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3163   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3164     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3165   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3166     return (Mask[0] < 2 && Mask[1] < 2);
3167   return false;
3168 }
3169
3170 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3171   SmallVector<int, 8> M;
3172   N->getMask(M);
3173   return ::isPSHUFDMask(M, N->getValueType(0));
3174 }
3175
3176 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3177 /// is suitable for input to PSHUFHW.
3178 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3179   if (VT != MVT::v8i16)
3180     return false;
3181
3182   // Lower quadword copied in order or undef.
3183   for (int i = 0; i != 4; ++i)
3184     if (Mask[i] >= 0 && Mask[i] != i)
3185       return false;
3186
3187   // Upper quadword shuffled.
3188   for (int i = 4; i != 8; ++i)
3189     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3190       return false;
3191
3192   return true;
3193 }
3194
3195 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3196   SmallVector<int, 8> M;
3197   N->getMask(M);
3198   return ::isPSHUFHWMask(M, N->getValueType(0));
3199 }
3200
3201 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3202 /// is suitable for input to PSHUFLW.
3203 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3204   if (VT != MVT::v8i16)
3205     return false;
3206
3207   // Upper quadword copied in order.
3208   for (int i = 4; i != 8; ++i)
3209     if (Mask[i] >= 0 && Mask[i] != i)
3210       return false;
3211
3212   // Lower quadword shuffled.
3213   for (int i = 0; i != 4; ++i)
3214     if (Mask[i] >= 4)
3215       return false;
3216
3217   return true;
3218 }
3219
3220 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3221   SmallVector<int, 8> M;
3222   N->getMask(M);
3223   return ::isPSHUFLWMask(M, N->getValueType(0));
3224 }
3225
3226 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3227 /// is suitable for input to PALIGNR.
3228 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3229                           bool hasSSSE3OrAVX) {
3230   int i, e = VT.getVectorNumElements();
3231   if (VT.getSizeInBits() != 128)
3232     return false;
3233
3234   // Do not handle v2i64 / v2f64 shuffles with palignr.
3235   if (e < 4 || !hasSSSE3OrAVX)
3236     return false;
3237
3238   for (i = 0; i != e; ++i)
3239     if (Mask[i] >= 0)
3240       break;
3241
3242   // All undef, not a palignr.
3243   if (i == e)
3244     return false;
3245
3246   // Make sure we're shifting in the right direction.
3247   if (Mask[i] <= i)
3248     return false;
3249
3250   int s = Mask[i] - i;
3251
3252   // Check the rest of the elements to see if they are consecutive.
3253   for (++i; i != e; ++i) {
3254     int m = Mask[i];
3255     if (m >= 0 && m != s+i)
3256       return false;
3257   }
3258   return true;
3259 }
3260
3261 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3262 /// specifies a shuffle of elements that is suitable for input to 256-bit
3263 /// VSHUFPSY.
3264 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3265                           bool HasAVX, bool Commuted = false) {
3266   int NumElems = VT.getVectorNumElements();
3267
3268   if (!HasAVX || VT.getSizeInBits() != 256)
3269     return false;
3270
3271   if (NumElems != 4 && NumElems != 8)
3272     return false;
3273
3274   // VSHUFPSY divides the resulting vector into 4 chunks.
3275   // The sources are also splitted into 4 chunks, and each destination
3276   // chunk must come from a different source chunk.
3277   //
3278   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3279   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3280   //
3281   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3282   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3283   //
3284   // VSHUFPDY divides the resulting vector into 4 chunks.
3285   // The sources are also splitted into 4 chunks, and each destination
3286   // chunk must come from a different source chunk.
3287   //
3288   //  SRC1 =>      X3       X2       X1       X0
3289   //  SRC2 =>      Y3       Y2       Y1       Y0
3290   //
3291   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3292   //
3293   unsigned QuarterSize = NumElems/4;
3294   unsigned HalfSize = QuarterSize*2;
3295   for (unsigned l = 0; l != 2; ++l) {
3296     unsigned LaneStart = l*HalfSize;
3297     for (unsigned s = 0; s != 2; ++s) {
3298       unsigned QuarterStart = s*QuarterSize;
3299       unsigned Src = (Commuted) ? (1-s) : s;
3300       unsigned SrcStart = Src*NumElems + LaneStart;
3301       for (unsigned i = 0; i != QuarterSize; ++i) {
3302         int Idx = Mask[i+QuarterStart+LaneStart];
3303         if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3304           return false;
3305         // For VSHUFPSY, the mask of the second half must be the same as the first
3306         // but with the appropriate offsets. This works in the same way as
3307         // VPERMILPS works with masks.
3308         if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3309           continue;
3310         if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3311           return false;
3312       }
3313     }
3314   }
3315
3316   return true;
3317 }
3318
3319 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3320 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3321 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3322   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3323   EVT VT = SVOp->getValueType(0);
3324   int NumElems = VT.getVectorNumElements();
3325
3326   assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3327   assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3328
3329   int HalfSize = NumElems/2;
3330   unsigned Mul = (NumElems == 8) ? 2 : 1;
3331   unsigned Mask = 0;
3332   for (int i = 0; i != NumElems; ++i) {
3333     int Elt = SVOp->getMaskElt(i);
3334     if (Elt < 0)
3335       continue;
3336     Elt %= HalfSize;
3337     unsigned Shamt = i;
3338     // For VSHUFPSY, the mask of the first half must be equal to the second one.
3339     if (NumElems == 8) Shamt %= HalfSize;
3340     Mask |= Elt << (Shamt*Mul);
3341   }
3342
3343   return Mask;
3344 }
3345
3346 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3347 /// the two vector operands have swapped position.
3348 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3349                                      unsigned NumElems) {
3350   for (unsigned i = 0; i != NumElems; ++i) {
3351     int idx = Mask[i];
3352     if (idx < 0)
3353       continue;
3354     else if (idx < (int)NumElems)
3355       Mask[i] = idx + NumElems;
3356     else
3357       Mask[i] = idx - NumElems;
3358   }
3359 }
3360
3361 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3362 /// specifies a shuffle of elements that is suitable for input to 128-bit
3363 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3364 /// reverse of what x86 shuffles want.
3365 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3366                         bool Commuted = false) {
3367   unsigned NumElems = VT.getVectorNumElements();
3368
3369   if (VT.getSizeInBits() != 128)
3370     return false;
3371
3372   if (NumElems != 2 && NumElems != 4)
3373     return false;
3374
3375   unsigned Half = NumElems / 2;
3376   unsigned SrcStart = Commuted ? NumElems : 0;
3377   for (unsigned i = 0; i != Half; ++i)
3378     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3379       return false;
3380   SrcStart = Commuted ? 0 : NumElems;
3381   for (unsigned i = Half; i != NumElems; ++i)
3382     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3383       return false;
3384
3385   return true;
3386 }
3387
3388 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3389   SmallVector<int, 8> M;
3390   N->getMask(M);
3391   return ::isSHUFPMask(M, N->getValueType(0));
3392 }
3393
3394 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3395 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3396 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3397   EVT VT = N->getValueType(0);
3398   unsigned NumElems = VT.getVectorNumElements();
3399
3400   if (VT.getSizeInBits() != 128)
3401     return false;
3402
3403   if (NumElems != 4)
3404     return false;
3405
3406   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3407   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3408          isUndefOrEqual(N->getMaskElt(1), 7) &&
3409          isUndefOrEqual(N->getMaskElt(2), 2) &&
3410          isUndefOrEqual(N->getMaskElt(3), 3);
3411 }
3412
3413 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3414 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3415 /// <2, 3, 2, 3>
3416 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3417   EVT VT = N->getValueType(0);
3418   unsigned NumElems = VT.getVectorNumElements();
3419
3420   if (VT.getSizeInBits() != 128)
3421     return false;
3422
3423   if (NumElems != 4)
3424     return false;
3425
3426   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3427          isUndefOrEqual(N->getMaskElt(1), 3) &&
3428          isUndefOrEqual(N->getMaskElt(2), 2) &&
3429          isUndefOrEqual(N->getMaskElt(3), 3);
3430 }
3431
3432 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3433 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3434 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3435   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3436
3437   if (NumElems != 2 && NumElems != 4)
3438     return false;
3439
3440   for (unsigned i = 0; i < NumElems/2; ++i)
3441     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3442       return false;
3443
3444   for (unsigned i = NumElems/2; i < NumElems; ++i)
3445     if (!isUndefOrEqual(N->getMaskElt(i), i))
3446       return false;
3447
3448   return true;
3449 }
3450
3451 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3452 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3453 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3454   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3455
3456   if ((NumElems != 2 && NumElems != 4)
3457       || N->getValueType(0).getSizeInBits() > 128)
3458     return false;
3459
3460   for (unsigned i = 0; i < NumElems/2; ++i)
3461     if (!isUndefOrEqual(N->getMaskElt(i), i))
3462       return false;
3463
3464   for (unsigned i = 0; i < NumElems/2; ++i)
3465     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3466       return false;
3467
3468   return true;
3469 }
3470
3471 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3472 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3473 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3474                          bool HasAVX2, bool V2IsSplat = false) {
3475   unsigned NumElts = VT.getVectorNumElements();
3476
3477   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3478          "Unsupported vector type for unpckh");
3479
3480   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3481       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3482     return false;
3483
3484   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3485   // independently on 128-bit lanes.
3486   unsigned NumLanes = VT.getSizeInBits()/128;
3487   unsigned NumLaneElts = NumElts/NumLanes;
3488
3489   for (unsigned l = 0; l != NumLanes; ++l) {
3490     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3491          i != (l+1)*NumLaneElts;
3492          i += 2, ++j) {
3493       int BitI  = Mask[i];
3494       int BitI1 = Mask[i+1];
3495       if (!isUndefOrEqual(BitI, j))
3496         return false;
3497       if (V2IsSplat) {
3498         if (!isUndefOrEqual(BitI1, NumElts))
3499           return false;
3500       } else {
3501         if (!isUndefOrEqual(BitI1, j + NumElts))
3502           return false;
3503       }
3504     }
3505   }
3506
3507   return true;
3508 }
3509
3510 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3511   SmallVector<int, 8> M;
3512   N->getMask(M);
3513   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3514 }
3515
3516 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3517 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3518 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3519                          bool HasAVX2, bool V2IsSplat = false) {
3520   unsigned NumElts = VT.getVectorNumElements();
3521
3522   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3523          "Unsupported vector type for unpckh");
3524
3525   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3526       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3527     return false;
3528
3529   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3530   // independently on 128-bit lanes.
3531   unsigned NumLanes = VT.getSizeInBits()/128;
3532   unsigned NumLaneElts = NumElts/NumLanes;
3533
3534   for (unsigned l = 0; l != NumLanes; ++l) {
3535     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3536          i != (l+1)*NumLaneElts; i += 2, ++j) {
3537       int BitI  = Mask[i];
3538       int BitI1 = Mask[i+1];
3539       if (!isUndefOrEqual(BitI, j))
3540         return false;
3541       if (V2IsSplat) {
3542         if (isUndefOrEqual(BitI1, NumElts))
3543           return false;
3544       } else {
3545         if (!isUndefOrEqual(BitI1, j+NumElts))
3546           return false;
3547       }
3548     }
3549   }
3550   return true;
3551 }
3552
3553 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3554   SmallVector<int, 8> M;
3555   N->getMask(M);
3556   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3557 }
3558
3559 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3560 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3561 /// <0, 0, 1, 1>
3562 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3563                                   bool HasAVX2) {
3564   unsigned NumElts = VT.getVectorNumElements();
3565
3566   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3567          "Unsupported vector type for unpckh");
3568
3569   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3570       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3571     return false;
3572
3573   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3574   // FIXME: Need a better way to get rid of this, there's no latency difference
3575   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3576   // the former later. We should also remove the "_undef" special mask.
3577   if (NumElts == 4 && VT.getSizeInBits() == 256)
3578     return false;
3579
3580   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3581   // independently on 128-bit lanes.
3582   unsigned NumLanes = VT.getSizeInBits()/128;
3583   unsigned NumLaneElts = NumElts/NumLanes;
3584
3585   for (unsigned l = 0; l != NumLanes; ++l) {
3586     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3587          i != (l+1)*NumLaneElts;
3588          i += 2, ++j) {
3589       int BitI  = Mask[i];
3590       int BitI1 = Mask[i+1];
3591
3592       if (!isUndefOrEqual(BitI, j))
3593         return false;
3594       if (!isUndefOrEqual(BitI1, j))
3595         return false;
3596     }
3597   }
3598
3599   return true;
3600 }
3601
3602 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3603   SmallVector<int, 8> M;
3604   N->getMask(M);
3605   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3606 }
3607
3608 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3609 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3610 /// <2, 2, 3, 3>
3611 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3612                                   bool HasAVX2) {
3613   unsigned NumElts = VT.getVectorNumElements();
3614
3615   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3616          "Unsupported vector type for unpckh");
3617
3618   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3619       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3620     return false;
3621
3622   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3623   // independently on 128-bit lanes.
3624   unsigned NumLanes = VT.getSizeInBits()/128;
3625   unsigned NumLaneElts = NumElts/NumLanes;
3626
3627   for (unsigned l = 0; l != NumLanes; ++l) {
3628     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3629          i != (l+1)*NumLaneElts; i += 2, ++j) {
3630       int BitI  = Mask[i];
3631       int BitI1 = Mask[i+1];
3632       if (!isUndefOrEqual(BitI, j))
3633         return false;
3634       if (!isUndefOrEqual(BitI1, j))
3635         return false;
3636     }
3637   }
3638   return true;
3639 }
3640
3641 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3642   SmallVector<int, 8> M;
3643   N->getMask(M);
3644   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3645 }
3646
3647 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3648 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3649 /// MOVSD, and MOVD, i.e. setting the lowest element.
3650 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3651   if (VT.getVectorElementType().getSizeInBits() < 32)
3652     return false;
3653
3654   int NumElts = VT.getVectorNumElements();
3655
3656   if (!isUndefOrEqual(Mask[0], NumElts))
3657     return false;
3658
3659   for (int i = 1; i < NumElts; ++i)
3660     if (!isUndefOrEqual(Mask[i], i))
3661       return false;
3662
3663   return true;
3664 }
3665
3666 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3667   SmallVector<int, 8> M;
3668   N->getMask(M);
3669   return ::isMOVLMask(M, N->getValueType(0));
3670 }
3671
3672 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3673 /// as permutations between 128-bit chunks or halves. As an example: this
3674 /// shuffle bellow:
3675 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3676 /// The first half comes from the second half of V1 and the second half from the
3677 /// the second half of V2.
3678 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3679                              bool HasAVX) {
3680   if (!HasAVX || VT.getSizeInBits() != 256)
3681     return false;
3682
3683   // The shuffle result is divided into half A and half B. In total the two
3684   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3685   // B must come from C, D, E or F.
3686   int HalfSize = VT.getVectorNumElements()/2;
3687   bool MatchA = false, MatchB = false;
3688
3689   // Check if A comes from one of C, D, E, F.
3690   for (int Half = 0; Half < 4; ++Half) {
3691     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3692       MatchA = true;
3693       break;
3694     }
3695   }
3696
3697   // Check if B comes from one of C, D, E, F.
3698   for (int Half = 0; Half < 4; ++Half) {
3699     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3700       MatchB = true;
3701       break;
3702     }
3703   }
3704
3705   return MatchA && MatchB;
3706 }
3707
3708 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3709 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3710 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3711   EVT VT = SVOp->getValueType(0);
3712
3713   int HalfSize = VT.getVectorNumElements()/2;
3714
3715   int FstHalf = 0, SndHalf = 0;
3716   for (int i = 0; i < HalfSize; ++i) {
3717     if (SVOp->getMaskElt(i) > 0) {
3718       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3719       break;
3720     }
3721   }
3722   for (int i = HalfSize; i < HalfSize*2; ++i) {
3723     if (SVOp->getMaskElt(i) > 0) {
3724       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3725       break;
3726     }
3727   }
3728
3729   return (FstHalf | (SndHalf << 4));
3730 }
3731
3732 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3733 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3734 /// Note that VPERMIL mask matching is different depending whether theunderlying
3735 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3736 /// to the same elements of the low, but to the higher half of the source.
3737 /// In VPERMILPD the two lanes could be shuffled independently of each other
3738 /// with the same restriction that lanes can't be crossed.
3739 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3740                            bool HasAVX) {
3741   int NumElts = VT.getVectorNumElements();
3742   int NumLanes = VT.getSizeInBits()/128;
3743
3744   if (!HasAVX)
3745     return false;
3746
3747   // Only match 256-bit with 32/64-bit types
3748   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3749     return false;
3750
3751   int LaneSize = NumElts/NumLanes;
3752   for (int l = 0; l != NumLanes; ++l) {
3753     int LaneStart = l*LaneSize;
3754     for (int i = 0; i != LaneSize; ++i) {
3755       if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3756         return false;
3757       if (NumElts == 4 || l == 0)
3758         continue;
3759       // VPERMILPS handling
3760       if (Mask[i] < 0)
3761         continue;
3762       if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3763         return false;
3764     }
3765   }
3766
3767   return true;
3768 }
3769
3770 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3771 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3772 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3773   EVT VT = SVOp->getValueType(0);
3774
3775   int NumElts = VT.getVectorNumElements();
3776   int NumLanes = VT.getSizeInBits()/128;
3777   int LaneSize = NumElts/NumLanes;
3778
3779   // Although the mask is equal for both lanes do it twice to get the cases
3780   // where a mask will match because the same mask element is undef on the
3781   // first half but valid on the second. This would get pathological cases
3782   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3783   unsigned Shift = (LaneSize == 4) ? 2 : 1;
3784   unsigned Mask = 0;
3785   for (int i = 0; i != NumElts; ++i) {
3786     int MaskElt = SVOp->getMaskElt(i);
3787     if (MaskElt < 0)
3788       continue;
3789     MaskElt %= LaneSize;
3790     unsigned Shamt = i;
3791     // VPERMILPSY, the mask of the first half must be equal to the second one
3792     if (NumElts == 8) Shamt %= LaneSize;
3793     Mask |= MaskElt << (Shamt*Shift);
3794   }
3795
3796   return Mask;
3797 }
3798
3799 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3800 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3801 /// element of vector 2 and the other elements to come from vector 1 in order.
3802 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3803                                bool V2IsSplat = false, bool V2IsUndef = false) {
3804   int NumOps = VT.getVectorNumElements();
3805   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3806     return false;
3807
3808   if (!isUndefOrEqual(Mask[0], 0))
3809     return false;
3810
3811   for (int i = 1; i < NumOps; ++i)
3812     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3813           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3814           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3815       return false;
3816
3817   return true;
3818 }
3819
3820 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3821                            bool V2IsUndef = false) {
3822   SmallVector<int, 8> M;
3823   N->getMask(M);
3824   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3825 }
3826
3827 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3828 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3829 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3830 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3831                          const X86Subtarget *Subtarget) {
3832   if (!Subtarget->hasSSE3orAVX())
3833     return false;
3834
3835   // The second vector must be undef
3836   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3837     return false;
3838
3839   EVT VT = N->getValueType(0);
3840   unsigned NumElems = VT.getVectorNumElements();
3841
3842   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3843       (VT.getSizeInBits() == 256 && NumElems != 8))
3844     return false;
3845
3846   // "i+1" is the value the indexed mask element must have
3847   for (unsigned i = 0; i < NumElems; i += 2)
3848     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3849         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3850       return false;
3851
3852   return true;
3853 }
3854
3855 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3856 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3857 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3858 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3859                          const X86Subtarget *Subtarget) {
3860   if (!Subtarget->hasSSE3orAVX())
3861     return false;
3862
3863   // The second vector must be undef
3864   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3865     return false;
3866
3867   EVT VT = N->getValueType(0);
3868   unsigned NumElems = VT.getVectorNumElements();
3869
3870   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3871       (VT.getSizeInBits() == 256 && NumElems != 8))
3872     return false;
3873
3874   // "i" is the value the indexed mask element must have
3875   for (unsigned i = 0; i < NumElems; i += 2)
3876     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3877         !isUndefOrEqual(N->getMaskElt(i+1), i))
3878       return false;
3879
3880   return true;
3881 }
3882
3883 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3884 /// specifies a shuffle of elements that is suitable for input to 256-bit
3885 /// version of MOVDDUP.
3886 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3887                            bool HasAVX) {
3888   int NumElts = VT.getVectorNumElements();
3889
3890   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3891     return false;
3892
3893   for (int i = 0; i != NumElts/2; ++i)
3894     if (!isUndefOrEqual(Mask[i], 0))
3895       return false;
3896   for (int i = NumElts/2; i != NumElts; ++i)
3897     if (!isUndefOrEqual(Mask[i], NumElts/2))
3898       return false;
3899   return true;
3900 }
3901
3902 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3903 /// specifies a shuffle of elements that is suitable for input to 128-bit
3904 /// version of MOVDDUP.
3905 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3906   EVT VT = N->getValueType(0);
3907
3908   if (VT.getSizeInBits() != 128)
3909     return false;
3910
3911   int e = VT.getVectorNumElements() / 2;
3912   for (int i = 0; i < e; ++i)
3913     if (!isUndefOrEqual(N->getMaskElt(i), i))
3914       return false;
3915   for (int i = 0; i < e; ++i)
3916     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3917       return false;
3918   return true;
3919 }
3920
3921 /// isVEXTRACTF128Index - Return true if the specified
3922 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3923 /// suitable for input to VEXTRACTF128.
3924 bool X86::isVEXTRACTF128Index(SDNode *N) {
3925   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3926     return false;
3927
3928   // The index should be aligned on a 128-bit boundary.
3929   uint64_t Index =
3930     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3931
3932   unsigned VL = N->getValueType(0).getVectorNumElements();
3933   unsigned VBits = N->getValueType(0).getSizeInBits();
3934   unsigned ElSize = VBits / VL;
3935   bool Result = (Index * ElSize) % 128 == 0;
3936
3937   return Result;
3938 }
3939
3940 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3941 /// operand specifies a subvector insert that is suitable for input to
3942 /// VINSERTF128.
3943 bool X86::isVINSERTF128Index(SDNode *N) {
3944   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3945     return false;
3946
3947   // The index should be aligned on a 128-bit boundary.
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   unsigned VL = N->getValueType(0).getVectorNumElements();
3952   unsigned VBits = N->getValueType(0).getSizeInBits();
3953   unsigned ElSize = VBits / VL;
3954   bool Result = (Index * ElSize) % 128 == 0;
3955
3956   return Result;
3957 }
3958
3959 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3960 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3961 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3963   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3964
3965   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3966   unsigned Mask = 0;
3967   for (int i = 0; i < NumOperands; ++i) {
3968     int Val = SVOp->getMaskElt(NumOperands-i-1);
3969     if (Val < 0) Val = 0;
3970     if (Val >= NumOperands) Val -= NumOperands;
3971     Mask |= Val;
3972     if (i != NumOperands - 1)
3973       Mask <<= Shift;
3974   }
3975   return Mask;
3976 }
3977
3978 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3979 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3980 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3981   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3982   unsigned Mask = 0;
3983   // 8 nodes, but we only care about the last 4.
3984   for (unsigned i = 7; i >= 4; --i) {
3985     int Val = SVOp->getMaskElt(i);
3986     if (Val >= 0)
3987       Mask |= (Val - 4);
3988     if (i != 4)
3989       Mask <<= 2;
3990   }
3991   return Mask;
3992 }
3993
3994 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3995 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3996 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3998   unsigned Mask = 0;
3999   // 8 nodes, but we only care about the first 4.
4000   for (int i = 3; i >= 0; --i) {
4001     int Val = SVOp->getMaskElt(i);
4002     if (Val >= 0)
4003       Mask |= Val;
4004     if (i != 0)
4005       Mask <<= 2;
4006   }
4007   return Mask;
4008 }
4009
4010 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4011 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4012 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4013   EVT VT = SVOp->getValueType(0);
4014   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4015   int Val = 0;
4016
4017   unsigned i, e;
4018   for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4019     Val = SVOp->getMaskElt(i);
4020     if (Val >= 0)
4021       break;
4022   }
4023   assert(Val - i > 0 && "PALIGNR imm should be positive");
4024   return (Val - i) * EltSize;
4025 }
4026
4027 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4028 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4029 /// instructions.
4030 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4031   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4032     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4033
4034   uint64_t Index =
4035     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4036
4037   EVT VecVT = N->getOperand(0).getValueType();
4038   EVT ElVT = VecVT.getVectorElementType();
4039
4040   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4041   return Index / NumElemsPerChunk;
4042 }
4043
4044 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4045 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4046 /// instructions.
4047 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4048   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4049     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4050
4051   uint64_t Index =
4052     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4053
4054   EVT VecVT = N->getValueType(0);
4055   EVT ElVT = VecVT.getVectorElementType();
4056
4057   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4058   return Index / NumElemsPerChunk;
4059 }
4060
4061 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4062 /// constant +0.0.
4063 bool X86::isZeroNode(SDValue Elt) {
4064   return ((isa<ConstantSDNode>(Elt) &&
4065            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4066           (isa<ConstantFPSDNode>(Elt) &&
4067            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4068 }
4069
4070 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4071 /// their permute mask.
4072 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4073                                     SelectionDAG &DAG) {
4074   EVT VT = SVOp->getValueType(0);
4075   unsigned NumElems = VT.getVectorNumElements();
4076   SmallVector<int, 8> MaskVec;
4077
4078   for (unsigned i = 0; i != NumElems; ++i) {
4079     int idx = SVOp->getMaskElt(i);
4080     if (idx < 0)
4081       MaskVec.push_back(idx);
4082     else if (idx < (int)NumElems)
4083       MaskVec.push_back(idx + NumElems);
4084     else
4085       MaskVec.push_back(idx - NumElems);
4086   }
4087   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4088                               SVOp->getOperand(0), &MaskVec[0]);
4089 }
4090
4091 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4092 /// match movhlps. The lower half elements should come from upper half of
4093 /// V1 (and in order), and the upper half elements should come from the upper
4094 /// half of V2 (and in order).
4095 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4096   EVT VT = Op->getValueType(0);
4097   if (VT.getSizeInBits() != 128)
4098     return false;
4099   if (VT.getVectorNumElements() != 4)
4100     return false;
4101   for (unsigned i = 0, e = 2; i != e; ++i)
4102     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4103       return false;
4104   for (unsigned i = 2; i != 4; ++i)
4105     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4106       return false;
4107   return true;
4108 }
4109
4110 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4111 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4112 /// required.
4113 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4114   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4115     return false;
4116   N = N->getOperand(0).getNode();
4117   if (!ISD::isNON_EXTLoad(N))
4118     return false;
4119   if (LD)
4120     *LD = cast<LoadSDNode>(N);
4121   return true;
4122 }
4123
4124 // Test whether the given value is a vector value which will be legalized
4125 // into a load.
4126 static bool WillBeConstantPoolLoad(SDNode *N) {
4127   if (N->getOpcode() != ISD::BUILD_VECTOR)
4128     return false;
4129
4130   // Check for any non-constant elements.
4131   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4132     switch (N->getOperand(i).getNode()->getOpcode()) {
4133     case ISD::UNDEF:
4134     case ISD::ConstantFP:
4135     case ISD::Constant:
4136       break;
4137     default:
4138       return false;
4139     }
4140
4141   // Vectors of all-zeros and all-ones are materialized with special
4142   // instructions rather than being loaded.
4143   return !ISD::isBuildVectorAllZeros(N) &&
4144          !ISD::isBuildVectorAllOnes(N);
4145 }
4146
4147 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4148 /// match movlp{s|d}. The lower half elements should come from lower half of
4149 /// V1 (and in order), and the upper half elements should come from the upper
4150 /// half of V2 (and in order). And since V1 will become the source of the
4151 /// MOVLP, it must be either a vector load or a scalar load to vector.
4152 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4153                                ShuffleVectorSDNode *Op) {
4154   EVT VT = Op->getValueType(0);
4155   if (VT.getSizeInBits() != 128)
4156     return false;
4157
4158   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4159     return false;
4160   // Is V2 is a vector load, don't do this transformation. We will try to use
4161   // load folding shufps op.
4162   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4163     return false;
4164
4165   unsigned NumElems = VT.getVectorNumElements();
4166
4167   if (NumElems != 2 && NumElems != 4)
4168     return false;
4169   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4170     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4171       return false;
4172   for (unsigned i = NumElems/2; i != NumElems; ++i)
4173     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4174       return false;
4175   return true;
4176 }
4177
4178 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4179 /// all the same.
4180 static bool isSplatVector(SDNode *N) {
4181   if (N->getOpcode() != ISD::BUILD_VECTOR)
4182     return false;
4183
4184   SDValue SplatValue = N->getOperand(0);
4185   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4186     if (N->getOperand(i) != SplatValue)
4187       return false;
4188   return true;
4189 }
4190
4191 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4192 /// to an zero vector.
4193 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4194 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4195   SDValue V1 = N->getOperand(0);
4196   SDValue V2 = N->getOperand(1);
4197   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4198   for (unsigned i = 0; i != NumElems; ++i) {
4199     int Idx = N->getMaskElt(i);
4200     if (Idx >= (int)NumElems) {
4201       unsigned Opc = V2.getOpcode();
4202       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4203         continue;
4204       if (Opc != ISD::BUILD_VECTOR ||
4205           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4206         return false;
4207     } else if (Idx >= 0) {
4208       unsigned Opc = V1.getOpcode();
4209       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4210         continue;
4211       if (Opc != ISD::BUILD_VECTOR ||
4212           !X86::isZeroNode(V1.getOperand(Idx)))
4213         return false;
4214     }
4215   }
4216   return true;
4217 }
4218
4219 /// getZeroVector - Returns a vector of specified type with all zero elements.
4220 ///
4221 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4222                              DebugLoc dl) {
4223   assert(VT.isVector() && "Expected a vector type");
4224
4225   // Always build SSE zero vectors as <4 x i32> bitcasted
4226   // to their dest type. This ensures they get CSE'd.
4227   SDValue Vec;
4228   if (VT.getSizeInBits() == 128) {  // SSE
4229     if (HasXMMInt) {  // SSE2
4230       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4232     } else { // SSE1
4233       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4234       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4235     }
4236   } else if (VT.getSizeInBits() == 256) { // AVX
4237     // 256-bit logic and arithmetic instructions in AVX are
4238     // all floating-point, no support for integer ops. Default
4239     // to emitting fp zeroed vectors then.
4240     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4241     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4242     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4243   }
4244   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4245 }
4246
4247 /// getOnesVector - Returns a vector of specified type with all bits set.
4248 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4249 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4250 /// Then bitcast to their original type, ensuring they get CSE'd.
4251 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4252                              DebugLoc dl) {
4253   assert(VT.isVector() && "Expected a vector type");
4254   assert((VT.is128BitVector() || VT.is256BitVector())
4255          && "Expected a 128-bit or 256-bit vector type");
4256
4257   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4258   SDValue Vec;
4259   if (VT.getSizeInBits() == 256) {
4260     if (HasAVX2) { // AVX2
4261       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4262       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4263     } else { // AVX
4264       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4265       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4266                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4267       Vec = Insert128BitVector(InsV, Vec,
4268                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4269     }
4270   } else {
4271     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4272   }
4273
4274   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4275 }
4276
4277 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4278 /// that point to V2 points to its first element.
4279 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4280   EVT VT = SVOp->getValueType(0);
4281   unsigned NumElems = VT.getVectorNumElements();
4282
4283   bool Changed = false;
4284   SmallVector<int, 8> MaskVec;
4285   SVOp->getMask(MaskVec);
4286
4287   for (unsigned i = 0; i != NumElems; ++i) {
4288     if (MaskVec[i] > (int)NumElems) {
4289       MaskVec[i] = NumElems;
4290       Changed = true;
4291     }
4292   }
4293   if (Changed)
4294     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4295                                 SVOp->getOperand(1), &MaskVec[0]);
4296   return SDValue(SVOp, 0);
4297 }
4298
4299 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4300 /// operation of specified width.
4301 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4302                        SDValue V2) {
4303   unsigned NumElems = VT.getVectorNumElements();
4304   SmallVector<int, 8> Mask;
4305   Mask.push_back(NumElems);
4306   for (unsigned i = 1; i != NumElems; ++i)
4307     Mask.push_back(i);
4308   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4309 }
4310
4311 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4312 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4313                           SDValue V2) {
4314   unsigned NumElems = VT.getVectorNumElements();
4315   SmallVector<int, 8> Mask;
4316   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4317     Mask.push_back(i);
4318     Mask.push_back(i + NumElems);
4319   }
4320   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4321 }
4322
4323 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4324 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4325                           SDValue V2) {
4326   unsigned NumElems = VT.getVectorNumElements();
4327   unsigned Half = NumElems/2;
4328   SmallVector<int, 8> Mask;
4329   for (unsigned i = 0; i != Half; ++i) {
4330     Mask.push_back(i + Half);
4331     Mask.push_back(i + NumElems + Half);
4332   }
4333   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4334 }
4335
4336 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4337 // a generic shuffle instruction because the target has no such instructions.
4338 // Generate shuffles which repeat i16 and i8 several times until they can be
4339 // represented by v4f32 and then be manipulated by target suported shuffles.
4340 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4341   EVT VT = V.getValueType();
4342   int NumElems = VT.getVectorNumElements();
4343   DebugLoc dl = V.getDebugLoc();
4344
4345   while (NumElems > 4) {
4346     if (EltNo < NumElems/2) {
4347       V = getUnpackl(DAG, dl, VT, V, V);
4348     } else {
4349       V = getUnpackh(DAG, dl, VT, V, V);
4350       EltNo -= NumElems/2;
4351     }
4352     NumElems >>= 1;
4353   }
4354   return V;
4355 }
4356
4357 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4358 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4359   EVT VT = V.getValueType();
4360   DebugLoc dl = V.getDebugLoc();
4361   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4362          && "Vector size not supported");
4363
4364   if (VT.getSizeInBits() == 128) {
4365     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4366     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4367     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4368                              &SplatMask[0]);
4369   } else {
4370     // To use VPERMILPS to splat scalars, the second half of indicies must
4371     // refer to the higher part, which is a duplication of the lower one,
4372     // because VPERMILPS can only handle in-lane permutations.
4373     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4374                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4375
4376     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4377     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4378                              &SplatMask[0]);
4379   }
4380
4381   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4382 }
4383
4384 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4385 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4386   EVT SrcVT = SV->getValueType(0);
4387   SDValue V1 = SV->getOperand(0);
4388   DebugLoc dl = SV->getDebugLoc();
4389
4390   int EltNo = SV->getSplatIndex();
4391   int NumElems = SrcVT.getVectorNumElements();
4392   unsigned Size = SrcVT.getSizeInBits();
4393
4394   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4395           "Unknown how to promote splat for type");
4396
4397   // Extract the 128-bit part containing the splat element and update
4398   // the splat element index when it refers to the higher register.
4399   if (Size == 256) {
4400     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4401     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4402     if (Idx > 0)
4403       EltNo -= NumElems/2;
4404   }
4405
4406   // All i16 and i8 vector types can't be used directly by a generic shuffle
4407   // instruction because the target has no such instruction. Generate shuffles
4408   // which repeat i16 and i8 several times until they fit in i32, and then can
4409   // be manipulated by target suported shuffles.
4410   EVT EltVT = SrcVT.getVectorElementType();
4411   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4412     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4413
4414   // Recreate the 256-bit vector and place the same 128-bit vector
4415   // into the low and high part. This is necessary because we want
4416   // to use VPERM* to shuffle the vectors
4417   if (Size == 256) {
4418     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4419                          DAG.getConstant(0, MVT::i32), DAG, dl);
4420     V1 = Insert128BitVector(InsV, V1,
4421                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4422   }
4423
4424   return getLegalSplat(DAG, V1, EltNo);
4425 }
4426
4427 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4428 /// vector of zero or undef vector.  This produces a shuffle where the low
4429 /// element of V2 is swizzled into the zero/undef vector, landing at element
4430 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4431 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4432                                            bool isZero, bool HasXMMInt,
4433                                            SelectionDAG &DAG) {
4434   EVT VT = V2.getValueType();
4435   SDValue V1 = isZero
4436     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4437   unsigned NumElems = VT.getVectorNumElements();
4438   SmallVector<int, 16> MaskVec;
4439   for (unsigned i = 0; i != NumElems; ++i)
4440     // If this is the insertion idx, put the low elt of V2 here.
4441     MaskVec.push_back(i == Idx ? NumElems : i);
4442   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4443 }
4444
4445 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4446 /// element of the result of the vector shuffle.
4447 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4448                                    unsigned Depth) {
4449   if (Depth == 6)
4450     return SDValue();  // Limit search depth.
4451
4452   SDValue V = SDValue(N, 0);
4453   EVT VT = V.getValueType();
4454   unsigned Opcode = V.getOpcode();
4455
4456   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4457   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4458     Index = SV->getMaskElt(Index);
4459
4460     if (Index < 0)
4461       return DAG.getUNDEF(VT.getVectorElementType());
4462
4463     int NumElems = VT.getVectorNumElements();
4464     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4465     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4466   }
4467
4468   // Recurse into target specific vector shuffles to find scalars.
4469   if (isTargetShuffle(Opcode)) {
4470     int NumElems = VT.getVectorNumElements();
4471     SmallVector<unsigned, 16> ShuffleMask;
4472     SDValue ImmN;
4473
4474     switch(Opcode) {
4475     case X86ISD::SHUFPS:
4476     case X86ISD::SHUFPD:
4477       ImmN = N->getOperand(N->getNumOperands()-1);
4478       DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4479                       ShuffleMask);
4480       break;
4481     case X86ISD::UNPCKH:
4482       DecodeUNPCKHMask(VT, ShuffleMask);
4483       break;
4484     case X86ISD::UNPCKL:
4485       DecodeUNPCKLMask(VT, ShuffleMask);
4486       break;
4487     case X86ISD::MOVHLPS:
4488       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4489       break;
4490     case X86ISD::MOVLHPS:
4491       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4492       break;
4493     case X86ISD::PSHUFD:
4494       ImmN = N->getOperand(N->getNumOperands()-1);
4495       DecodePSHUFMask(NumElems,
4496                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4497                       ShuffleMask);
4498       break;
4499     case X86ISD::PSHUFHW:
4500       ImmN = N->getOperand(N->getNumOperands()-1);
4501       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4502                         ShuffleMask);
4503       break;
4504     case X86ISD::PSHUFLW:
4505       ImmN = N->getOperand(N->getNumOperands()-1);
4506       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4507                         ShuffleMask);
4508       break;
4509     case X86ISD::MOVSS:
4510     case X86ISD::MOVSD: {
4511       // The index 0 always comes from the first element of the second source,
4512       // this is why MOVSS and MOVSD are used in the first place. The other
4513       // elements come from the other positions of the first source vector.
4514       unsigned OpNum = (Index == 0) ? 1 : 0;
4515       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4516                                  Depth+1);
4517     }
4518     case X86ISD::VPERMILP:
4519       ImmN = N->getOperand(N->getNumOperands()-1);
4520       DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4521                         ShuffleMask);
4522       break;
4523     case X86ISD::VPERM2X128:
4524       ImmN = N->getOperand(N->getNumOperands()-1);
4525       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4526                            ShuffleMask);
4527       break;
4528     case X86ISD::MOVDDUP:
4529     case X86ISD::MOVLHPD:
4530     case X86ISD::MOVLPD:
4531     case X86ISD::MOVLPS:
4532     case X86ISD::MOVSHDUP:
4533     case X86ISD::MOVSLDUP:
4534     case X86ISD::PALIGN:
4535       return SDValue(); // Not yet implemented.
4536     default:
4537       assert(0 && "unknown target shuffle node");
4538       return SDValue();
4539     }
4540
4541     Index = ShuffleMask[Index];
4542     if (Index < 0)
4543       return DAG.getUNDEF(VT.getVectorElementType());
4544
4545     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4546     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4547                                Depth+1);
4548   }
4549
4550   // Actual nodes that may contain scalar elements
4551   if (Opcode == ISD::BITCAST) {
4552     V = V.getOperand(0);
4553     EVT SrcVT = V.getValueType();
4554     unsigned NumElems = VT.getVectorNumElements();
4555
4556     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4557       return SDValue();
4558   }
4559
4560   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4561     return (Index == 0) ? V.getOperand(0)
4562                           : DAG.getUNDEF(VT.getVectorElementType());
4563
4564   if (V.getOpcode() == ISD::BUILD_VECTOR)
4565     return V.getOperand(Index);
4566
4567   return SDValue();
4568 }
4569
4570 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4571 /// shuffle operation which come from a consecutively from a zero. The
4572 /// search can start in two different directions, from left or right.
4573 static
4574 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4575                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4576   int i = 0;
4577
4578   while (i < NumElems) {
4579     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4580     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4581     if (!(Elt.getNode() &&
4582          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4583       break;
4584     ++i;
4585   }
4586
4587   return i;
4588 }
4589
4590 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4591 /// MaskE correspond consecutively to elements from one of the vector operands,
4592 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4593 static
4594 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4595                               int OpIdx, int NumElems, unsigned &OpNum) {
4596   bool SeenV1 = false;
4597   bool SeenV2 = false;
4598
4599   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4600     int Idx = SVOp->getMaskElt(i);
4601     // Ignore undef indicies
4602     if (Idx < 0)
4603       continue;
4604
4605     if (Idx < NumElems)
4606       SeenV1 = true;
4607     else
4608       SeenV2 = true;
4609
4610     // Only accept consecutive elements from the same vector
4611     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4612       return false;
4613   }
4614
4615   OpNum = SeenV1 ? 0 : 1;
4616   return true;
4617 }
4618
4619 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4620 /// logical left shift of a vector.
4621 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4622                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4623   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4624   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4625               false /* check zeros from right */, DAG);
4626   unsigned OpSrc;
4627
4628   if (!NumZeros)
4629     return false;
4630
4631   // Considering the elements in the mask that are not consecutive zeros,
4632   // check if they consecutively come from only one of the source vectors.
4633   //
4634   //               V1 = {X, A, B, C}     0
4635   //                         \  \  \    /
4636   //   vector_shuffle V1, V2 <1, 2, 3, X>
4637   //
4638   if (!isShuffleMaskConsecutive(SVOp,
4639             0,                   // Mask Start Index
4640             NumElems-NumZeros-1, // Mask End Index
4641             NumZeros,            // Where to start looking in the src vector
4642             NumElems,            // Number of elements in vector
4643             OpSrc))              // Which source operand ?
4644     return false;
4645
4646   isLeft = false;
4647   ShAmt = NumZeros;
4648   ShVal = SVOp->getOperand(OpSrc);
4649   return true;
4650 }
4651
4652 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4653 /// logical left shift of a vector.
4654 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4655                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4656   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4657   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4658               true /* check zeros from left */, DAG);
4659   unsigned OpSrc;
4660
4661   if (!NumZeros)
4662     return false;
4663
4664   // Considering the elements in the mask that are not consecutive zeros,
4665   // check if they consecutively come from only one of the source vectors.
4666   //
4667   //                           0    { A, B, X, X } = V2
4668   //                          / \    /  /
4669   //   vector_shuffle V1, V2 <X, X, 4, 5>
4670   //
4671   if (!isShuffleMaskConsecutive(SVOp,
4672             NumZeros,     // Mask Start Index
4673             NumElems-1,   // Mask End Index
4674             0,            // Where to start looking in the src vector
4675             NumElems,     // Number of elements in vector
4676             OpSrc))       // Which source operand ?
4677     return false;
4678
4679   isLeft = true;
4680   ShAmt = NumZeros;
4681   ShVal = SVOp->getOperand(OpSrc);
4682   return true;
4683 }
4684
4685 /// isVectorShift - Returns true if the shuffle can be implemented as a
4686 /// logical left or right shift of a vector.
4687 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4688                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4689   // Although the logic below support any bitwidth size, there are no
4690   // shift instructions which handle more than 128-bit vectors.
4691   if (SVOp->getValueType(0).getSizeInBits() > 128)
4692     return false;
4693
4694   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4695       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4696     return true;
4697
4698   return false;
4699 }
4700
4701 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4702 ///
4703 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4704                                        unsigned NumNonZero, unsigned NumZero,
4705                                        SelectionDAG &DAG,
4706                                        const TargetLowering &TLI) {
4707   if (NumNonZero > 8)
4708     return SDValue();
4709
4710   DebugLoc dl = Op.getDebugLoc();
4711   SDValue V(0, 0);
4712   bool First = true;
4713   for (unsigned i = 0; i < 16; ++i) {
4714     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4715     if (ThisIsNonZero && First) {
4716       if (NumZero)
4717         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4718       else
4719         V = DAG.getUNDEF(MVT::v8i16);
4720       First = false;
4721     }
4722
4723     if ((i & 1) != 0) {
4724       SDValue ThisElt(0, 0), LastElt(0, 0);
4725       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4726       if (LastIsNonZero) {
4727         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4728                               MVT::i16, Op.getOperand(i-1));
4729       }
4730       if (ThisIsNonZero) {
4731         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4732         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4733                               ThisElt, DAG.getConstant(8, MVT::i8));
4734         if (LastIsNonZero)
4735           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4736       } else
4737         ThisElt = LastElt;
4738
4739       if (ThisElt.getNode())
4740         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4741                         DAG.getIntPtrConstant(i/2));
4742     }
4743   }
4744
4745   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4746 }
4747
4748 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4749 ///
4750 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4751                                      unsigned NumNonZero, unsigned NumZero,
4752                                      SelectionDAG &DAG,
4753                                      const TargetLowering &TLI) {
4754   if (NumNonZero > 4)
4755     return SDValue();
4756
4757   DebugLoc dl = Op.getDebugLoc();
4758   SDValue V(0, 0);
4759   bool First = true;
4760   for (unsigned i = 0; i < 8; ++i) {
4761     bool isNonZero = (NonZeros & (1 << i)) != 0;
4762     if (isNonZero) {
4763       if (First) {
4764         if (NumZero)
4765           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4766         else
4767           V = DAG.getUNDEF(MVT::v8i16);
4768         First = false;
4769       }
4770       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4771                       MVT::v8i16, V, Op.getOperand(i),
4772                       DAG.getIntPtrConstant(i));
4773     }
4774   }
4775
4776   return V;
4777 }
4778
4779 /// getVShift - Return a vector logical shift node.
4780 ///
4781 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4782                          unsigned NumBits, SelectionDAG &DAG,
4783                          const TargetLowering &TLI, DebugLoc dl) {
4784   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4785   EVT ShVT = MVT::v2i64;
4786   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4787   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4788   return DAG.getNode(ISD::BITCAST, dl, VT,
4789                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4790                              DAG.getConstant(NumBits,
4791                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4792 }
4793
4794 SDValue
4795 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4796                                           SelectionDAG &DAG) const {
4797
4798   // Check if the scalar load can be widened into a vector load. And if
4799   // the address is "base + cst" see if the cst can be "absorbed" into
4800   // the shuffle mask.
4801   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4802     SDValue Ptr = LD->getBasePtr();
4803     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4804       return SDValue();
4805     EVT PVT = LD->getValueType(0);
4806     if (PVT != MVT::i32 && PVT != MVT::f32)
4807       return SDValue();
4808
4809     int FI = -1;
4810     int64_t Offset = 0;
4811     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4812       FI = FINode->getIndex();
4813       Offset = 0;
4814     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4815                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4816       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4817       Offset = Ptr.getConstantOperandVal(1);
4818       Ptr = Ptr.getOperand(0);
4819     } else {
4820       return SDValue();
4821     }
4822
4823     // FIXME: 256-bit vector instructions don't require a strict alignment,
4824     // improve this code to support it better.
4825     unsigned RequiredAlign = VT.getSizeInBits()/8;
4826     SDValue Chain = LD->getChain();
4827     // Make sure the stack object alignment is at least 16 or 32.
4828     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4829     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4830       if (MFI->isFixedObjectIndex(FI)) {
4831         // Can't change the alignment. FIXME: It's possible to compute
4832         // the exact stack offset and reference FI + adjust offset instead.
4833         // If someone *really* cares about this. That's the way to implement it.
4834         return SDValue();
4835       } else {
4836         MFI->setObjectAlignment(FI, RequiredAlign);
4837       }
4838     }
4839
4840     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4841     // Ptr + (Offset & ~15).
4842     if (Offset < 0)
4843       return SDValue();
4844     if ((Offset % RequiredAlign) & 3)
4845       return SDValue();
4846     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4847     if (StartOffset)
4848       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4849                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4850
4851     int EltNo = (Offset - StartOffset) >> 2;
4852     int NumElems = VT.getVectorNumElements();
4853
4854     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4855     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4856     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4857                              LD->getPointerInfo().getWithOffset(StartOffset),
4858                              false, false, false, 0);
4859
4860     // Canonicalize it to a v4i32 or v8i32 shuffle.
4861     SmallVector<int, 8> Mask;
4862     for (int i = 0; i < NumElems; ++i)
4863       Mask.push_back(EltNo);
4864
4865     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4866     return DAG.getNode(ISD::BITCAST, dl, NVT,
4867                        DAG.getVectorShuffle(CanonVT, dl, V1,
4868                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4869   }
4870
4871   return SDValue();
4872 }
4873
4874 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4875 /// vector of type 'VT', see if the elements can be replaced by a single large
4876 /// load which has the same value as a build_vector whose operands are 'elts'.
4877 ///
4878 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4879 ///
4880 /// FIXME: we'd also like to handle the case where the last elements are zero
4881 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4882 /// There's even a handy isZeroNode for that purpose.
4883 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4884                                         DebugLoc &DL, SelectionDAG &DAG) {
4885   EVT EltVT = VT.getVectorElementType();
4886   unsigned NumElems = Elts.size();
4887
4888   LoadSDNode *LDBase = NULL;
4889   unsigned LastLoadedElt = -1U;
4890
4891   // For each element in the initializer, see if we've found a load or an undef.
4892   // If we don't find an initial load element, or later load elements are
4893   // non-consecutive, bail out.
4894   for (unsigned i = 0; i < NumElems; ++i) {
4895     SDValue Elt = Elts[i];
4896
4897     if (!Elt.getNode() ||
4898         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4899       return SDValue();
4900     if (!LDBase) {
4901       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4902         return SDValue();
4903       LDBase = cast<LoadSDNode>(Elt.getNode());
4904       LastLoadedElt = i;
4905       continue;
4906     }
4907     if (Elt.getOpcode() == ISD::UNDEF)
4908       continue;
4909
4910     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4911     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4912       return SDValue();
4913     LastLoadedElt = i;
4914   }
4915
4916   // If we have found an entire vector of loads and undefs, then return a large
4917   // load of the entire vector width starting at the base pointer.  If we found
4918   // consecutive loads for the low half, generate a vzext_load node.
4919   if (LastLoadedElt == NumElems - 1) {
4920     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4921       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4922                          LDBase->getPointerInfo(),
4923                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4924                          LDBase->isInvariant(), 0);
4925     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4926                        LDBase->getPointerInfo(),
4927                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4928                        LDBase->isInvariant(), LDBase->getAlignment());
4929   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4930              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4931     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4932     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4933     SDValue ResNode =
4934         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4935                                 LDBase->getPointerInfo(),
4936                                 LDBase->getAlignment(),
4937                                 false/*isVolatile*/, true/*ReadMem*/,
4938                                 false/*WriteMem*/);
4939     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4940   }
4941   return SDValue();
4942 }
4943
4944 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4945 /// a vbroadcast node. We support two patterns:
4946 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4947 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4948 /// a scalar load.
4949 /// The scalar load node is returned when a pattern is found,
4950 /// or SDValue() otherwise.
4951 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4952   EVT VT = Op.getValueType();
4953   SDValue V = Op;
4954
4955   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4956     V = V.getOperand(0);
4957
4958   //A suspected load to be broadcasted.
4959   SDValue Ld;
4960
4961   switch (V.getOpcode()) {
4962     default:
4963       // Unknown pattern found.
4964       return SDValue();
4965
4966     case ISD::BUILD_VECTOR: {
4967       // The BUILD_VECTOR node must be a splat.
4968       if (!isSplatVector(V.getNode()))
4969         return SDValue();
4970
4971       Ld = V.getOperand(0);
4972
4973       // The suspected load node has several users. Make sure that all
4974       // of its users are from the BUILD_VECTOR node.
4975       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4976         return SDValue();
4977       break;
4978     }
4979
4980     case ISD::VECTOR_SHUFFLE: {
4981       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4982
4983       // Shuffles must have a splat mask where the first element is
4984       // broadcasted.
4985       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4986         return SDValue();
4987
4988       SDValue Sc = Op.getOperand(0);
4989       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4990         return SDValue();
4991
4992       Ld = Sc.getOperand(0);
4993
4994       // The scalar_to_vector node and the suspected
4995       // load node must have exactly one user.
4996       if (!Sc.hasOneUse() || !Ld.hasOneUse())
4997         return SDValue();
4998       break;
4999     }
5000   }
5001
5002   // The scalar source must be a normal load.
5003   if (!ISD::isNormalLoad(Ld.getNode()))
5004     return SDValue();
5005
5006   bool Is256 = VT.getSizeInBits() == 256;
5007   bool Is128 = VT.getSizeInBits() == 128;
5008   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5009
5010   if (hasAVX2) {
5011     // VBroadcast to YMM
5012     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5013                   ScalarSize == 32 || ScalarSize == 64 ))
5014       return Ld;
5015
5016     // VBroadcast to XMM
5017     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5018                   ScalarSize == 16 || ScalarSize == 64 ))
5019       return Ld;
5020   }
5021
5022   // VBroadcast to YMM
5023   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5024     return Ld;
5025
5026   // VBroadcast to XMM
5027   if (Is128 && (ScalarSize == 32))
5028     return Ld;
5029
5030
5031   // Unsupported broadcast.
5032   return SDValue();
5033 }
5034
5035 SDValue
5036 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5037   DebugLoc dl = Op.getDebugLoc();
5038
5039   EVT VT = Op.getValueType();
5040   EVT ExtVT = VT.getVectorElementType();
5041   unsigned NumElems = Op.getNumOperands();
5042
5043   // Vectors containing all zeros can be matched by pxor and xorps later
5044   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5045     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5046     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5047     if (Op.getValueType() == MVT::v4i32 ||
5048         Op.getValueType() == MVT::v8i32)
5049       return Op;
5050
5051     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5052   }
5053
5054   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5055   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5056   // vpcmpeqd on 256-bit vectors.
5057   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5058     if (Op.getValueType() == MVT::v4i32 ||
5059         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5060       return Op;
5061
5062     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5063   }
5064
5065   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5066   if (Subtarget->hasAVX() && LD.getNode())
5067       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5068
5069   unsigned EVTBits = ExtVT.getSizeInBits();
5070
5071   unsigned NumZero  = 0;
5072   unsigned NumNonZero = 0;
5073   unsigned NonZeros = 0;
5074   bool IsAllConstants = true;
5075   SmallSet<SDValue, 8> Values;
5076   for (unsigned i = 0; i < NumElems; ++i) {
5077     SDValue Elt = Op.getOperand(i);
5078     if (Elt.getOpcode() == ISD::UNDEF)
5079       continue;
5080     Values.insert(Elt);
5081     if (Elt.getOpcode() != ISD::Constant &&
5082         Elt.getOpcode() != ISD::ConstantFP)
5083       IsAllConstants = false;
5084     if (X86::isZeroNode(Elt))
5085       NumZero++;
5086     else {
5087       NonZeros |= (1 << i);
5088       NumNonZero++;
5089     }
5090   }
5091
5092   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5093   if (NumNonZero == 0)
5094     return DAG.getUNDEF(VT);
5095
5096   // Special case for single non-zero, non-undef, element.
5097   if (NumNonZero == 1) {
5098     unsigned Idx = CountTrailingZeros_32(NonZeros);
5099     SDValue Item = Op.getOperand(Idx);
5100
5101     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5102     // the value are obviously zero, truncate the value to i32 and do the
5103     // insertion that way.  Only do this if the value is non-constant or if the
5104     // value is a constant being inserted into element 0.  It is cheaper to do
5105     // a constant pool load than it is to do a movd + shuffle.
5106     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5107         (!IsAllConstants || Idx == 0)) {
5108       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5109         // Handle SSE only.
5110         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5111         EVT VecVT = MVT::v4i32;
5112         unsigned VecElts = 4;
5113
5114         // Truncate the value (which may itself be a constant) to i32, and
5115         // convert it to a vector with movd (S2V+shuffle to zero extend).
5116         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5117         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5118         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5119                                            Subtarget->hasXMMInt(), DAG);
5120
5121         // Now we have our 32-bit value zero extended in the low element of
5122         // a vector.  If Idx != 0, swizzle it into place.
5123         if (Idx != 0) {
5124           SmallVector<int, 4> Mask;
5125           Mask.push_back(Idx);
5126           for (unsigned i = 1; i != VecElts; ++i)
5127             Mask.push_back(i);
5128           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5129                                       DAG.getUNDEF(Item.getValueType()),
5130                                       &Mask[0]);
5131         }
5132         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5133       }
5134     }
5135
5136     // If we have a constant or non-constant insertion into the low element of
5137     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5138     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5139     // depending on what the source datatype is.
5140     if (Idx == 0) {
5141       if (NumZero == 0) {
5142         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5143       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5144           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5145         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5146         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5147         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5148                                            DAG);
5149       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5150         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5151         unsigned NumBits = VT.getSizeInBits();
5152         assert((NumBits == 128 || NumBits == 256) && 
5153                "Expected an SSE or AVX value type!");
5154         EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5155         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5156         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5157                                            Subtarget->hasXMMInt(), DAG);
5158         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5159       }
5160     }
5161
5162     // Is it a vector logical left shift?
5163     if (NumElems == 2 && Idx == 1 &&
5164         X86::isZeroNode(Op.getOperand(0)) &&
5165         !X86::isZeroNode(Op.getOperand(1))) {
5166       unsigned NumBits = VT.getSizeInBits();
5167       return getVShift(true, VT,
5168                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5169                                    VT, Op.getOperand(1)),
5170                        NumBits/2, DAG, *this, dl);
5171     }
5172
5173     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5174       return SDValue();
5175
5176     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5177     // is a non-constant being inserted into an element other than the low one,
5178     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5179     // movd/movss) to move this into the low element, then shuffle it into
5180     // place.
5181     if (EVTBits == 32) {
5182       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5183
5184       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5185       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5186                                          Subtarget->hasXMMInt(), DAG);
5187       SmallVector<int, 8> MaskVec;
5188       for (unsigned i = 0; i < NumElems; i++)
5189         MaskVec.push_back(i == Idx ? 0 : 1);
5190       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5191     }
5192   }
5193
5194   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5195   if (Values.size() == 1) {
5196     if (EVTBits == 32) {
5197       // Instead of a shuffle like this:
5198       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5199       // Check if it's possible to issue this instead.
5200       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5201       unsigned Idx = CountTrailingZeros_32(NonZeros);
5202       SDValue Item = Op.getOperand(Idx);
5203       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5204         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5205     }
5206     return SDValue();
5207   }
5208
5209   // A vector full of immediates; various special cases are already
5210   // handled, so this is best done with a single constant-pool load.
5211   if (IsAllConstants)
5212     return SDValue();
5213
5214   // For AVX-length vectors, build the individual 128-bit pieces and use
5215   // shuffles to put them in place.
5216   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5217     SmallVector<SDValue, 32> V;
5218     for (unsigned i = 0; i < NumElems; ++i)
5219       V.push_back(Op.getOperand(i));
5220
5221     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5222
5223     // Build both the lower and upper subvector.
5224     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5225     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5226                                 NumElems/2);
5227
5228     // Recreate the wider vector with the lower and upper part.
5229     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5230                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5231     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5232                               DAG, dl);
5233   }
5234
5235   // Let legalizer expand 2-wide build_vectors.
5236   if (EVTBits == 64) {
5237     if (NumNonZero == 1) {
5238       // One half is zero or undef.
5239       unsigned Idx = CountTrailingZeros_32(NonZeros);
5240       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5241                                  Op.getOperand(Idx));
5242       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5243                                          Subtarget->hasXMMInt(), DAG);
5244     }
5245     return SDValue();
5246   }
5247
5248   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5249   if (EVTBits == 8 && NumElems == 16) {
5250     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5251                                         *this);
5252     if (V.getNode()) return V;
5253   }
5254
5255   if (EVTBits == 16 && NumElems == 8) {
5256     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5257                                       *this);
5258     if (V.getNode()) return V;
5259   }
5260
5261   // If element VT is == 32 bits, turn it into a number of shuffles.
5262   SmallVector<SDValue, 8> V;
5263   V.resize(NumElems);
5264   if (NumElems == 4 && NumZero > 0) {
5265     for (unsigned i = 0; i < 4; ++i) {
5266       bool isZero = !(NonZeros & (1 << i));
5267       if (isZero)
5268         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5269       else
5270         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5271     }
5272
5273     for (unsigned i = 0; i < 2; ++i) {
5274       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5275         default: break;
5276         case 0:
5277           V[i] = V[i*2];  // Must be a zero vector.
5278           break;
5279         case 1:
5280           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5281           break;
5282         case 2:
5283           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5284           break;
5285         case 3:
5286           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5287           break;
5288       }
5289     }
5290
5291     SmallVector<int, 8> MaskVec;
5292     bool Reverse = (NonZeros & 0x3) == 2;
5293     for (unsigned i = 0; i < 2; ++i)
5294       MaskVec.push_back(Reverse ? 1-i : i);
5295     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5296     for (unsigned i = 0; i < 2; ++i)
5297       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5298     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5299   }
5300
5301   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5302     // Check for a build vector of consecutive loads.
5303     for (unsigned i = 0; i < NumElems; ++i)
5304       V[i] = Op.getOperand(i);
5305
5306     // Check for elements which are consecutive loads.
5307     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5308     if (LD.getNode())
5309       return LD;
5310
5311     // For SSE 4.1, use insertps to put the high elements into the low element.
5312     if (getSubtarget()->hasSSE41orAVX()) {
5313       SDValue Result;
5314       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5315         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5316       else
5317         Result = DAG.getUNDEF(VT);
5318
5319       for (unsigned i = 1; i < NumElems; ++i) {
5320         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5321         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5322                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5323       }
5324       return Result;
5325     }
5326
5327     // Otherwise, expand into a number of unpckl*, start by extending each of
5328     // our (non-undef) elements to the full vector width with the element in the
5329     // bottom slot of the vector (which generates no code for SSE).
5330     for (unsigned i = 0; i < NumElems; ++i) {
5331       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5332         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5333       else
5334         V[i] = DAG.getUNDEF(VT);
5335     }
5336
5337     // Next, we iteratively mix elements, e.g. for v4f32:
5338     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5339     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5340     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5341     unsigned EltStride = NumElems >> 1;
5342     while (EltStride != 0) {
5343       for (unsigned i = 0; i < EltStride; ++i) {
5344         // If V[i+EltStride] is undef and this is the first round of mixing,
5345         // then it is safe to just drop this shuffle: V[i] is already in the
5346         // right place, the one element (since it's the first round) being
5347         // inserted as undef can be dropped.  This isn't safe for successive
5348         // rounds because they will permute elements within both vectors.
5349         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5350             EltStride == NumElems/2)
5351           continue;
5352
5353         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5354       }
5355       EltStride >>= 1;
5356     }
5357     return V[0];
5358   }
5359   return SDValue();
5360 }
5361
5362 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5363 // them in a MMX register.  This is better than doing a stack convert.
5364 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5365   DebugLoc dl = Op.getDebugLoc();
5366   EVT ResVT = Op.getValueType();
5367
5368   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5369          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5370   int Mask[2];
5371   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5372   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5373   InVec = Op.getOperand(1);
5374   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5375     unsigned NumElts = ResVT.getVectorNumElements();
5376     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5377     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5378                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5379   } else {
5380     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5381     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5382     Mask[0] = 0; Mask[1] = 2;
5383     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5384   }
5385   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5386 }
5387
5388 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5389 // to create 256-bit vectors from two other 128-bit ones.
5390 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5391   DebugLoc dl = Op.getDebugLoc();
5392   EVT ResVT = Op.getValueType();
5393
5394   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5395
5396   SDValue V1 = Op.getOperand(0);
5397   SDValue V2 = Op.getOperand(1);
5398   unsigned NumElems = ResVT.getVectorNumElements();
5399
5400   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5401                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5402   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5403                             DAG, dl);
5404 }
5405
5406 SDValue
5407 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5408   EVT ResVT = Op.getValueType();
5409
5410   assert(Op.getNumOperands() == 2);
5411   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5412          "Unsupported CONCAT_VECTORS for value type");
5413
5414   // We support concatenate two MMX registers and place them in a MMX register.
5415   // This is better than doing a stack convert.
5416   if (ResVT.is128BitVector())
5417     return LowerMMXCONCAT_VECTORS(Op, DAG);
5418
5419   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5420   // from two other 128-bit ones.
5421   return LowerAVXCONCAT_VECTORS(Op, DAG);
5422 }
5423
5424 // v8i16 shuffles - Prefer shuffles in the following order:
5425 // 1. [all]   pshuflw, pshufhw, optional move
5426 // 2. [ssse3] 1 x pshufb
5427 // 3. [ssse3] 2 x pshufb + 1 x por
5428 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5429 SDValue
5430 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5431                                             SelectionDAG &DAG) const {
5432   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5433   SDValue V1 = SVOp->getOperand(0);
5434   SDValue V2 = SVOp->getOperand(1);
5435   DebugLoc dl = SVOp->getDebugLoc();
5436   SmallVector<int, 8> MaskVals;
5437
5438   // Determine if more than 1 of the words in each of the low and high quadwords
5439   // of the result come from the same quadword of one of the two inputs.  Undef
5440   // mask values count as coming from any quadword, for better codegen.
5441   unsigned LoQuad[] = { 0, 0, 0, 0 };
5442   unsigned HiQuad[] = { 0, 0, 0, 0 };
5443   BitVector InputQuads(4);
5444   for (unsigned i = 0; i < 8; ++i) {
5445     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5446     int EltIdx = SVOp->getMaskElt(i);
5447     MaskVals.push_back(EltIdx);
5448     if (EltIdx < 0) {
5449       ++Quad[0];
5450       ++Quad[1];
5451       ++Quad[2];
5452       ++Quad[3];
5453       continue;
5454     }
5455     ++Quad[EltIdx / 4];
5456     InputQuads.set(EltIdx / 4);
5457   }
5458
5459   int BestLoQuad = -1;
5460   unsigned MaxQuad = 1;
5461   for (unsigned i = 0; i < 4; ++i) {
5462     if (LoQuad[i] > MaxQuad) {
5463       BestLoQuad = i;
5464       MaxQuad = LoQuad[i];
5465     }
5466   }
5467
5468   int BestHiQuad = -1;
5469   MaxQuad = 1;
5470   for (unsigned i = 0; i < 4; ++i) {
5471     if (HiQuad[i] > MaxQuad) {
5472       BestHiQuad = i;
5473       MaxQuad = HiQuad[i];
5474     }
5475   }
5476
5477   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5478   // of the two input vectors, shuffle them into one input vector so only a
5479   // single pshufb instruction is necessary. If There are more than 2 input
5480   // quads, disable the next transformation since it does not help SSSE3.
5481   bool V1Used = InputQuads[0] || InputQuads[1];
5482   bool V2Used = InputQuads[2] || InputQuads[3];
5483   if (Subtarget->hasSSSE3orAVX()) {
5484     if (InputQuads.count() == 2 && V1Used && V2Used) {
5485       BestLoQuad = InputQuads.find_first();
5486       BestHiQuad = InputQuads.find_next(BestLoQuad);
5487     }
5488     if (InputQuads.count() > 2) {
5489       BestLoQuad = -1;
5490       BestHiQuad = -1;
5491     }
5492   }
5493
5494   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5495   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5496   // words from all 4 input quadwords.
5497   SDValue NewV;
5498   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5499     SmallVector<int, 8> MaskV;
5500     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5501     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5502     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5503                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5504                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5505     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5506
5507     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5508     // source words for the shuffle, to aid later transformations.
5509     bool AllWordsInNewV = true;
5510     bool InOrder[2] = { true, true };
5511     for (unsigned i = 0; i != 8; ++i) {
5512       int idx = MaskVals[i];
5513       if (idx != (int)i)
5514         InOrder[i/4] = false;
5515       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5516         continue;
5517       AllWordsInNewV = false;
5518       break;
5519     }
5520
5521     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5522     if (AllWordsInNewV) {
5523       for (int i = 0; i != 8; ++i) {
5524         int idx = MaskVals[i];
5525         if (idx < 0)
5526           continue;
5527         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5528         if ((idx != i) && idx < 4)
5529           pshufhw = false;
5530         if ((idx != i) && idx > 3)
5531           pshuflw = false;
5532       }
5533       V1 = NewV;
5534       V2Used = false;
5535       BestLoQuad = 0;
5536       BestHiQuad = 1;
5537     }
5538
5539     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5540     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5541     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5542       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5543       unsigned TargetMask = 0;
5544       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5545                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5546       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5547                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5548       V1 = NewV.getOperand(0);
5549       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5550     }
5551   }
5552
5553   // If we have SSSE3, and all words of the result are from 1 input vector,
5554   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5555   // is present, fall back to case 4.
5556   if (Subtarget->hasSSSE3orAVX()) {
5557     SmallVector<SDValue,16> pshufbMask;
5558
5559     // If we have elements from both input vectors, set the high bit of the
5560     // shuffle mask element to zero out elements that come from V2 in the V1
5561     // mask, and elements that come from V1 in the V2 mask, so that the two
5562     // results can be OR'd together.
5563     bool TwoInputs = V1Used && V2Used;
5564     for (unsigned i = 0; i != 8; ++i) {
5565       int EltIdx = MaskVals[i] * 2;
5566       if (TwoInputs && (EltIdx >= 16)) {
5567         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5568         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5569         continue;
5570       }
5571       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5572       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5573     }
5574     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5575     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5576                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5577                                  MVT::v16i8, &pshufbMask[0], 16));
5578     if (!TwoInputs)
5579       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5580
5581     // Calculate the shuffle mask for the second input, shuffle it, and
5582     // OR it with the first shuffled input.
5583     pshufbMask.clear();
5584     for (unsigned i = 0; i != 8; ++i) {
5585       int EltIdx = MaskVals[i] * 2;
5586       if (EltIdx < 16) {
5587         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5588         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5589         continue;
5590       }
5591       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5592       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5593     }
5594     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5595     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5596                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5597                                  MVT::v16i8, &pshufbMask[0], 16));
5598     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5599     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5600   }
5601
5602   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5603   // and update MaskVals with new element order.
5604   BitVector InOrder(8);
5605   if (BestLoQuad >= 0) {
5606     SmallVector<int, 8> MaskV;
5607     for (int i = 0; i != 4; ++i) {
5608       int idx = MaskVals[i];
5609       if (idx < 0) {
5610         MaskV.push_back(-1);
5611         InOrder.set(i);
5612       } else if ((idx / 4) == BestLoQuad) {
5613         MaskV.push_back(idx & 3);
5614         InOrder.set(i);
5615       } else {
5616         MaskV.push_back(-1);
5617       }
5618     }
5619     for (unsigned i = 4; i != 8; ++i)
5620       MaskV.push_back(i);
5621     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5622                                 &MaskV[0]);
5623
5624     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5625       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5626                                NewV.getOperand(0),
5627                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5628                                DAG);
5629   }
5630
5631   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5632   // and update MaskVals with the new element order.
5633   if (BestHiQuad >= 0) {
5634     SmallVector<int, 8> MaskV;
5635     for (unsigned i = 0; i != 4; ++i)
5636       MaskV.push_back(i);
5637     for (unsigned i = 4; i != 8; ++i) {
5638       int idx = MaskVals[i];
5639       if (idx < 0) {
5640         MaskV.push_back(-1);
5641         InOrder.set(i);
5642       } else if ((idx / 4) == BestHiQuad) {
5643         MaskV.push_back((idx & 3) + 4);
5644         InOrder.set(i);
5645       } else {
5646         MaskV.push_back(-1);
5647       }
5648     }
5649     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5650                                 &MaskV[0]);
5651
5652     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5653       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5654                               NewV.getOperand(0),
5655                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5656                               DAG);
5657   }
5658
5659   // In case BestHi & BestLo were both -1, which means each quadword has a word
5660   // from each of the four input quadwords, calculate the InOrder bitvector now
5661   // before falling through to the insert/extract cleanup.
5662   if (BestLoQuad == -1 && BestHiQuad == -1) {
5663     NewV = V1;
5664     for (int i = 0; i != 8; ++i)
5665       if (MaskVals[i] < 0 || MaskVals[i] == i)
5666         InOrder.set(i);
5667   }
5668
5669   // The other elements are put in the right place using pextrw and pinsrw.
5670   for (unsigned i = 0; i != 8; ++i) {
5671     if (InOrder[i])
5672       continue;
5673     int EltIdx = MaskVals[i];
5674     if (EltIdx < 0)
5675       continue;
5676     SDValue ExtOp = (EltIdx < 8)
5677     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5678                   DAG.getIntPtrConstant(EltIdx))
5679     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5680                   DAG.getIntPtrConstant(EltIdx - 8));
5681     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5682                        DAG.getIntPtrConstant(i));
5683   }
5684   return NewV;
5685 }
5686
5687 // v16i8 shuffles - Prefer shuffles in the following order:
5688 // 1. [ssse3] 1 x pshufb
5689 // 2. [ssse3] 2 x pshufb + 1 x por
5690 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5691 static
5692 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5693                                  SelectionDAG &DAG,
5694                                  const X86TargetLowering &TLI) {
5695   SDValue V1 = SVOp->getOperand(0);
5696   SDValue V2 = SVOp->getOperand(1);
5697   DebugLoc dl = SVOp->getDebugLoc();
5698   SmallVector<int, 16> MaskVals;
5699   SVOp->getMask(MaskVals);
5700
5701   // If we have SSSE3, case 1 is generated when all result bytes come from
5702   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5703   // present, fall back to case 3.
5704   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5705   bool V1Only = true;
5706   bool V2Only = true;
5707   for (unsigned i = 0; i < 16; ++i) {
5708     int EltIdx = MaskVals[i];
5709     if (EltIdx < 0)
5710       continue;
5711     if (EltIdx < 16)
5712       V2Only = false;
5713     else
5714       V1Only = false;
5715   }
5716
5717   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5718   if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5719     SmallVector<SDValue,16> pshufbMask;
5720
5721     // If all result elements are from one input vector, then only translate
5722     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5723     //
5724     // Otherwise, we have elements from both input vectors, and must zero out
5725     // elements that come from V2 in the first mask, and V1 in the second mask
5726     // so that we can OR them together.
5727     bool TwoInputs = !(V1Only || V2Only);
5728     for (unsigned i = 0; i != 16; ++i) {
5729       int EltIdx = MaskVals[i];
5730       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5731         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5732         continue;
5733       }
5734       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5735     }
5736     // If all the elements are from V2, assign it to V1 and return after
5737     // building the first pshufb.
5738     if (V2Only)
5739       V1 = V2;
5740     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5741                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5742                                  MVT::v16i8, &pshufbMask[0], 16));
5743     if (!TwoInputs)
5744       return V1;
5745
5746     // Calculate the shuffle mask for the second input, shuffle it, and
5747     // OR it with the first shuffled input.
5748     pshufbMask.clear();
5749     for (unsigned i = 0; i != 16; ++i) {
5750       int EltIdx = MaskVals[i];
5751       if (EltIdx < 16) {
5752         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5753         continue;
5754       }
5755       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5756     }
5757     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5758                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5759                                  MVT::v16i8, &pshufbMask[0], 16));
5760     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5761   }
5762
5763   // No SSSE3 - Calculate in place words and then fix all out of place words
5764   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5765   // the 16 different words that comprise the two doublequadword input vectors.
5766   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5767   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5768   SDValue NewV = V2Only ? V2 : V1;
5769   for (int i = 0; i != 8; ++i) {
5770     int Elt0 = MaskVals[i*2];
5771     int Elt1 = MaskVals[i*2+1];
5772
5773     // This word of the result is all undef, skip it.
5774     if (Elt0 < 0 && Elt1 < 0)
5775       continue;
5776
5777     // This word of the result is already in the correct place, skip it.
5778     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5779       continue;
5780     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5781       continue;
5782
5783     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5784     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5785     SDValue InsElt;
5786
5787     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5788     // using a single extract together, load it and store it.
5789     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5790       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5791                            DAG.getIntPtrConstant(Elt1 / 2));
5792       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5793                         DAG.getIntPtrConstant(i));
5794       continue;
5795     }
5796
5797     // If Elt1 is defined, extract it from the appropriate source.  If the
5798     // source byte is not also odd, shift the extracted word left 8 bits
5799     // otherwise clear the bottom 8 bits if we need to do an or.
5800     if (Elt1 >= 0) {
5801       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5802                            DAG.getIntPtrConstant(Elt1 / 2));
5803       if ((Elt1 & 1) == 0)
5804         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5805                              DAG.getConstant(8,
5806                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5807       else if (Elt0 >= 0)
5808         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5809                              DAG.getConstant(0xFF00, MVT::i16));
5810     }
5811     // If Elt0 is defined, extract it from the appropriate source.  If the
5812     // source byte is not also even, shift the extracted word right 8 bits. If
5813     // Elt1 was also defined, OR the extracted values together before
5814     // inserting them in the result.
5815     if (Elt0 >= 0) {
5816       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5817                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5818       if ((Elt0 & 1) != 0)
5819         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5820                               DAG.getConstant(8,
5821                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5822       else if (Elt1 >= 0)
5823         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5824                              DAG.getConstant(0x00FF, MVT::i16));
5825       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5826                          : InsElt0;
5827     }
5828     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5829                        DAG.getIntPtrConstant(i));
5830   }
5831   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5832 }
5833
5834 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5835 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5836 /// done when every pair / quad of shuffle mask elements point to elements in
5837 /// the right sequence. e.g.
5838 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5839 static
5840 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5841                                  SelectionDAG &DAG, DebugLoc dl) {
5842   EVT VT = SVOp->getValueType(0);
5843   SDValue V1 = SVOp->getOperand(0);
5844   SDValue V2 = SVOp->getOperand(1);
5845   unsigned NumElems = VT.getVectorNumElements();
5846   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5847   EVT NewVT;
5848   switch (VT.getSimpleVT().SimpleTy) {
5849   default: assert(false && "Unexpected!");
5850   case MVT::v4f32: NewVT = MVT::v2f64; break;
5851   case MVT::v4i32: NewVT = MVT::v2i64; break;
5852   case MVT::v8i16: NewVT = MVT::v4i32; break;
5853   case MVT::v16i8: NewVT = MVT::v4i32; break;
5854   }
5855
5856   int Scale = NumElems / NewWidth;
5857   SmallVector<int, 8> MaskVec;
5858   for (unsigned i = 0; i < NumElems; i += Scale) {
5859     int StartIdx = -1;
5860     for (int j = 0; j < Scale; ++j) {
5861       int EltIdx = SVOp->getMaskElt(i+j);
5862       if (EltIdx < 0)
5863         continue;
5864       if (StartIdx == -1)
5865         StartIdx = EltIdx - (EltIdx % Scale);
5866       if (EltIdx != StartIdx + j)
5867         return SDValue();
5868     }
5869     if (StartIdx == -1)
5870       MaskVec.push_back(-1);
5871     else
5872       MaskVec.push_back(StartIdx / Scale);
5873   }
5874
5875   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5876   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5877   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5878 }
5879
5880 /// getVZextMovL - Return a zero-extending vector move low node.
5881 ///
5882 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5883                             SDValue SrcOp, SelectionDAG &DAG,
5884                             const X86Subtarget *Subtarget, DebugLoc dl) {
5885   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5886     LoadSDNode *LD = NULL;
5887     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5888       LD = dyn_cast<LoadSDNode>(SrcOp);
5889     if (!LD) {
5890       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5891       // instead.
5892       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5893       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5894           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5895           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5896           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5897         // PR2108
5898         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5899         return DAG.getNode(ISD::BITCAST, dl, VT,
5900                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5901                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5902                                                    OpVT,
5903                                                    SrcOp.getOperand(0)
5904                                                           .getOperand(0))));
5905       }
5906     }
5907   }
5908
5909   return DAG.getNode(ISD::BITCAST, dl, VT,
5910                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5911                                  DAG.getNode(ISD::BITCAST, dl,
5912                                              OpVT, SrcOp)));
5913 }
5914
5915 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5916 /// shuffle node referes to only one lane in the sources.
5917 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5918   EVT VT = SVOp->getValueType(0);
5919   int NumElems = VT.getVectorNumElements();
5920   int HalfSize = NumElems/2;
5921   SmallVector<int, 16> M;
5922   SVOp->getMask(M);
5923   bool MatchA = false, MatchB = false;
5924
5925   for (int l = 0; l < NumElems*2; l += HalfSize) {
5926     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5927       MatchA = true;
5928       break;
5929     }
5930   }
5931
5932   for (int l = 0; l < NumElems*2; l += HalfSize) {
5933     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5934       MatchB = true;
5935       break;
5936     }
5937   }
5938
5939   return MatchA && MatchB;
5940 }
5941
5942 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5943 /// which could not be matched by any known target speficic shuffle
5944 static SDValue
5945 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5946   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5947     // If each half of a vector shuffle node referes to only one lane in the
5948     // source vectors, extract each used 128-bit lane and shuffle them using
5949     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5950     // the work to the legalizer.
5951     DebugLoc dl = SVOp->getDebugLoc();
5952     EVT VT = SVOp->getValueType(0);
5953     int NumElems = VT.getVectorNumElements();
5954     int HalfSize = NumElems/2;
5955
5956     // Extract the reference for each half
5957     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5958     int FstVecOpNum = 0, SndVecOpNum = 0;
5959     for (int i = 0; i < HalfSize; ++i) {
5960       int Elt = SVOp->getMaskElt(i);
5961       if (SVOp->getMaskElt(i) < 0)
5962         continue;
5963       FstVecOpNum = Elt/NumElems;
5964       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5965       break;
5966     }
5967     for (int i = HalfSize; i < NumElems; ++i) {
5968       int Elt = SVOp->getMaskElt(i);
5969       if (SVOp->getMaskElt(i) < 0)
5970         continue;
5971       SndVecOpNum = Elt/NumElems;
5972       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5973       break;
5974     }
5975
5976     // Extract the subvectors
5977     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5978                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5979     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5980                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5981
5982     // Generate 128-bit shuffles
5983     SmallVector<int, 16> MaskV1, MaskV2;
5984     for (int i = 0; i < HalfSize; ++i) {
5985       int Elt = SVOp->getMaskElt(i);
5986       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5987     }
5988     for (int i = HalfSize; i < NumElems; ++i) {
5989       int Elt = SVOp->getMaskElt(i);
5990       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5991     }
5992
5993     EVT NVT = V1.getValueType();
5994     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5995     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5996
5997     // Concatenate the result back
5998     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5999                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6000     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6001                               DAG, dl);
6002   }
6003
6004   return SDValue();
6005 }
6006
6007 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6008 /// 4 elements, and match them with several different shuffle types.
6009 static SDValue
6010 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6011   SDValue V1 = SVOp->getOperand(0);
6012   SDValue V2 = SVOp->getOperand(1);
6013   DebugLoc dl = SVOp->getDebugLoc();
6014   EVT VT = SVOp->getValueType(0);
6015
6016   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6017
6018   SmallVector<std::pair<int, int>, 8> Locs;
6019   Locs.resize(4);
6020   SmallVector<int, 8> Mask1(4U, -1);
6021   SmallVector<int, 8> PermMask;
6022   SVOp->getMask(PermMask);
6023
6024   unsigned NumHi = 0;
6025   unsigned NumLo = 0;
6026   for (unsigned i = 0; i != 4; ++i) {
6027     int Idx = PermMask[i];
6028     if (Idx < 0) {
6029       Locs[i] = std::make_pair(-1, -1);
6030     } else {
6031       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6032       if (Idx < 4) {
6033         Locs[i] = std::make_pair(0, NumLo);
6034         Mask1[NumLo] = Idx;
6035         NumLo++;
6036       } else {
6037         Locs[i] = std::make_pair(1, NumHi);
6038         if (2+NumHi < 4)
6039           Mask1[2+NumHi] = Idx;
6040         NumHi++;
6041       }
6042     }
6043   }
6044
6045   if (NumLo <= 2 && NumHi <= 2) {
6046     // If no more than two elements come from either vector. This can be
6047     // implemented with two shuffles. First shuffle gather the elements.
6048     // The second shuffle, which takes the first shuffle as both of its
6049     // vector operands, put the elements into the right order.
6050     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6051
6052     SmallVector<int, 8> Mask2(4U, -1);
6053
6054     for (unsigned i = 0; i != 4; ++i) {
6055       if (Locs[i].first == -1)
6056         continue;
6057       else {
6058         unsigned Idx = (i < 2) ? 0 : 4;
6059         Idx += Locs[i].first * 2 + Locs[i].second;
6060         Mask2[i] = Idx;
6061       }
6062     }
6063
6064     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6065   } else if (NumLo == 3 || NumHi == 3) {
6066     // Otherwise, we must have three elements from one vector, call it X, and
6067     // one element from the other, call it Y.  First, use a shufps to build an
6068     // intermediate vector with the one element from Y and the element from X
6069     // that will be in the same half in the final destination (the indexes don't
6070     // matter). Then, use a shufps to build the final vector, taking the half
6071     // containing the element from Y from the intermediate, and the other half
6072     // from X.
6073     if (NumHi == 3) {
6074       // Normalize it so the 3 elements come from V1.
6075       CommuteVectorShuffleMask(PermMask, 4);
6076       std::swap(V1, V2);
6077     }
6078
6079     // Find the element from V2.
6080     unsigned HiIndex;
6081     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6082       int Val = PermMask[HiIndex];
6083       if (Val < 0)
6084         continue;
6085       if (Val >= 4)
6086         break;
6087     }
6088
6089     Mask1[0] = PermMask[HiIndex];
6090     Mask1[1] = -1;
6091     Mask1[2] = PermMask[HiIndex^1];
6092     Mask1[3] = -1;
6093     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6094
6095     if (HiIndex >= 2) {
6096       Mask1[0] = PermMask[0];
6097       Mask1[1] = PermMask[1];
6098       Mask1[2] = HiIndex & 1 ? 6 : 4;
6099       Mask1[3] = HiIndex & 1 ? 4 : 6;
6100       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6101     } else {
6102       Mask1[0] = HiIndex & 1 ? 2 : 0;
6103       Mask1[1] = HiIndex & 1 ? 0 : 2;
6104       Mask1[2] = PermMask[2];
6105       Mask1[3] = PermMask[3];
6106       if (Mask1[2] >= 0)
6107         Mask1[2] += 4;
6108       if (Mask1[3] >= 0)
6109         Mask1[3] += 4;
6110       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6111     }
6112   }
6113
6114   // Break it into (shuffle shuffle_hi, shuffle_lo).
6115   Locs.clear();
6116   Locs.resize(4);
6117   SmallVector<int,8> LoMask(4U, -1);
6118   SmallVector<int,8> HiMask(4U, -1);
6119
6120   SmallVector<int,8> *MaskPtr = &LoMask;
6121   unsigned MaskIdx = 0;
6122   unsigned LoIdx = 0;
6123   unsigned HiIdx = 2;
6124   for (unsigned i = 0; i != 4; ++i) {
6125     if (i == 2) {
6126       MaskPtr = &HiMask;
6127       MaskIdx = 1;
6128       LoIdx = 0;
6129       HiIdx = 2;
6130     }
6131     int Idx = PermMask[i];
6132     if (Idx < 0) {
6133       Locs[i] = std::make_pair(-1, -1);
6134     } else if (Idx < 4) {
6135       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6136       (*MaskPtr)[LoIdx] = Idx;
6137       LoIdx++;
6138     } else {
6139       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6140       (*MaskPtr)[HiIdx] = Idx;
6141       HiIdx++;
6142     }
6143   }
6144
6145   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6146   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6147   SmallVector<int, 8> MaskOps;
6148   for (unsigned i = 0; i != 4; ++i) {
6149     if (Locs[i].first == -1) {
6150       MaskOps.push_back(-1);
6151     } else {
6152       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6153       MaskOps.push_back(Idx);
6154     }
6155   }
6156   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6157 }
6158
6159 static bool MayFoldVectorLoad(SDValue V) {
6160   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6161     V = V.getOperand(0);
6162   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6163     V = V.getOperand(0);
6164   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6165       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6166     // BUILD_VECTOR (load), undef
6167     V = V.getOperand(0);
6168   if (MayFoldLoad(V))
6169     return true;
6170   return false;
6171 }
6172
6173 // FIXME: the version above should always be used. Since there's
6174 // a bug where several vector shuffles can't be folded because the
6175 // DAG is not updated during lowering and a node claims to have two
6176 // uses while it only has one, use this version, and let isel match
6177 // another instruction if the load really happens to have more than
6178 // one use. Remove this version after this bug get fixed.
6179 // rdar://8434668, PR8156
6180 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6181   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6182     V = V.getOperand(0);
6183   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6184     V = V.getOperand(0);
6185   if (ISD::isNormalLoad(V.getNode()))
6186     return true;
6187   return false;
6188 }
6189
6190 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6191 /// a vector extract, and if both can be later optimized into a single load.
6192 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6193 /// here because otherwise a target specific shuffle node is going to be
6194 /// emitted for this shuffle, and the optimization not done.
6195 /// FIXME: This is probably not the best approach, but fix the problem
6196 /// until the right path is decided.
6197 static
6198 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6199                                          const TargetLowering &TLI) {
6200   EVT VT = V.getValueType();
6201   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6202
6203   // Be sure that the vector shuffle is present in a pattern like this:
6204   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6205   if (!V.hasOneUse())
6206     return false;
6207
6208   SDNode *N = *V.getNode()->use_begin();
6209   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6210     return false;
6211
6212   SDValue EltNo = N->getOperand(1);
6213   if (!isa<ConstantSDNode>(EltNo))
6214     return false;
6215
6216   // If the bit convert changed the number of elements, it is unsafe
6217   // to examine the mask.
6218   bool HasShuffleIntoBitcast = false;
6219   if (V.getOpcode() == ISD::BITCAST) {
6220     EVT SrcVT = V.getOperand(0).getValueType();
6221     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6222       return false;
6223     V = V.getOperand(0);
6224     HasShuffleIntoBitcast = true;
6225   }
6226
6227   // Select the input vector, guarding against out of range extract vector.
6228   unsigned NumElems = VT.getVectorNumElements();
6229   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6230   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6231   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6232
6233   // Skip one more bit_convert if necessary
6234   if (V.getOpcode() == ISD::BITCAST)
6235     V = V.getOperand(0);
6236
6237   if (ISD::isNormalLoad(V.getNode())) {
6238     // Is the original load suitable?
6239     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6240
6241     // FIXME: avoid the multi-use bug that is preventing lots of
6242     // of foldings to be detected, this is still wrong of course, but
6243     // give the temporary desired behavior, and if it happens that
6244     // the load has real more uses, during isel it will not fold, and
6245     // will generate poor code.
6246     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6247       return false;
6248
6249     if (!HasShuffleIntoBitcast)
6250       return true;
6251
6252     // If there's a bitcast before the shuffle, check if the load type and
6253     // alignment is valid.
6254     unsigned Align = LN0->getAlignment();
6255     unsigned NewAlign =
6256       TLI.getTargetData()->getABITypeAlignment(
6257                                     VT.getTypeForEVT(*DAG.getContext()));
6258
6259     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6260       return false;
6261   }
6262
6263   return true;
6264 }
6265
6266 static
6267 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6268   EVT VT = Op.getValueType();
6269
6270   // Canonizalize to v2f64.
6271   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6272   return DAG.getNode(ISD::BITCAST, dl, VT,
6273                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6274                                           V1, DAG));
6275 }
6276
6277 static
6278 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6279                         bool HasXMMInt) {
6280   SDValue V1 = Op.getOperand(0);
6281   SDValue V2 = Op.getOperand(1);
6282   EVT VT = Op.getValueType();
6283
6284   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6285
6286   if (HasXMMInt && VT == MVT::v2f64)
6287     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6288
6289   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6290   return DAG.getNode(ISD::BITCAST, dl, VT,
6291                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6292                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6293                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6294 }
6295
6296 static
6297 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6298   SDValue V1 = Op.getOperand(0);
6299   SDValue V2 = Op.getOperand(1);
6300   EVT VT = Op.getValueType();
6301
6302   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6303          "unsupported shuffle type");
6304
6305   if (V2.getOpcode() == ISD::UNDEF)
6306     V2 = V1;
6307
6308   // v4i32 or v4f32
6309   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6310 }
6311
6312 static inline unsigned getSHUFPOpcode(EVT VT) {
6313   switch(VT.getSimpleVT().SimpleTy) {
6314   case MVT::v8i32: // Use fp unit for int unpack.
6315   case MVT::v8f32:
6316   case MVT::v4i32: // Use fp unit for int unpack.
6317   case MVT::v4f32: return X86ISD::SHUFPS;
6318   case MVT::v4i64: // Use fp unit for int unpack.
6319   case MVT::v4f64:
6320   case MVT::v2i64: // Use fp unit for int unpack.
6321   case MVT::v2f64: return X86ISD::SHUFPD;
6322   default:
6323     llvm_unreachable("Unknown type for shufp*");
6324   }
6325   return 0;
6326 }
6327
6328 static
6329 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6330   SDValue V1 = Op.getOperand(0);
6331   SDValue V2 = Op.getOperand(1);
6332   EVT VT = Op.getValueType();
6333   unsigned NumElems = VT.getVectorNumElements();
6334
6335   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6336   // operand of these instructions is only memory, so check if there's a
6337   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6338   // same masks.
6339   bool CanFoldLoad = false;
6340
6341   // Trivial case, when V2 comes from a load.
6342   if (MayFoldVectorLoad(V2))
6343     CanFoldLoad = true;
6344
6345   // When V1 is a load, it can be folded later into a store in isel, example:
6346   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6347   //    turns into:
6348   //  (MOVLPSmr addr:$src1, VR128:$src2)
6349   // So, recognize this potential and also use MOVLPS or MOVLPD
6350   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6351     CanFoldLoad = true;
6352
6353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6354   if (CanFoldLoad) {
6355     if (HasXMMInt && NumElems == 2)
6356       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6357
6358     if (NumElems == 4)
6359       // If we don't care about the second element, procede to use movss.
6360       if (SVOp->getMaskElt(1) != -1)
6361         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6362   }
6363
6364   // movl and movlp will both match v2i64, but v2i64 is never matched by
6365   // movl earlier because we make it strict to avoid messing with the movlp load
6366   // folding logic (see the code above getMOVLP call). Match it here then,
6367   // this is horrible, but will stay like this until we move all shuffle
6368   // matching to x86 specific nodes. Note that for the 1st condition all
6369   // types are matched with movsd.
6370   if (HasXMMInt) {
6371     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6372     // as to remove this logic from here, as much as possible
6373     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6374       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6375     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6376   }
6377
6378   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6379
6380   // Invert the operand order and use SHUFPS to match it.
6381   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6382                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6383 }
6384
6385 static
6386 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6387                                const TargetLowering &TLI,
6388                                const X86Subtarget *Subtarget) {
6389   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6390   EVT VT = Op.getValueType();
6391   DebugLoc dl = Op.getDebugLoc();
6392   SDValue V1 = Op.getOperand(0);
6393   SDValue V2 = Op.getOperand(1);
6394
6395   if (isZeroShuffle(SVOp))
6396     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6397
6398   // Handle splat operations
6399   if (SVOp->isSplat()) {
6400     unsigned NumElem = VT.getVectorNumElements();
6401     int Size = VT.getSizeInBits();
6402     // Special case, this is the only place now where it's allowed to return
6403     // a vector_shuffle operation without using a target specific node, because
6404     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6405     // this be moved to DAGCombine instead?
6406     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6407       return Op;
6408
6409     // Use vbroadcast whenever the splat comes from a foldable load
6410     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6411     if (Subtarget->hasAVX() && LD.getNode())
6412       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6413
6414     // Handle splats by matching through known shuffle masks
6415     if ((Size == 128 && NumElem <= 4) ||
6416         (Size == 256 && NumElem < 8))
6417       return SDValue();
6418
6419     // All remaning splats are promoted to target supported vector shuffles.
6420     return PromoteSplat(SVOp, DAG);
6421   }
6422
6423   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6424   // do it!
6425   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6426     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6427     if (NewOp.getNode())
6428       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6429   } else if ((VT == MVT::v4i32 ||
6430              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6431     // FIXME: Figure out a cleaner way to do this.
6432     // Try to make use of movq to zero out the top part.
6433     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6434       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6435       if (NewOp.getNode()) {
6436         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6437           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6438                               DAG, Subtarget, dl);
6439       }
6440     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6441       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6442       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6443         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6444                             DAG, Subtarget, dl);
6445     }
6446   }
6447   return SDValue();
6448 }
6449
6450 SDValue
6451 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6453   SDValue V1 = Op.getOperand(0);
6454   SDValue V2 = Op.getOperand(1);
6455   EVT VT = Op.getValueType();
6456   DebugLoc dl = Op.getDebugLoc();
6457   unsigned NumElems = VT.getVectorNumElements();
6458   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6459   bool V1IsSplat = false;
6460   bool V2IsSplat = false;
6461   bool HasXMMInt = Subtarget->hasXMMInt();
6462   bool HasAVX    = Subtarget->hasAVX();
6463   bool HasAVX2   = Subtarget->hasAVX2();
6464   MachineFunction &MF = DAG.getMachineFunction();
6465   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6466
6467   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6468
6469   assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6470
6471   // Vector shuffle lowering takes 3 steps:
6472   //
6473   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6474   //    narrowing and commutation of operands should be handled.
6475   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6476   //    shuffle nodes.
6477   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6478   //    so the shuffle can be broken into other shuffles and the legalizer can
6479   //    try the lowering again.
6480   //
6481   // The general idea is that no vector_shuffle operation should be left to
6482   // be matched during isel, all of them must be converted to a target specific
6483   // node here.
6484
6485   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6486   // narrowing and commutation of operands should be handled. The actual code
6487   // doesn't include all of those, work in progress...
6488   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6489   if (NewOp.getNode())
6490     return NewOp;
6491
6492   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6493   // unpckh_undef). Only use pshufd if speed is more important than size.
6494   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6495     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6496   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6497     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6498
6499   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6500       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6501     return getMOVDDup(Op, dl, V1, DAG);
6502
6503   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6504     return getMOVHighToLow(Op, dl, DAG);
6505
6506   // Use to match splats
6507   if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6508       (VT == MVT::v2f64 || VT == MVT::v2i64))
6509     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6510
6511   if (X86::isPSHUFDMask(SVOp)) {
6512     // The actual implementation will match the mask in the if above and then
6513     // during isel it can match several different instructions, not only pshufd
6514     // as its name says, sad but true, emulate the behavior for now...
6515     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6516         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6517
6518     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6519
6520     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6521       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6522
6523     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6524                                 TargetMask, DAG);
6525   }
6526
6527   // Check if this can be converted into a logical shift.
6528   bool isLeft = false;
6529   unsigned ShAmt = 0;
6530   SDValue ShVal;
6531   bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6532   if (isShift && ShVal.hasOneUse()) {
6533     // If the shifted value has multiple uses, it may be cheaper to use
6534     // v_set0 + movlhps or movhlps, etc.
6535     EVT EltVT = VT.getVectorElementType();
6536     ShAmt *= EltVT.getSizeInBits();
6537     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6538   }
6539
6540   if (X86::isMOVLMask(SVOp)) {
6541     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6542       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6543     if (!X86::isMOVLPMask(SVOp)) {
6544       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6545         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6546
6547       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6548         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6549     }
6550   }
6551
6552   // FIXME: fold these into legal mask.
6553   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6554     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6555
6556   if (X86::isMOVHLPSMask(SVOp))
6557     return getMOVHighToLow(Op, dl, DAG);
6558
6559   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6560     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6561
6562   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6563     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6564
6565   if (X86::isMOVLPMask(SVOp))
6566     return getMOVLP(Op, dl, DAG, HasXMMInt);
6567
6568   if (ShouldXformToMOVHLPS(SVOp) ||
6569       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6570     return CommuteVectorShuffle(SVOp, DAG);
6571
6572   if (isShift) {
6573     // No better options. Use a vshl / vsrl.
6574     EVT EltVT = VT.getVectorElementType();
6575     ShAmt *= EltVT.getSizeInBits();
6576     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6577   }
6578
6579   bool Commuted = false;
6580   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6581   // 1,1,1,1 -> v8i16 though.
6582   V1IsSplat = isSplatVector(V1.getNode());
6583   V2IsSplat = isSplatVector(V2.getNode());
6584
6585   // Canonicalize the splat or undef, if present, to be on the RHS.
6586   if (V1IsSplat && !V2IsSplat) {
6587     Op = CommuteVectorShuffle(SVOp, DAG);
6588     SVOp = cast<ShuffleVectorSDNode>(Op);
6589     V1 = SVOp->getOperand(0);
6590     V2 = SVOp->getOperand(1);
6591     std::swap(V1IsSplat, V2IsSplat);
6592     Commuted = true;
6593   }
6594
6595   SmallVector<int, 32> M;
6596   SVOp->getMask(M);
6597
6598   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6599     // Shuffling low element of v1 into undef, just return v1.
6600     if (V2IsUndef)
6601       return V1;
6602     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6603     // the instruction selector will not match, so get a canonical MOVL with
6604     // swapped operands to undo the commute.
6605     return getMOVL(DAG, dl, VT, V2, V1);
6606   }
6607
6608   if (isUNPCKLMask(M, VT, HasAVX2))
6609     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6610
6611   if (isUNPCKHMask(M, VT, HasAVX2))
6612     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6613
6614   if (V2IsSplat) {
6615     // Normalize mask so all entries that point to V2 points to its first
6616     // element then try to match unpck{h|l} again. If match, return a
6617     // new vector_shuffle with the corrected mask.
6618     SDValue NewMask = NormalizeMask(SVOp, DAG);
6619     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6620     if (NSVOp != SVOp) {
6621       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6622         return NewMask;
6623       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6624         return NewMask;
6625       }
6626     }
6627   }
6628
6629   if (Commuted) {
6630     // Commute is back and try unpck* again.
6631     // FIXME: this seems wrong.
6632     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6633     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6634
6635     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6636       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6637
6638     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6639       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6640   }
6641
6642   // Normalize the node to match x86 shuffle ops if needed
6643   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6644                      isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6645     return CommuteVectorShuffle(SVOp, DAG);
6646
6647   // The checks below are all present in isShuffleMaskLegal, but they are
6648   // inlined here right now to enable us to directly emit target specific
6649   // nodes, and remove one by one until they don't return Op anymore.
6650
6651   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6652     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6653                                 getShufflePALIGNRImmediate(SVOp),
6654                                 DAG);
6655
6656   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6657       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6658     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6659       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6660   }
6661
6662   if (isPSHUFHWMask(M, VT))
6663     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6664                                 X86::getShufflePSHUFHWImmediate(SVOp),
6665                                 DAG);
6666
6667   if (isPSHUFLWMask(M, VT))
6668     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6669                                 X86::getShufflePSHUFLWImmediate(SVOp),
6670                                 DAG);
6671
6672   if (isSHUFPMask(M, VT))
6673     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6674                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6675
6676   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6677     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6678   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6679     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6680
6681   //===--------------------------------------------------------------------===//
6682   // Generate target specific nodes for 128 or 256-bit shuffles only
6683   // supported in the AVX instruction set.
6684   //
6685
6686   // Handle VMOVDDUPY permutations
6687   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6688     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6689
6690   // Handle VPERMILPS/D* permutations
6691   if (isVPERMILPMask(M, VT, HasAVX))
6692     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6693                                 getShuffleVPERMILPImmediate(SVOp), DAG);
6694
6695   // Handle VPERM2F128/VPERM2I128 permutations
6696   if (isVPERM2X128Mask(M, VT, HasAVX))
6697     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6698                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6699
6700   // Handle VSHUFPS/DY permutations
6701   if (isVSHUFPYMask(M, VT, HasAVX))
6702     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6703                                 getShuffleVSHUFPYImmediate(SVOp), DAG);
6704
6705   //===--------------------------------------------------------------------===//
6706   // Since no target specific shuffle was selected for this generic one,
6707   // lower it into other known shuffles. FIXME: this isn't true yet, but
6708   // this is the plan.
6709   //
6710
6711   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6712   if (VT == MVT::v8i16) {
6713     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6714     if (NewOp.getNode())
6715       return NewOp;
6716   }
6717
6718   if (VT == MVT::v16i8) {
6719     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6720     if (NewOp.getNode())
6721       return NewOp;
6722   }
6723
6724   // Handle all 128-bit wide vectors with 4 elements, and match them with
6725   // several different shuffle types.
6726   if (NumElems == 4 && VT.getSizeInBits() == 128)
6727     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6728
6729   // Handle general 256-bit shuffles
6730   if (VT.is256BitVector())
6731     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6732
6733   return SDValue();
6734 }
6735
6736 SDValue
6737 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6738                                                 SelectionDAG &DAG) const {
6739   EVT VT = Op.getValueType();
6740   DebugLoc dl = Op.getDebugLoc();
6741
6742   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6743     return SDValue();
6744
6745   if (VT.getSizeInBits() == 8) {
6746     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6747                                     Op.getOperand(0), Op.getOperand(1));
6748     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6749                                     DAG.getValueType(VT));
6750     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6751   } else if (VT.getSizeInBits() == 16) {
6752     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6753     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6754     if (Idx == 0)
6755       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6756                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6757                                      DAG.getNode(ISD::BITCAST, dl,
6758                                                  MVT::v4i32,
6759                                                  Op.getOperand(0)),
6760                                      Op.getOperand(1)));
6761     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6762                                     Op.getOperand(0), Op.getOperand(1));
6763     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6764                                     DAG.getValueType(VT));
6765     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6766   } else if (VT == MVT::f32) {
6767     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6768     // the result back to FR32 register. It's only worth matching if the
6769     // result has a single use which is a store or a bitcast to i32.  And in
6770     // the case of a store, it's not worth it if the index is a constant 0,
6771     // because a MOVSSmr can be used instead, which is smaller and faster.
6772     if (!Op.hasOneUse())
6773       return SDValue();
6774     SDNode *User = *Op.getNode()->use_begin();
6775     if ((User->getOpcode() != ISD::STORE ||
6776          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6777           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6778         (User->getOpcode() != ISD::BITCAST ||
6779          User->getValueType(0) != MVT::i32))
6780       return SDValue();
6781     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6782                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6783                                               Op.getOperand(0)),
6784                                               Op.getOperand(1));
6785     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6786   } else if (VT == MVT::i32 || VT == MVT::i64) {
6787     // ExtractPS/pextrq works with constant index.
6788     if (isa<ConstantSDNode>(Op.getOperand(1)))
6789       return Op;
6790   }
6791   return SDValue();
6792 }
6793
6794
6795 SDValue
6796 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6797                                            SelectionDAG &DAG) const {
6798   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6799     return SDValue();
6800
6801   SDValue Vec = Op.getOperand(0);
6802   EVT VecVT = Vec.getValueType();
6803
6804   // If this is a 256-bit vector result, first extract the 128-bit vector and
6805   // then extract the element from the 128-bit vector.
6806   if (VecVT.getSizeInBits() == 256) {
6807     DebugLoc dl = Op.getNode()->getDebugLoc();
6808     unsigned NumElems = VecVT.getVectorNumElements();
6809     SDValue Idx = Op.getOperand(1);
6810     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6811
6812     // Get the 128-bit vector.
6813     bool Upper = IdxVal >= NumElems/2;
6814     Vec = Extract128BitVector(Vec,
6815                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6816
6817     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6818                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6819   }
6820
6821   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6822
6823   if (Subtarget->hasSSE41orAVX()) {
6824     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6825     if (Res.getNode())
6826       return Res;
6827   }
6828
6829   EVT VT = Op.getValueType();
6830   DebugLoc dl = Op.getDebugLoc();
6831   // TODO: handle v16i8.
6832   if (VT.getSizeInBits() == 16) {
6833     SDValue Vec = Op.getOperand(0);
6834     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6835     if (Idx == 0)
6836       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6837                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6838                                      DAG.getNode(ISD::BITCAST, dl,
6839                                                  MVT::v4i32, Vec),
6840                                      Op.getOperand(1)));
6841     // Transform it so it match pextrw which produces a 32-bit result.
6842     EVT EltVT = MVT::i32;
6843     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6844                                     Op.getOperand(0), Op.getOperand(1));
6845     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6846                                     DAG.getValueType(VT));
6847     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6848   } else if (VT.getSizeInBits() == 32) {
6849     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6850     if (Idx == 0)
6851       return Op;
6852
6853     // SHUFPS the element to the lowest double word, then movss.
6854     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6855     EVT VVT = Op.getOperand(0).getValueType();
6856     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6857                                        DAG.getUNDEF(VVT), Mask);
6858     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6859                        DAG.getIntPtrConstant(0));
6860   } else if (VT.getSizeInBits() == 64) {
6861     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6862     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6863     //        to match extract_elt for f64.
6864     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6865     if (Idx == 0)
6866       return Op;
6867
6868     // UNPCKHPD the element to the lowest double word, then movsd.
6869     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6870     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6871     int Mask[2] = { 1, -1 };
6872     EVT VVT = Op.getOperand(0).getValueType();
6873     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6874                                        DAG.getUNDEF(VVT), Mask);
6875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6876                        DAG.getIntPtrConstant(0));
6877   }
6878
6879   return SDValue();
6880 }
6881
6882 SDValue
6883 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6884                                                SelectionDAG &DAG) const {
6885   EVT VT = Op.getValueType();
6886   EVT EltVT = VT.getVectorElementType();
6887   DebugLoc dl = Op.getDebugLoc();
6888
6889   SDValue N0 = Op.getOperand(0);
6890   SDValue N1 = Op.getOperand(1);
6891   SDValue N2 = Op.getOperand(2);
6892
6893   if (VT.getSizeInBits() == 256)
6894     return SDValue();
6895
6896   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6897       isa<ConstantSDNode>(N2)) {
6898     unsigned Opc;
6899     if (VT == MVT::v8i16)
6900       Opc = X86ISD::PINSRW;
6901     else if (VT == MVT::v16i8)
6902       Opc = X86ISD::PINSRB;
6903     else
6904       Opc = X86ISD::PINSRB;
6905
6906     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6907     // argument.
6908     if (N1.getValueType() != MVT::i32)
6909       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6910     if (N2.getValueType() != MVT::i32)
6911       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6912     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6913   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6914     // Bits [7:6] of the constant are the source select.  This will always be
6915     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6916     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6917     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6918     // Bits [5:4] of the constant are the destination select.  This is the
6919     //  value of the incoming immediate.
6920     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6921     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6922     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6923     // Create this as a scalar to vector..
6924     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6925     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6926   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6927              isa<ConstantSDNode>(N2)) {
6928     // PINSR* works with constant index.
6929     return Op;
6930   }
6931   return SDValue();
6932 }
6933
6934 SDValue
6935 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6936   EVT VT = Op.getValueType();
6937   EVT EltVT = VT.getVectorElementType();
6938
6939   DebugLoc dl = Op.getDebugLoc();
6940   SDValue N0 = Op.getOperand(0);
6941   SDValue N1 = Op.getOperand(1);
6942   SDValue N2 = Op.getOperand(2);
6943
6944   // If this is a 256-bit vector result, first extract the 128-bit vector,
6945   // insert the element into the extracted half and then place it back.
6946   if (VT.getSizeInBits() == 256) {
6947     if (!isa<ConstantSDNode>(N2))
6948       return SDValue();
6949
6950     // Get the desired 128-bit vector half.
6951     unsigned NumElems = VT.getVectorNumElements();
6952     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6953     bool Upper = IdxVal >= NumElems/2;
6954     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6955     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6956
6957     // Insert the element into the desired half.
6958     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6959                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6960
6961     // Insert the changed part back to the 256-bit vector
6962     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6963   }
6964
6965   if (Subtarget->hasSSE41orAVX())
6966     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6967
6968   if (EltVT == MVT::i8)
6969     return SDValue();
6970
6971   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6972     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6973     // as its second argument.
6974     if (N1.getValueType() != MVT::i32)
6975       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6976     if (N2.getValueType() != MVT::i32)
6977       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6978     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6979   }
6980   return SDValue();
6981 }
6982
6983 SDValue
6984 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6985   LLVMContext *Context = DAG.getContext();
6986   DebugLoc dl = Op.getDebugLoc();
6987   EVT OpVT = Op.getValueType();
6988
6989   // If this is a 256-bit vector result, first insert into a 128-bit
6990   // vector and then insert into the 256-bit vector.
6991   if (OpVT.getSizeInBits() > 128) {
6992     // Insert into a 128-bit vector.
6993     EVT VT128 = EVT::getVectorVT(*Context,
6994                                  OpVT.getVectorElementType(),
6995                                  OpVT.getVectorNumElements() / 2);
6996
6997     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6998
6999     // Insert the 128-bit vector.
7000     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7001                               DAG.getConstant(0, MVT::i32),
7002                               DAG, dl);
7003   }
7004
7005   if (Op.getValueType() == MVT::v1i64 &&
7006       Op.getOperand(0).getValueType() == MVT::i64)
7007     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7008
7009   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7010   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7011          "Expected an SSE type!");
7012   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7013                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7014 }
7015
7016 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7017 // a simple subregister reference or explicit instructions to grab
7018 // upper bits of a vector.
7019 SDValue
7020 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7021   if (Subtarget->hasAVX()) {
7022     DebugLoc dl = Op.getNode()->getDebugLoc();
7023     SDValue Vec = Op.getNode()->getOperand(0);
7024     SDValue Idx = Op.getNode()->getOperand(1);
7025
7026     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7027         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7028         return Extract128BitVector(Vec, Idx, DAG, dl);
7029     }
7030   }
7031   return SDValue();
7032 }
7033
7034 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7035 // simple superregister reference or explicit instructions to insert
7036 // the upper bits of a vector.
7037 SDValue
7038 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7039   if (Subtarget->hasAVX()) {
7040     DebugLoc dl = Op.getNode()->getDebugLoc();
7041     SDValue Vec = Op.getNode()->getOperand(0);
7042     SDValue SubVec = Op.getNode()->getOperand(1);
7043     SDValue Idx = Op.getNode()->getOperand(2);
7044
7045     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7046         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7047       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7048     }
7049   }
7050   return SDValue();
7051 }
7052
7053 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7054 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7055 // one of the above mentioned nodes. It has to be wrapped because otherwise
7056 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7057 // be used to form addressing mode. These wrapped nodes will be selected
7058 // into MOV32ri.
7059 SDValue
7060 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7061   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7062
7063   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7064   // global base reg.
7065   unsigned char OpFlag = 0;
7066   unsigned WrapperKind = X86ISD::Wrapper;
7067   CodeModel::Model M = getTargetMachine().getCodeModel();
7068
7069   if (Subtarget->isPICStyleRIPRel() &&
7070       (M == CodeModel::Small || M == CodeModel::Kernel))
7071     WrapperKind = X86ISD::WrapperRIP;
7072   else if (Subtarget->isPICStyleGOT())
7073     OpFlag = X86II::MO_GOTOFF;
7074   else if (Subtarget->isPICStyleStubPIC())
7075     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7076
7077   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7078                                              CP->getAlignment(),
7079                                              CP->getOffset(), OpFlag);
7080   DebugLoc DL = CP->getDebugLoc();
7081   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7082   // With PIC, the address is actually $g + Offset.
7083   if (OpFlag) {
7084     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7085                          DAG.getNode(X86ISD::GlobalBaseReg,
7086                                      DebugLoc(), getPointerTy()),
7087                          Result);
7088   }
7089
7090   return Result;
7091 }
7092
7093 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7094   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7095
7096   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7097   // global base reg.
7098   unsigned char OpFlag = 0;
7099   unsigned WrapperKind = X86ISD::Wrapper;
7100   CodeModel::Model M = getTargetMachine().getCodeModel();
7101
7102   if (Subtarget->isPICStyleRIPRel() &&
7103       (M == CodeModel::Small || M == CodeModel::Kernel))
7104     WrapperKind = X86ISD::WrapperRIP;
7105   else if (Subtarget->isPICStyleGOT())
7106     OpFlag = X86II::MO_GOTOFF;
7107   else if (Subtarget->isPICStyleStubPIC())
7108     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7109
7110   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7111                                           OpFlag);
7112   DebugLoc DL = JT->getDebugLoc();
7113   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7114
7115   // With PIC, the address is actually $g + Offset.
7116   if (OpFlag)
7117     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7118                          DAG.getNode(X86ISD::GlobalBaseReg,
7119                                      DebugLoc(), getPointerTy()),
7120                          Result);
7121
7122   return Result;
7123 }
7124
7125 SDValue
7126 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7127   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7128
7129   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7130   // global base reg.
7131   unsigned char OpFlag = 0;
7132   unsigned WrapperKind = X86ISD::Wrapper;
7133   CodeModel::Model M = getTargetMachine().getCodeModel();
7134
7135   if (Subtarget->isPICStyleRIPRel() &&
7136       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7137     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7138       OpFlag = X86II::MO_GOTPCREL;
7139     WrapperKind = X86ISD::WrapperRIP;
7140   } else if (Subtarget->isPICStyleGOT()) {
7141     OpFlag = X86II::MO_GOT;
7142   } else if (Subtarget->isPICStyleStubPIC()) {
7143     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7144   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7145     OpFlag = X86II::MO_DARWIN_NONLAZY;
7146   }
7147
7148   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7149
7150   DebugLoc DL = Op.getDebugLoc();
7151   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7152
7153
7154   // With PIC, the address is actually $g + Offset.
7155   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7156       !Subtarget->is64Bit()) {
7157     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7158                          DAG.getNode(X86ISD::GlobalBaseReg,
7159                                      DebugLoc(), getPointerTy()),
7160                          Result);
7161   }
7162
7163   // For symbols that require a load from a stub to get the address, emit the
7164   // load.
7165   if (isGlobalStubReference(OpFlag))
7166     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7167                          MachinePointerInfo::getGOT(), false, false, false, 0);
7168
7169   return Result;
7170 }
7171
7172 SDValue
7173 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7174   // Create the TargetBlockAddressAddress node.
7175   unsigned char OpFlags =
7176     Subtarget->ClassifyBlockAddressReference();
7177   CodeModel::Model M = getTargetMachine().getCodeModel();
7178   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7179   DebugLoc dl = Op.getDebugLoc();
7180   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7181                                        /*isTarget=*/true, OpFlags);
7182
7183   if (Subtarget->isPICStyleRIPRel() &&
7184       (M == CodeModel::Small || M == CodeModel::Kernel))
7185     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7186   else
7187     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7188
7189   // With PIC, the address is actually $g + Offset.
7190   if (isGlobalRelativeToPICBase(OpFlags)) {
7191     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7192                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7193                          Result);
7194   }
7195
7196   return Result;
7197 }
7198
7199 SDValue
7200 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7201                                       int64_t Offset,
7202                                       SelectionDAG &DAG) const {
7203   // Create the TargetGlobalAddress node, folding in the constant
7204   // offset if it is legal.
7205   unsigned char OpFlags =
7206     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7207   CodeModel::Model M = getTargetMachine().getCodeModel();
7208   SDValue Result;
7209   if (OpFlags == X86II::MO_NO_FLAG &&
7210       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7211     // A direct static reference to a global.
7212     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7213     Offset = 0;
7214   } else {
7215     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7216   }
7217
7218   if (Subtarget->isPICStyleRIPRel() &&
7219       (M == CodeModel::Small || M == CodeModel::Kernel))
7220     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7221   else
7222     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7223
7224   // With PIC, the address is actually $g + Offset.
7225   if (isGlobalRelativeToPICBase(OpFlags)) {
7226     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7227                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7228                          Result);
7229   }
7230
7231   // For globals that require a load from a stub to get the address, emit the
7232   // load.
7233   if (isGlobalStubReference(OpFlags))
7234     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7235                          MachinePointerInfo::getGOT(), false, false, false, 0);
7236
7237   // If there was a non-zero offset that we didn't fold, create an explicit
7238   // addition for it.
7239   if (Offset != 0)
7240     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7241                          DAG.getConstant(Offset, getPointerTy()));
7242
7243   return Result;
7244 }
7245
7246 SDValue
7247 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7248   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7249   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7250   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7251 }
7252
7253 static SDValue
7254 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7255            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7256            unsigned char OperandFlags) {
7257   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7258   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7259   DebugLoc dl = GA->getDebugLoc();
7260   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7261                                            GA->getValueType(0),
7262                                            GA->getOffset(),
7263                                            OperandFlags);
7264   if (InFlag) {
7265     SDValue Ops[] = { Chain,  TGA, *InFlag };
7266     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7267   } else {
7268     SDValue Ops[]  = { Chain, TGA };
7269     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7270   }
7271
7272   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7273   MFI->setAdjustsStack(true);
7274
7275   SDValue Flag = Chain.getValue(1);
7276   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7277 }
7278
7279 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7280 static SDValue
7281 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7282                                 const EVT PtrVT) {
7283   SDValue InFlag;
7284   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7285   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7286                                      DAG.getNode(X86ISD::GlobalBaseReg,
7287                                                  DebugLoc(), PtrVT), InFlag);
7288   InFlag = Chain.getValue(1);
7289
7290   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7291 }
7292
7293 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7294 static SDValue
7295 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7296                                 const EVT PtrVT) {
7297   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7298                     X86::RAX, X86II::MO_TLSGD);
7299 }
7300
7301 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7302 // "local exec" model.
7303 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7304                                    const EVT PtrVT, TLSModel::Model model,
7305                                    bool is64Bit) {
7306   DebugLoc dl = GA->getDebugLoc();
7307
7308   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7309   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7310                                                          is64Bit ? 257 : 256));
7311
7312   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7313                                       DAG.getIntPtrConstant(0),
7314                                       MachinePointerInfo(Ptr),
7315                                       false, false, false, 0);
7316
7317   unsigned char OperandFlags = 0;
7318   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7319   // initialexec.
7320   unsigned WrapperKind = X86ISD::Wrapper;
7321   if (model == TLSModel::LocalExec) {
7322     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7323   } else if (is64Bit) {
7324     assert(model == TLSModel::InitialExec);
7325     OperandFlags = X86II::MO_GOTTPOFF;
7326     WrapperKind = X86ISD::WrapperRIP;
7327   } else {
7328     assert(model == TLSModel::InitialExec);
7329     OperandFlags = X86II::MO_INDNTPOFF;
7330   }
7331
7332   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7333   // exec)
7334   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7335                                            GA->getValueType(0),
7336                                            GA->getOffset(), OperandFlags);
7337   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7338
7339   if (model == TLSModel::InitialExec)
7340     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7341                          MachinePointerInfo::getGOT(), false, false, false, 0);
7342
7343   // The address of the thread local variable is the add of the thread
7344   // pointer with the offset of the variable.
7345   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7346 }
7347
7348 SDValue
7349 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7350
7351   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7352   const GlobalValue *GV = GA->getGlobal();
7353
7354   if (Subtarget->isTargetELF()) {
7355     // TODO: implement the "local dynamic" model
7356     // TODO: implement the "initial exec"model for pic executables
7357
7358     // If GV is an alias then use the aliasee for determining
7359     // thread-localness.
7360     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7361       GV = GA->resolveAliasedGlobal(false);
7362
7363     TLSModel::Model model
7364       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7365
7366     switch (model) {
7367       case TLSModel::GeneralDynamic:
7368       case TLSModel::LocalDynamic: // not implemented
7369         if (Subtarget->is64Bit())
7370           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7371         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7372
7373       case TLSModel::InitialExec:
7374       case TLSModel::LocalExec:
7375         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7376                                    Subtarget->is64Bit());
7377     }
7378   } else if (Subtarget->isTargetDarwin()) {
7379     // Darwin only has one model of TLS.  Lower to that.
7380     unsigned char OpFlag = 0;
7381     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7382                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7383
7384     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7385     // global base reg.
7386     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7387                   !Subtarget->is64Bit();
7388     if (PIC32)
7389       OpFlag = X86II::MO_TLVP_PIC_BASE;
7390     else
7391       OpFlag = X86II::MO_TLVP;
7392     DebugLoc DL = Op.getDebugLoc();
7393     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7394                                                 GA->getValueType(0),
7395                                                 GA->getOffset(), OpFlag);
7396     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7397
7398     // With PIC32, the address is actually $g + Offset.
7399     if (PIC32)
7400       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7401                            DAG.getNode(X86ISD::GlobalBaseReg,
7402                                        DebugLoc(), getPointerTy()),
7403                            Offset);
7404
7405     // Lowering the machine isd will make sure everything is in the right
7406     // location.
7407     SDValue Chain = DAG.getEntryNode();
7408     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7409     SDValue Args[] = { Chain, Offset };
7410     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7411
7412     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7413     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7414     MFI->setAdjustsStack(true);
7415
7416     // And our return value (tls address) is in the standard call return value
7417     // location.
7418     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7419     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7420                               Chain.getValue(1));
7421   }
7422
7423   assert(false &&
7424          "TLS not implemented for this target.");
7425
7426   llvm_unreachable("Unreachable");
7427   return SDValue();
7428 }
7429
7430
7431 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7432 /// take a 2 x i32 value to shift plus a shift amount.
7433 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7434   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7435   EVT VT = Op.getValueType();
7436   unsigned VTBits = VT.getSizeInBits();
7437   DebugLoc dl = Op.getDebugLoc();
7438   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7439   SDValue ShOpLo = Op.getOperand(0);
7440   SDValue ShOpHi = Op.getOperand(1);
7441   SDValue ShAmt  = Op.getOperand(2);
7442   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7443                                      DAG.getConstant(VTBits - 1, MVT::i8))
7444                        : DAG.getConstant(0, VT);
7445
7446   SDValue Tmp2, Tmp3;
7447   if (Op.getOpcode() == ISD::SHL_PARTS) {
7448     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7449     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7450   } else {
7451     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7452     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7453   }
7454
7455   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7456                                 DAG.getConstant(VTBits, MVT::i8));
7457   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7458                              AndNode, DAG.getConstant(0, MVT::i8));
7459
7460   SDValue Hi, Lo;
7461   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7462   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7463   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7464
7465   if (Op.getOpcode() == ISD::SHL_PARTS) {
7466     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7467     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7468   } else {
7469     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7470     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7471   }
7472
7473   SDValue Ops[2] = { Lo, Hi };
7474   return DAG.getMergeValues(Ops, 2, dl);
7475 }
7476
7477 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7478                                            SelectionDAG &DAG) const {
7479   EVT SrcVT = Op.getOperand(0).getValueType();
7480
7481   if (SrcVT.isVector())
7482     return SDValue();
7483
7484   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7485          "Unknown SINT_TO_FP to lower!");
7486
7487   // These are really Legal; return the operand so the caller accepts it as
7488   // Legal.
7489   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7490     return Op;
7491   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7492       Subtarget->is64Bit()) {
7493     return Op;
7494   }
7495
7496   DebugLoc dl = Op.getDebugLoc();
7497   unsigned Size = SrcVT.getSizeInBits()/8;
7498   MachineFunction &MF = DAG.getMachineFunction();
7499   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7500   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7501   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7502                                StackSlot,
7503                                MachinePointerInfo::getFixedStack(SSFI),
7504                                false, false, 0);
7505   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7506 }
7507
7508 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7509                                      SDValue StackSlot,
7510                                      SelectionDAG &DAG) const {
7511   // Build the FILD
7512   DebugLoc DL = Op.getDebugLoc();
7513   SDVTList Tys;
7514   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7515   if (useSSE)
7516     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7517   else
7518     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7519
7520   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7521
7522   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7523   MachineMemOperand *MMO;
7524   if (FI) {
7525     int SSFI = FI->getIndex();
7526     MMO =
7527       DAG.getMachineFunction()
7528       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7529                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7530   } else {
7531     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7532     StackSlot = StackSlot.getOperand(1);
7533   }
7534   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7535   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7536                                            X86ISD::FILD, DL,
7537                                            Tys, Ops, array_lengthof(Ops),
7538                                            SrcVT, MMO);
7539
7540   if (useSSE) {
7541     Chain = Result.getValue(1);
7542     SDValue InFlag = Result.getValue(2);
7543
7544     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7545     // shouldn't be necessary except that RFP cannot be live across
7546     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7547     MachineFunction &MF = DAG.getMachineFunction();
7548     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7549     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7550     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7551     Tys = DAG.getVTList(MVT::Other);
7552     SDValue Ops[] = {
7553       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7554     };
7555     MachineMemOperand *MMO =
7556       DAG.getMachineFunction()
7557       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7558                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7559
7560     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7561                                     Ops, array_lengthof(Ops),
7562                                     Op.getValueType(), MMO);
7563     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7564                          MachinePointerInfo::getFixedStack(SSFI),
7565                          false, false, false, 0);
7566   }
7567
7568   return Result;
7569 }
7570
7571 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7572 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7573                                                SelectionDAG &DAG) const {
7574   // This algorithm is not obvious. Here it is in C code, more or less:
7575   /*
7576     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7577       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7578       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7579
7580       // Copy ints to xmm registers.
7581       __m128i xh = _mm_cvtsi32_si128( hi );
7582       __m128i xl = _mm_cvtsi32_si128( lo );
7583
7584       // Combine into low half of a single xmm register.
7585       __m128i x = _mm_unpacklo_epi32( xh, xl );
7586       __m128d d;
7587       double sd;
7588
7589       // Merge in appropriate exponents to give the integer bits the right
7590       // magnitude.
7591       x = _mm_unpacklo_epi32( x, exp );
7592
7593       // Subtract away the biases to deal with the IEEE-754 double precision
7594       // implicit 1.
7595       d = _mm_sub_pd( (__m128d) x, bias );
7596
7597       // All conversions up to here are exact. The correctly rounded result is
7598       // calculated using the current rounding mode using the following
7599       // horizontal add.
7600       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7601       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7602                                 // store doesn't really need to be here (except
7603                                 // maybe to zero the other double)
7604       return sd;
7605     }
7606   */
7607
7608   DebugLoc dl = Op.getDebugLoc();
7609   LLVMContext *Context = DAG.getContext();
7610
7611   // Build some magic constants.
7612   SmallVector<Constant*,4> CV0;
7613   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7614   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7615   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7616   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7617   Constant *C0 = ConstantVector::get(CV0);
7618   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7619
7620   SmallVector<Constant*,2> CV1;
7621   CV1.push_back(
7622     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7623   CV1.push_back(
7624     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7625   Constant *C1 = ConstantVector::get(CV1);
7626   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7627
7628   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7629                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7630                                         Op.getOperand(0),
7631                                         DAG.getIntPtrConstant(1)));
7632   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7633                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7634                                         Op.getOperand(0),
7635                                         DAG.getIntPtrConstant(0)));
7636   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7637   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7638                               MachinePointerInfo::getConstantPool(),
7639                               false, false, false, 16);
7640   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7641   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7642   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7643                               MachinePointerInfo::getConstantPool(),
7644                               false, false, false, 16);
7645   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7646
7647   // Add the halves; easiest way is to swap them into another reg first.
7648   int ShufMask[2] = { 1, -1 };
7649   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7650                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7651   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7652   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7653                      DAG.getIntPtrConstant(0));
7654 }
7655
7656 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7657 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7658                                                SelectionDAG &DAG) const {
7659   DebugLoc dl = Op.getDebugLoc();
7660   // FP constant to bias correct the final result.
7661   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7662                                    MVT::f64);
7663
7664   // Load the 32-bit value into an XMM register.
7665   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7666                              Op.getOperand(0));
7667
7668   // Zero out the upper parts of the register.
7669   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7670                                      DAG);
7671
7672   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7673                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7674                      DAG.getIntPtrConstant(0));
7675
7676   // Or the load with the bias.
7677   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7678                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7679                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7680                                                    MVT::v2f64, Load)),
7681                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7682                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7683                                                    MVT::v2f64, Bias)));
7684   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7685                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7686                    DAG.getIntPtrConstant(0));
7687
7688   // Subtract the bias.
7689   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7690
7691   // Handle final rounding.
7692   EVT DestVT = Op.getValueType();
7693
7694   if (DestVT.bitsLT(MVT::f64)) {
7695     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7696                        DAG.getIntPtrConstant(0));
7697   } else if (DestVT.bitsGT(MVT::f64)) {
7698     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7699   }
7700
7701   // Handle final rounding.
7702   return Sub;
7703 }
7704
7705 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7706                                            SelectionDAG &DAG) const {
7707   SDValue N0 = Op.getOperand(0);
7708   DebugLoc dl = Op.getDebugLoc();
7709
7710   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7711   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7712   // the optimization here.
7713   if (DAG.SignBitIsZero(N0))
7714     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7715
7716   EVT SrcVT = N0.getValueType();
7717   EVT DstVT = Op.getValueType();
7718   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7719     return LowerUINT_TO_FP_i64(Op, DAG);
7720   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7721     return LowerUINT_TO_FP_i32(Op, DAG);
7722
7723   // Make a 64-bit buffer, and use it to build an FILD.
7724   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7725   if (SrcVT == MVT::i32) {
7726     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7727     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7728                                      getPointerTy(), StackSlot, WordOff);
7729     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7730                                   StackSlot, MachinePointerInfo(),
7731                                   false, false, 0);
7732     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7733                                   OffsetSlot, MachinePointerInfo(),
7734                                   false, false, 0);
7735     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7736     return Fild;
7737   }
7738
7739   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7740   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7741                                 StackSlot, MachinePointerInfo(),
7742                                false, false, 0);
7743   // For i64 source, we need to add the appropriate power of 2 if the input
7744   // was negative.  This is the same as the optimization in
7745   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7746   // we must be careful to do the computation in x87 extended precision, not
7747   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7748   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7749   MachineMemOperand *MMO =
7750     DAG.getMachineFunction()
7751     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7752                           MachineMemOperand::MOLoad, 8, 8);
7753
7754   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7755   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7756   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7757                                          MVT::i64, MMO);
7758
7759   APInt FF(32, 0x5F800000ULL);
7760
7761   // Check whether the sign bit is set.
7762   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7763                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7764                                  ISD::SETLT);
7765
7766   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7767   SDValue FudgePtr = DAG.getConstantPool(
7768                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7769                                          getPointerTy());
7770
7771   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7772   SDValue Zero = DAG.getIntPtrConstant(0);
7773   SDValue Four = DAG.getIntPtrConstant(4);
7774   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7775                                Zero, Four);
7776   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7777
7778   // Load the value out, extending it from f32 to f80.
7779   // FIXME: Avoid the extend by constructing the right constant pool?
7780   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7781                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7782                                  MVT::f32, false, false, 4);
7783   // Extend everything to 80 bits to force it to be done on x87.
7784   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7785   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7786 }
7787
7788 std::pair<SDValue,SDValue> X86TargetLowering::
7789 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7790   DebugLoc DL = Op.getDebugLoc();
7791
7792   EVT DstTy = Op.getValueType();
7793
7794   if (!IsSigned) {
7795     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7796     DstTy = MVT::i64;
7797   }
7798
7799   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7800          DstTy.getSimpleVT() >= MVT::i16 &&
7801          "Unknown FP_TO_SINT to lower!");
7802
7803   // These are really Legal.
7804   if (DstTy == MVT::i32 &&
7805       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7806     return std::make_pair(SDValue(), SDValue());
7807   if (Subtarget->is64Bit() &&
7808       DstTy == MVT::i64 &&
7809       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7810     return std::make_pair(SDValue(), SDValue());
7811
7812   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7813   // stack slot.
7814   MachineFunction &MF = DAG.getMachineFunction();
7815   unsigned MemSize = DstTy.getSizeInBits()/8;
7816   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7817   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7818
7819
7820
7821   unsigned Opc;
7822   switch (DstTy.getSimpleVT().SimpleTy) {
7823   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7824   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7825   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7826   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7827   }
7828
7829   SDValue Chain = DAG.getEntryNode();
7830   SDValue Value = Op.getOperand(0);
7831   EVT TheVT = Op.getOperand(0).getValueType();
7832   if (isScalarFPTypeInSSEReg(TheVT)) {
7833     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7834     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7835                          MachinePointerInfo::getFixedStack(SSFI),
7836                          false, false, 0);
7837     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7838     SDValue Ops[] = {
7839       Chain, StackSlot, DAG.getValueType(TheVT)
7840     };
7841
7842     MachineMemOperand *MMO =
7843       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7844                               MachineMemOperand::MOLoad, MemSize, MemSize);
7845     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7846                                     DstTy, MMO);
7847     Chain = Value.getValue(1);
7848     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7849     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7850   }
7851
7852   MachineMemOperand *MMO =
7853     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7854                             MachineMemOperand::MOStore, MemSize, MemSize);
7855
7856   // Build the FP_TO_INT*_IN_MEM
7857   SDValue Ops[] = { Chain, Value, StackSlot };
7858   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7859                                          Ops, 3, DstTy, MMO);
7860
7861   return std::make_pair(FIST, StackSlot);
7862 }
7863
7864 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7865                                            SelectionDAG &DAG) const {
7866   if (Op.getValueType().isVector())
7867     return SDValue();
7868
7869   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7870   SDValue FIST = Vals.first, StackSlot = Vals.second;
7871   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7872   if (FIST.getNode() == 0) return Op;
7873
7874   // Load the result.
7875   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7876                      FIST, StackSlot, MachinePointerInfo(),
7877                      false, false, false, 0);
7878 }
7879
7880 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7881                                            SelectionDAG &DAG) const {
7882   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7883   SDValue FIST = Vals.first, StackSlot = Vals.second;
7884   assert(FIST.getNode() && "Unexpected failure");
7885
7886   // Load the result.
7887   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7888                      FIST, StackSlot, MachinePointerInfo(),
7889                      false, false, false, 0);
7890 }
7891
7892 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7893                                      SelectionDAG &DAG) const {
7894   LLVMContext *Context = DAG.getContext();
7895   DebugLoc dl = Op.getDebugLoc();
7896   EVT VT = Op.getValueType();
7897   EVT EltVT = VT;
7898   if (VT.isVector())
7899     EltVT = VT.getVectorElementType();
7900   SmallVector<Constant*,4> CV;
7901   if (EltVT == MVT::f64) {
7902     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7903     CV.assign(2, C);
7904   } else {
7905     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7906     CV.assign(4, C);
7907   }
7908   Constant *C = ConstantVector::get(CV);
7909   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7910   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7911                              MachinePointerInfo::getConstantPool(),
7912                              false, false, false, 16);
7913   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7914 }
7915
7916 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7917   LLVMContext *Context = DAG.getContext();
7918   DebugLoc dl = Op.getDebugLoc();
7919   EVT VT = Op.getValueType();
7920   EVT EltVT = VT;
7921   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7922   if (VT.isVector()) {
7923     EltVT = VT.getVectorElementType();
7924     NumElts = VT.getVectorNumElements();
7925   }
7926   SmallVector<Constant*,8> CV;
7927   if (EltVT == MVT::f64) {
7928     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7929     CV.assign(NumElts, C);
7930   } else {
7931     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7932     CV.assign(NumElts, C);
7933   }
7934   Constant *C = ConstantVector::get(CV);
7935   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7936   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7937                              MachinePointerInfo::getConstantPool(),
7938                              false, false, false, 16);
7939   if (VT.isVector()) {
7940     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7941     return DAG.getNode(ISD::BITCAST, dl, VT,
7942                        DAG.getNode(ISD::XOR, dl, XORVT,
7943                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7944                                 Op.getOperand(0)),
7945                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7946   } else {
7947     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7948   }
7949 }
7950
7951 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7952   LLVMContext *Context = DAG.getContext();
7953   SDValue Op0 = Op.getOperand(0);
7954   SDValue Op1 = Op.getOperand(1);
7955   DebugLoc dl = Op.getDebugLoc();
7956   EVT VT = Op.getValueType();
7957   EVT SrcVT = Op1.getValueType();
7958
7959   // If second operand is smaller, extend it first.
7960   if (SrcVT.bitsLT(VT)) {
7961     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7962     SrcVT = VT;
7963   }
7964   // And if it is bigger, shrink it first.
7965   if (SrcVT.bitsGT(VT)) {
7966     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7967     SrcVT = VT;
7968   }
7969
7970   // At this point the operands and the result should have the same
7971   // type, and that won't be f80 since that is not custom lowered.
7972
7973   // First get the sign bit of second operand.
7974   SmallVector<Constant*,4> CV;
7975   if (SrcVT == MVT::f64) {
7976     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7977     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7978   } else {
7979     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7980     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7981     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7982     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7983   }
7984   Constant *C = ConstantVector::get(CV);
7985   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7986   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7987                               MachinePointerInfo::getConstantPool(),
7988                               false, false, false, 16);
7989   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7990
7991   // Shift sign bit right or left if the two operands have different types.
7992   if (SrcVT.bitsGT(VT)) {
7993     // Op0 is MVT::f32, Op1 is MVT::f64.
7994     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7995     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7996                           DAG.getConstant(32, MVT::i32));
7997     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7998     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7999                           DAG.getIntPtrConstant(0));
8000   }
8001
8002   // Clear first operand sign bit.
8003   CV.clear();
8004   if (VT == MVT::f64) {
8005     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8006     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8007   } else {
8008     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8009     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8010     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8011     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8012   }
8013   C = ConstantVector::get(CV);
8014   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8015   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8016                               MachinePointerInfo::getConstantPool(),
8017                               false, false, false, 16);
8018   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8019
8020   // Or the value with the sign bit.
8021   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8022 }
8023
8024 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8025   SDValue N0 = Op.getOperand(0);
8026   DebugLoc dl = Op.getDebugLoc();
8027   EVT VT = Op.getValueType();
8028
8029   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8030   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8031                                   DAG.getConstant(1, VT));
8032   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8033 }
8034
8035 /// Emit nodes that will be selected as "test Op0,Op0", or something
8036 /// equivalent.
8037 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8038                                     SelectionDAG &DAG) const {
8039   DebugLoc dl = Op.getDebugLoc();
8040
8041   // CF and OF aren't always set the way we want. Determine which
8042   // of these we need.
8043   bool NeedCF = false;
8044   bool NeedOF = false;
8045   switch (X86CC) {
8046   default: break;
8047   case X86::COND_A: case X86::COND_AE:
8048   case X86::COND_B: case X86::COND_BE:
8049     NeedCF = true;
8050     break;
8051   case X86::COND_G: case X86::COND_GE:
8052   case X86::COND_L: case X86::COND_LE:
8053   case X86::COND_O: case X86::COND_NO:
8054     NeedOF = true;
8055     break;
8056   }
8057
8058   // See if we can use the EFLAGS value from the operand instead of
8059   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8060   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8061   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8062     // Emit a CMP with 0, which is the TEST pattern.
8063     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8064                        DAG.getConstant(0, Op.getValueType()));
8065
8066   unsigned Opcode = 0;
8067   unsigned NumOperands = 0;
8068   switch (Op.getNode()->getOpcode()) {
8069   case ISD::ADD:
8070     // Due to an isel shortcoming, be conservative if this add is likely to be
8071     // selected as part of a load-modify-store instruction. When the root node
8072     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8073     // uses of other nodes in the match, such as the ADD in this case. This
8074     // leads to the ADD being left around and reselected, with the result being
8075     // two adds in the output.  Alas, even if none our users are stores, that
8076     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8077     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8078     // climbing the DAG back to the root, and it doesn't seem to be worth the
8079     // effort.
8080     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8081          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8082       if (UI->getOpcode() != ISD::CopyToReg &&
8083           UI->getOpcode() != ISD::SETCC &&
8084           UI->getOpcode() != ISD::STORE)
8085         goto default_case;
8086
8087     if (ConstantSDNode *C =
8088         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8089       // An add of one will be selected as an INC.
8090       if (C->getAPIntValue() == 1) {
8091         Opcode = X86ISD::INC;
8092         NumOperands = 1;
8093         break;
8094       }
8095
8096       // An add of negative one (subtract of one) will be selected as a DEC.
8097       if (C->getAPIntValue().isAllOnesValue()) {
8098         Opcode = X86ISD::DEC;
8099         NumOperands = 1;
8100         break;
8101       }
8102     }
8103
8104     // Otherwise use a regular EFLAGS-setting add.
8105     Opcode = X86ISD::ADD;
8106     NumOperands = 2;
8107     break;
8108   case ISD::AND: {
8109     // If the primary and result isn't used, don't bother using X86ISD::AND,
8110     // because a TEST instruction will be better.
8111     bool NonFlagUse = false;
8112     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8113            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8114       SDNode *User = *UI;
8115       unsigned UOpNo = UI.getOperandNo();
8116       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8117         // Look pass truncate.
8118         UOpNo = User->use_begin().getOperandNo();
8119         User = *User->use_begin();
8120       }
8121
8122       if (User->getOpcode() != ISD::BRCOND &&
8123           User->getOpcode() != ISD::SETCC &&
8124           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8125         NonFlagUse = true;
8126         break;
8127       }
8128     }
8129
8130     if (!NonFlagUse)
8131       break;
8132   }
8133     // FALL THROUGH
8134   case ISD::SUB:
8135   case ISD::OR:
8136   case ISD::XOR:
8137     // Due to the ISEL shortcoming noted above, be conservative if this op is
8138     // likely to be selected as part of a load-modify-store instruction.
8139     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8140            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8141       if (UI->getOpcode() == ISD::STORE)
8142         goto default_case;
8143
8144     // Otherwise use a regular EFLAGS-setting instruction.
8145     switch (Op.getNode()->getOpcode()) {
8146     default: llvm_unreachable("unexpected operator!");
8147     case ISD::SUB: Opcode = X86ISD::SUB; break;
8148     case ISD::OR:  Opcode = X86ISD::OR;  break;
8149     case ISD::XOR: Opcode = X86ISD::XOR; break;
8150     case ISD::AND: Opcode = X86ISD::AND; break;
8151     }
8152
8153     NumOperands = 2;
8154     break;
8155   case X86ISD::ADD:
8156   case X86ISD::SUB:
8157   case X86ISD::INC:
8158   case X86ISD::DEC:
8159   case X86ISD::OR:
8160   case X86ISD::XOR:
8161   case X86ISD::AND:
8162     return SDValue(Op.getNode(), 1);
8163   default:
8164   default_case:
8165     break;
8166   }
8167
8168   if (Opcode == 0)
8169     // Emit a CMP with 0, which is the TEST pattern.
8170     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8171                        DAG.getConstant(0, Op.getValueType()));
8172
8173   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8174   SmallVector<SDValue, 4> Ops;
8175   for (unsigned i = 0; i != NumOperands; ++i)
8176     Ops.push_back(Op.getOperand(i));
8177
8178   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8179   DAG.ReplaceAllUsesWith(Op, New);
8180   return SDValue(New.getNode(), 1);
8181 }
8182
8183 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8184 /// equivalent.
8185 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8186                                    SelectionDAG &DAG) const {
8187   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8188     if (C->getAPIntValue() == 0)
8189       return EmitTest(Op0, X86CC, DAG);
8190
8191   DebugLoc dl = Op0.getDebugLoc();
8192   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8193 }
8194
8195 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8196 /// if it's possible.
8197 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8198                                      DebugLoc dl, SelectionDAG &DAG) const {
8199   SDValue Op0 = And.getOperand(0);
8200   SDValue Op1 = And.getOperand(1);
8201   if (Op0.getOpcode() == ISD::TRUNCATE)
8202     Op0 = Op0.getOperand(0);
8203   if (Op1.getOpcode() == ISD::TRUNCATE)
8204     Op1 = Op1.getOperand(0);
8205
8206   SDValue LHS, RHS;
8207   if (Op1.getOpcode() == ISD::SHL)
8208     std::swap(Op0, Op1);
8209   if (Op0.getOpcode() == ISD::SHL) {
8210     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8211       if (And00C->getZExtValue() == 1) {
8212         // If we looked past a truncate, check that it's only truncating away
8213         // known zeros.
8214         unsigned BitWidth = Op0.getValueSizeInBits();
8215         unsigned AndBitWidth = And.getValueSizeInBits();
8216         if (BitWidth > AndBitWidth) {
8217           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8218           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8219           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8220             return SDValue();
8221         }
8222         LHS = Op1;
8223         RHS = Op0.getOperand(1);
8224       }
8225   } else if (Op1.getOpcode() == ISD::Constant) {
8226     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8227     uint64_t AndRHSVal = AndRHS->getZExtValue();
8228     SDValue AndLHS = Op0;
8229
8230     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8231       LHS = AndLHS.getOperand(0);
8232       RHS = AndLHS.getOperand(1);
8233     }
8234
8235     // Use BT if the immediate can't be encoded in a TEST instruction.
8236     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8237       LHS = AndLHS;
8238       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8239     }
8240   }
8241
8242   if (LHS.getNode()) {
8243     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8244     // instruction.  Since the shift amount is in-range-or-undefined, we know
8245     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8246     // the encoding for the i16 version is larger than the i32 version.
8247     // Also promote i16 to i32 for performance / code size reason.
8248     if (LHS.getValueType() == MVT::i8 ||
8249         LHS.getValueType() == MVT::i16)
8250       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8251
8252     // If the operand types disagree, extend the shift amount to match.  Since
8253     // BT ignores high bits (like shifts) we can use anyextend.
8254     if (LHS.getValueType() != RHS.getValueType())
8255       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8256
8257     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8258     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8259     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8260                        DAG.getConstant(Cond, MVT::i8), BT);
8261   }
8262
8263   return SDValue();
8264 }
8265
8266 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8267
8268   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8269
8270   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8271   SDValue Op0 = Op.getOperand(0);
8272   SDValue Op1 = Op.getOperand(1);
8273   DebugLoc dl = Op.getDebugLoc();
8274   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8275
8276   // Optimize to BT if possible.
8277   // Lower (X & (1 << N)) == 0 to BT(X, N).
8278   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8279   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8280   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8281       Op1.getOpcode() == ISD::Constant &&
8282       cast<ConstantSDNode>(Op1)->isNullValue() &&
8283       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8284     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8285     if (NewSetCC.getNode())
8286       return NewSetCC;
8287   }
8288
8289   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8290   // these.
8291   if (Op1.getOpcode() == ISD::Constant &&
8292       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8293        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8294       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8295
8296     // If the input is a setcc, then reuse the input setcc or use a new one with
8297     // the inverted condition.
8298     if (Op0.getOpcode() == X86ISD::SETCC) {
8299       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8300       bool Invert = (CC == ISD::SETNE) ^
8301         cast<ConstantSDNode>(Op1)->isNullValue();
8302       if (!Invert) return Op0;
8303
8304       CCode = X86::GetOppositeBranchCondition(CCode);
8305       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8306                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8307     }
8308   }
8309
8310   bool isFP = Op1.getValueType().isFloatingPoint();
8311   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8312   if (X86CC == X86::COND_INVALID)
8313     return SDValue();
8314
8315   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8316   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8317                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8318 }
8319
8320 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8321 // ones, and then concatenate the result back.
8322 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8323   EVT VT = Op.getValueType();
8324
8325   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8326          "Unsupported value type for operation");
8327
8328   int NumElems = VT.getVectorNumElements();
8329   DebugLoc dl = Op.getDebugLoc();
8330   SDValue CC = Op.getOperand(2);
8331   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8332   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8333
8334   // Extract the LHS vectors
8335   SDValue LHS = Op.getOperand(0);
8336   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8337   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8338
8339   // Extract the RHS vectors
8340   SDValue RHS = Op.getOperand(1);
8341   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8342   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8343
8344   // Issue the operation on the smaller types and concatenate the result back
8345   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8346   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8347   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8348                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8349                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8350 }
8351
8352
8353 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8354   SDValue Cond;
8355   SDValue Op0 = Op.getOperand(0);
8356   SDValue Op1 = Op.getOperand(1);
8357   SDValue CC = Op.getOperand(2);
8358   EVT VT = Op.getValueType();
8359   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8360   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8361   DebugLoc dl = Op.getDebugLoc();
8362
8363   if (isFP) {
8364     unsigned SSECC = 8;
8365     EVT EltVT = Op0.getValueType().getVectorElementType();
8366     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8367
8368     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8369     bool Swap = false;
8370
8371     // SSE Condition code mapping:
8372     //  0 - EQ
8373     //  1 - LT
8374     //  2 - LE
8375     //  3 - UNORD
8376     //  4 - NEQ
8377     //  5 - NLT
8378     //  6 - NLE
8379     //  7 - ORD
8380     switch (SetCCOpcode) {
8381     default: break;
8382     case ISD::SETOEQ:
8383     case ISD::SETEQ:  SSECC = 0; break;
8384     case ISD::SETOGT:
8385     case ISD::SETGT: Swap = true; // Fallthrough
8386     case ISD::SETLT:
8387     case ISD::SETOLT: SSECC = 1; break;
8388     case ISD::SETOGE:
8389     case ISD::SETGE: Swap = true; // Fallthrough
8390     case ISD::SETLE:
8391     case ISD::SETOLE: SSECC = 2; break;
8392     case ISD::SETUO:  SSECC = 3; break;
8393     case ISD::SETUNE:
8394     case ISD::SETNE:  SSECC = 4; break;
8395     case ISD::SETULE: Swap = true;
8396     case ISD::SETUGE: SSECC = 5; break;
8397     case ISD::SETULT: Swap = true;
8398     case ISD::SETUGT: SSECC = 6; break;
8399     case ISD::SETO:   SSECC = 7; break;
8400     }
8401     if (Swap)
8402       std::swap(Op0, Op1);
8403
8404     // In the two special cases we can't handle, emit two comparisons.
8405     if (SSECC == 8) {
8406       if (SetCCOpcode == ISD::SETUEQ) {
8407         SDValue UNORD, EQ;
8408         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8409         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8410         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8411       } else if (SetCCOpcode == ISD::SETONE) {
8412         SDValue ORD, NEQ;
8413         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8414         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8415         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8416       }
8417       llvm_unreachable("Illegal FP comparison");
8418     }
8419     // Handle all other FP comparisons here.
8420     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8421   }
8422
8423   // Break 256-bit integer vector compare into smaller ones.
8424   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8425     return Lower256IntVSETCC(Op, DAG);
8426
8427   // We are handling one of the integer comparisons here.  Since SSE only has
8428   // GT and EQ comparisons for integer, swapping operands and multiple
8429   // operations may be required for some comparisons.
8430   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8431   bool Swap = false, Invert = false, FlipSigns = false;
8432
8433   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8434   default: break;
8435   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8436   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8437   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8438   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8439   }
8440
8441   switch (SetCCOpcode) {
8442   default: break;
8443   case ISD::SETNE:  Invert = true;
8444   case ISD::SETEQ:  Opc = EQOpc; break;
8445   case ISD::SETLT:  Swap = true;
8446   case ISD::SETGT:  Opc = GTOpc; break;
8447   case ISD::SETGE:  Swap = true;
8448   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8449   case ISD::SETULT: Swap = true;
8450   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8451   case ISD::SETUGE: Swap = true;
8452   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8453   }
8454   if (Swap)
8455     std::swap(Op0, Op1);
8456
8457   // Check that the operation in question is available (most are plain SSE2,
8458   // but PCMPGTQ and PCMPEQQ have different requirements).
8459   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8460     return SDValue();
8461   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8462     return SDValue();
8463
8464   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8465   // bits of the inputs before performing those operations.
8466   if (FlipSigns) {
8467     EVT EltVT = VT.getVectorElementType();
8468     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8469                                       EltVT);
8470     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8471     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8472                                     SignBits.size());
8473     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8474     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8475   }
8476
8477   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8478
8479   // If the logical-not of the result is required, perform that now.
8480   if (Invert)
8481     Result = DAG.getNOT(dl, Result, VT);
8482
8483   return Result;
8484 }
8485
8486 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8487 static bool isX86LogicalCmp(SDValue Op) {
8488   unsigned Opc = Op.getNode()->getOpcode();
8489   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8490     return true;
8491   if (Op.getResNo() == 1 &&
8492       (Opc == X86ISD::ADD ||
8493        Opc == X86ISD::SUB ||
8494        Opc == X86ISD::ADC ||
8495        Opc == X86ISD::SBB ||
8496        Opc == X86ISD::SMUL ||
8497        Opc == X86ISD::UMUL ||
8498        Opc == X86ISD::INC ||
8499        Opc == X86ISD::DEC ||
8500        Opc == X86ISD::OR ||
8501        Opc == X86ISD::XOR ||
8502        Opc == X86ISD::AND))
8503     return true;
8504
8505   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8506     return true;
8507
8508   return false;
8509 }
8510
8511 static bool isZero(SDValue V) {
8512   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8513   return C && C->isNullValue();
8514 }
8515
8516 static bool isAllOnes(SDValue V) {
8517   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8518   return C && C->isAllOnesValue();
8519 }
8520
8521 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8522   bool addTest = true;
8523   SDValue Cond  = Op.getOperand(0);
8524   SDValue Op1 = Op.getOperand(1);
8525   SDValue Op2 = Op.getOperand(2);
8526   DebugLoc DL = Op.getDebugLoc();
8527   SDValue CC;
8528
8529   if (Cond.getOpcode() == ISD::SETCC) {
8530     SDValue NewCond = LowerSETCC(Cond, DAG);
8531     if (NewCond.getNode())
8532       Cond = NewCond;
8533   }
8534
8535   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8536   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8537   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8538   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8539   if (Cond.getOpcode() == X86ISD::SETCC &&
8540       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8541       isZero(Cond.getOperand(1).getOperand(1))) {
8542     SDValue Cmp = Cond.getOperand(1);
8543
8544     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8545
8546     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8547         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8548       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8549
8550       SDValue CmpOp0 = Cmp.getOperand(0);
8551       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8552                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8553
8554       SDValue Res =   // Res = 0 or -1.
8555         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8556                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8557
8558       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8559         Res = DAG.getNOT(DL, Res, Res.getValueType());
8560
8561       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8562       if (N2C == 0 || !N2C->isNullValue())
8563         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8564       return Res;
8565     }
8566   }
8567
8568   // Look past (and (setcc_carry (cmp ...)), 1).
8569   if (Cond.getOpcode() == ISD::AND &&
8570       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8571     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8572     if (C && C->getAPIntValue() == 1)
8573       Cond = Cond.getOperand(0);
8574   }
8575
8576   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8577   // setting operand in place of the X86ISD::SETCC.
8578   unsigned CondOpcode = Cond.getOpcode();
8579   if (CondOpcode == X86ISD::SETCC ||
8580       CondOpcode == X86ISD::SETCC_CARRY) {
8581     CC = Cond.getOperand(0);
8582
8583     SDValue Cmp = Cond.getOperand(1);
8584     unsigned Opc = Cmp.getOpcode();
8585     EVT VT = Op.getValueType();
8586
8587     bool IllegalFPCMov = false;
8588     if (VT.isFloatingPoint() && !VT.isVector() &&
8589         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8590       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8591
8592     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8593         Opc == X86ISD::BT) { // FIXME
8594       Cond = Cmp;
8595       addTest = false;
8596     }
8597   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8598              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8599              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8600               Cond.getOperand(0).getValueType() != MVT::i8)) {
8601     SDValue LHS = Cond.getOperand(0);
8602     SDValue RHS = Cond.getOperand(1);
8603     unsigned X86Opcode;
8604     unsigned X86Cond;
8605     SDVTList VTs;
8606     switch (CondOpcode) {
8607     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8608     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8609     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8610     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8611     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8612     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8613     default: llvm_unreachable("unexpected overflowing operator");
8614     }
8615     if (CondOpcode == ISD::UMULO)
8616       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8617                           MVT::i32);
8618     else
8619       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8620
8621     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8622
8623     if (CondOpcode == ISD::UMULO)
8624       Cond = X86Op.getValue(2);
8625     else
8626       Cond = X86Op.getValue(1);
8627
8628     CC = DAG.getConstant(X86Cond, MVT::i8);
8629     addTest = false;
8630   }
8631
8632   if (addTest) {
8633     // Look pass the truncate.
8634     if (Cond.getOpcode() == ISD::TRUNCATE)
8635       Cond = Cond.getOperand(0);
8636
8637     // We know the result of AND is compared against zero. Try to match
8638     // it to BT.
8639     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8640       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8641       if (NewSetCC.getNode()) {
8642         CC = NewSetCC.getOperand(0);
8643         Cond = NewSetCC.getOperand(1);
8644         addTest = false;
8645       }
8646     }
8647   }
8648
8649   if (addTest) {
8650     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8651     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8652   }
8653
8654   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8655   // a <  b ?  0 : -1 -> RES = setcc_carry
8656   // a >= b ? -1 :  0 -> RES = setcc_carry
8657   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8658   if (Cond.getOpcode() == X86ISD::CMP) {
8659     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8660
8661     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8662         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8663       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8664                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8665       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8666         return DAG.getNOT(DL, Res, Res.getValueType());
8667       return Res;
8668     }
8669   }
8670
8671   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8672   // condition is true.
8673   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8674   SDValue Ops[] = { Op2, Op1, CC, Cond };
8675   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8676 }
8677
8678 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8679 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8680 // from the AND / OR.
8681 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8682   Opc = Op.getOpcode();
8683   if (Opc != ISD::OR && Opc != ISD::AND)
8684     return false;
8685   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8686           Op.getOperand(0).hasOneUse() &&
8687           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8688           Op.getOperand(1).hasOneUse());
8689 }
8690
8691 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8692 // 1 and that the SETCC node has a single use.
8693 static bool isXor1OfSetCC(SDValue Op) {
8694   if (Op.getOpcode() != ISD::XOR)
8695     return false;
8696   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8697   if (N1C && N1C->getAPIntValue() == 1) {
8698     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8699       Op.getOperand(0).hasOneUse();
8700   }
8701   return false;
8702 }
8703
8704 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8705   bool addTest = true;
8706   SDValue Chain = Op.getOperand(0);
8707   SDValue Cond  = Op.getOperand(1);
8708   SDValue Dest  = Op.getOperand(2);
8709   DebugLoc dl = Op.getDebugLoc();
8710   SDValue CC;
8711   bool Inverted = false;
8712
8713   if (Cond.getOpcode() == ISD::SETCC) {
8714     // Check for setcc([su]{add,sub,mul}o == 0).
8715     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8716         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8717         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8718         Cond.getOperand(0).getResNo() == 1 &&
8719         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8720          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8721          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8722          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8723          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8724          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8725       Inverted = true;
8726       Cond = Cond.getOperand(0);
8727     } else {
8728       SDValue NewCond = LowerSETCC(Cond, DAG);
8729       if (NewCond.getNode())
8730         Cond = NewCond;
8731     }
8732   }
8733 #if 0
8734   // FIXME: LowerXALUO doesn't handle these!!
8735   else if (Cond.getOpcode() == X86ISD::ADD  ||
8736            Cond.getOpcode() == X86ISD::SUB  ||
8737            Cond.getOpcode() == X86ISD::SMUL ||
8738            Cond.getOpcode() == X86ISD::UMUL)
8739     Cond = LowerXALUO(Cond, DAG);
8740 #endif
8741
8742   // Look pass (and (setcc_carry (cmp ...)), 1).
8743   if (Cond.getOpcode() == ISD::AND &&
8744       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8745     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8746     if (C && C->getAPIntValue() == 1)
8747       Cond = Cond.getOperand(0);
8748   }
8749
8750   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8751   // setting operand in place of the X86ISD::SETCC.
8752   unsigned CondOpcode = Cond.getOpcode();
8753   if (CondOpcode == X86ISD::SETCC ||
8754       CondOpcode == X86ISD::SETCC_CARRY) {
8755     CC = Cond.getOperand(0);
8756
8757     SDValue Cmp = Cond.getOperand(1);
8758     unsigned Opc = Cmp.getOpcode();
8759     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8760     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8761       Cond = Cmp;
8762       addTest = false;
8763     } else {
8764       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8765       default: break;
8766       case X86::COND_O:
8767       case X86::COND_B:
8768         // These can only come from an arithmetic instruction with overflow,
8769         // e.g. SADDO, UADDO.
8770         Cond = Cond.getNode()->getOperand(1);
8771         addTest = false;
8772         break;
8773       }
8774     }
8775   }
8776   CondOpcode = Cond.getOpcode();
8777   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8778       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8779       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8780        Cond.getOperand(0).getValueType() != MVT::i8)) {
8781     SDValue LHS = Cond.getOperand(0);
8782     SDValue RHS = Cond.getOperand(1);
8783     unsigned X86Opcode;
8784     unsigned X86Cond;
8785     SDVTList VTs;
8786     switch (CondOpcode) {
8787     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8788     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8789     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8790     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8791     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8792     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8793     default: llvm_unreachable("unexpected overflowing operator");
8794     }
8795     if (Inverted)
8796       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8797     if (CondOpcode == ISD::UMULO)
8798       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8799                           MVT::i32);
8800     else
8801       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8802
8803     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8804
8805     if (CondOpcode == ISD::UMULO)
8806       Cond = X86Op.getValue(2);
8807     else
8808       Cond = X86Op.getValue(1);
8809
8810     CC = DAG.getConstant(X86Cond, MVT::i8);
8811     addTest = false;
8812   } else {
8813     unsigned CondOpc;
8814     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8815       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8816       if (CondOpc == ISD::OR) {
8817         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8818         // two branches instead of an explicit OR instruction with a
8819         // separate test.
8820         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8821             isX86LogicalCmp(Cmp)) {
8822           CC = Cond.getOperand(0).getOperand(0);
8823           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8824                               Chain, Dest, CC, Cmp);
8825           CC = Cond.getOperand(1).getOperand(0);
8826           Cond = Cmp;
8827           addTest = false;
8828         }
8829       } else { // ISD::AND
8830         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8831         // two branches instead of an explicit AND instruction with a
8832         // separate test. However, we only do this if this block doesn't
8833         // have a fall-through edge, because this requires an explicit
8834         // jmp when the condition is false.
8835         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8836             isX86LogicalCmp(Cmp) &&
8837             Op.getNode()->hasOneUse()) {
8838           X86::CondCode CCode =
8839             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8840           CCode = X86::GetOppositeBranchCondition(CCode);
8841           CC = DAG.getConstant(CCode, MVT::i8);
8842           SDNode *User = *Op.getNode()->use_begin();
8843           // Look for an unconditional branch following this conditional branch.
8844           // We need this because we need to reverse the successors in order
8845           // to implement FCMP_OEQ.
8846           if (User->getOpcode() == ISD::BR) {
8847             SDValue FalseBB = User->getOperand(1);
8848             SDNode *NewBR =
8849               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8850             assert(NewBR == User);
8851             (void)NewBR;
8852             Dest = FalseBB;
8853
8854             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8855                                 Chain, Dest, CC, Cmp);
8856             X86::CondCode CCode =
8857               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8858             CCode = X86::GetOppositeBranchCondition(CCode);
8859             CC = DAG.getConstant(CCode, MVT::i8);
8860             Cond = Cmp;
8861             addTest = false;
8862           }
8863         }
8864       }
8865     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8866       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8867       // It should be transformed during dag combiner except when the condition
8868       // is set by a arithmetics with overflow node.
8869       X86::CondCode CCode =
8870         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8871       CCode = X86::GetOppositeBranchCondition(CCode);
8872       CC = DAG.getConstant(CCode, MVT::i8);
8873       Cond = Cond.getOperand(0).getOperand(1);
8874       addTest = false;
8875     } else if (Cond.getOpcode() == ISD::SETCC &&
8876                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8877       // For FCMP_OEQ, we can emit
8878       // two branches instead of an explicit AND instruction with a
8879       // separate test. However, we only do this if this block doesn't
8880       // have a fall-through edge, because this requires an explicit
8881       // jmp when the condition is false.
8882       if (Op.getNode()->hasOneUse()) {
8883         SDNode *User = *Op.getNode()->use_begin();
8884         // Look for an unconditional branch following this conditional branch.
8885         // We need this because we need to reverse the successors in order
8886         // to implement FCMP_OEQ.
8887         if (User->getOpcode() == ISD::BR) {
8888           SDValue FalseBB = User->getOperand(1);
8889           SDNode *NewBR =
8890             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8891           assert(NewBR == User);
8892           (void)NewBR;
8893           Dest = FalseBB;
8894
8895           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8896                                     Cond.getOperand(0), Cond.getOperand(1));
8897           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8898           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8899                               Chain, Dest, CC, Cmp);
8900           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8901           Cond = Cmp;
8902           addTest = false;
8903         }
8904       }
8905     } else if (Cond.getOpcode() == ISD::SETCC &&
8906                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8907       // For FCMP_UNE, we can emit
8908       // two branches instead of an explicit AND instruction with a
8909       // separate test. However, we only do this if this block doesn't
8910       // have a fall-through edge, because this requires an explicit
8911       // jmp when the condition is false.
8912       if (Op.getNode()->hasOneUse()) {
8913         SDNode *User = *Op.getNode()->use_begin();
8914         // Look for an unconditional branch following this conditional branch.
8915         // We need this because we need to reverse the successors in order
8916         // to implement FCMP_UNE.
8917         if (User->getOpcode() == ISD::BR) {
8918           SDValue FalseBB = User->getOperand(1);
8919           SDNode *NewBR =
8920             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8921           assert(NewBR == User);
8922           (void)NewBR;
8923
8924           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8925                                     Cond.getOperand(0), Cond.getOperand(1));
8926           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8927           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8928                               Chain, Dest, CC, Cmp);
8929           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8930           Cond = Cmp;
8931           addTest = false;
8932           Dest = FalseBB;
8933         }
8934       }
8935     }
8936   }
8937
8938   if (addTest) {
8939     // Look pass the truncate.
8940     if (Cond.getOpcode() == ISD::TRUNCATE)
8941       Cond = Cond.getOperand(0);
8942
8943     // We know the result of AND is compared against zero. Try to match
8944     // it to BT.
8945     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8946       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8947       if (NewSetCC.getNode()) {
8948         CC = NewSetCC.getOperand(0);
8949         Cond = NewSetCC.getOperand(1);
8950         addTest = false;
8951       }
8952     }
8953   }
8954
8955   if (addTest) {
8956     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8957     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8958   }
8959   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8960                      Chain, Dest, CC, Cond);
8961 }
8962
8963
8964 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8965 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8966 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8967 // that the guard pages used by the OS virtual memory manager are allocated in
8968 // correct sequence.
8969 SDValue
8970 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8971                                            SelectionDAG &DAG) const {
8972   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8973           getTargetMachine().Options.EnableSegmentedStacks) &&
8974          "This should be used only on Windows targets or when segmented stacks "
8975          "are being used");
8976   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8977   DebugLoc dl = Op.getDebugLoc();
8978
8979   // Get the inputs.
8980   SDValue Chain = Op.getOperand(0);
8981   SDValue Size  = Op.getOperand(1);
8982   // FIXME: Ensure alignment here
8983
8984   bool Is64Bit = Subtarget->is64Bit();
8985   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8986
8987   if (getTargetMachine().Options.EnableSegmentedStacks) {
8988     MachineFunction &MF = DAG.getMachineFunction();
8989     MachineRegisterInfo &MRI = MF.getRegInfo();
8990
8991     if (Is64Bit) {
8992       // The 64 bit implementation of segmented stacks needs to clobber both r10
8993       // r11. This makes it impossible to use it along with nested parameters.
8994       const Function *F = MF.getFunction();
8995
8996       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8997            I != E; I++)
8998         if (I->hasNestAttr())
8999           report_fatal_error("Cannot use segmented stacks with functions that "
9000                              "have nested arguments.");
9001     }
9002
9003     const TargetRegisterClass *AddrRegClass =
9004       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9005     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9006     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9007     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9008                                 DAG.getRegister(Vreg, SPTy));
9009     SDValue Ops1[2] = { Value, Chain };
9010     return DAG.getMergeValues(Ops1, 2, dl);
9011   } else {
9012     SDValue Flag;
9013     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9014
9015     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9016     Flag = Chain.getValue(1);
9017     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9018
9019     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9020     Flag = Chain.getValue(1);
9021
9022     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9023
9024     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9025     return DAG.getMergeValues(Ops1, 2, dl);
9026   }
9027 }
9028
9029 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9030   MachineFunction &MF = DAG.getMachineFunction();
9031   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9032
9033   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9034   DebugLoc DL = Op.getDebugLoc();
9035
9036   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9037     // vastart just stores the address of the VarArgsFrameIndex slot into the
9038     // memory location argument.
9039     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9040                                    getPointerTy());
9041     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9042                         MachinePointerInfo(SV), false, false, 0);
9043   }
9044
9045   // __va_list_tag:
9046   //   gp_offset         (0 - 6 * 8)
9047   //   fp_offset         (48 - 48 + 8 * 16)
9048   //   overflow_arg_area (point to parameters coming in memory).
9049   //   reg_save_area
9050   SmallVector<SDValue, 8> MemOps;
9051   SDValue FIN = Op.getOperand(1);
9052   // Store gp_offset
9053   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9054                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9055                                                MVT::i32),
9056                                FIN, MachinePointerInfo(SV), false, false, 0);
9057   MemOps.push_back(Store);
9058
9059   // Store fp_offset
9060   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9061                     FIN, DAG.getIntPtrConstant(4));
9062   Store = DAG.getStore(Op.getOperand(0), DL,
9063                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9064                                        MVT::i32),
9065                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9066   MemOps.push_back(Store);
9067
9068   // Store ptr to overflow_arg_area
9069   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9070                     FIN, DAG.getIntPtrConstant(4));
9071   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9072                                     getPointerTy());
9073   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9074                        MachinePointerInfo(SV, 8),
9075                        false, false, 0);
9076   MemOps.push_back(Store);
9077
9078   // Store ptr to reg_save_area.
9079   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9080                     FIN, DAG.getIntPtrConstant(8));
9081   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9082                                     getPointerTy());
9083   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9084                        MachinePointerInfo(SV, 16), false, false, 0);
9085   MemOps.push_back(Store);
9086   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9087                      &MemOps[0], MemOps.size());
9088 }
9089
9090 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9091   assert(Subtarget->is64Bit() &&
9092          "LowerVAARG only handles 64-bit va_arg!");
9093   assert((Subtarget->isTargetLinux() ||
9094           Subtarget->isTargetDarwin()) &&
9095           "Unhandled target in LowerVAARG");
9096   assert(Op.getNode()->getNumOperands() == 4);
9097   SDValue Chain = Op.getOperand(0);
9098   SDValue SrcPtr = Op.getOperand(1);
9099   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9100   unsigned Align = Op.getConstantOperandVal(3);
9101   DebugLoc dl = Op.getDebugLoc();
9102
9103   EVT ArgVT = Op.getNode()->getValueType(0);
9104   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9105   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9106   uint8_t ArgMode;
9107
9108   // Decide which area this value should be read from.
9109   // TODO: Implement the AMD64 ABI in its entirety. This simple
9110   // selection mechanism works only for the basic types.
9111   if (ArgVT == MVT::f80) {
9112     llvm_unreachable("va_arg for f80 not yet implemented");
9113   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9114     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9115   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9116     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9117   } else {
9118     llvm_unreachable("Unhandled argument type in LowerVAARG");
9119   }
9120
9121   if (ArgMode == 2) {
9122     // Sanity Check: Make sure using fp_offset makes sense.
9123     assert(!getTargetMachine().Options.UseSoftFloat &&
9124            !(DAG.getMachineFunction()
9125                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9126            Subtarget->hasXMM());
9127   }
9128
9129   // Insert VAARG_64 node into the DAG
9130   // VAARG_64 returns two values: Variable Argument Address, Chain
9131   SmallVector<SDValue, 11> InstOps;
9132   InstOps.push_back(Chain);
9133   InstOps.push_back(SrcPtr);
9134   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9135   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9136   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9137   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9138   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9139                                           VTs, &InstOps[0], InstOps.size(),
9140                                           MVT::i64,
9141                                           MachinePointerInfo(SV),
9142                                           /*Align=*/0,
9143                                           /*Volatile=*/false,
9144                                           /*ReadMem=*/true,
9145                                           /*WriteMem=*/true);
9146   Chain = VAARG.getValue(1);
9147
9148   // Load the next argument and return it
9149   return DAG.getLoad(ArgVT, dl,
9150                      Chain,
9151                      VAARG,
9152                      MachinePointerInfo(),
9153                      false, false, false, 0);
9154 }
9155
9156 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9157   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9158   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9159   SDValue Chain = Op.getOperand(0);
9160   SDValue DstPtr = Op.getOperand(1);
9161   SDValue SrcPtr = Op.getOperand(2);
9162   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9163   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9164   DebugLoc DL = Op.getDebugLoc();
9165
9166   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9167                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9168                        false,
9169                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9170 }
9171
9172 SDValue
9173 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9174   DebugLoc dl = Op.getDebugLoc();
9175   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9176   switch (IntNo) {
9177   default: return SDValue();    // Don't custom lower most intrinsics.
9178   // Comparison intrinsics.
9179   case Intrinsic::x86_sse_comieq_ss:
9180   case Intrinsic::x86_sse_comilt_ss:
9181   case Intrinsic::x86_sse_comile_ss:
9182   case Intrinsic::x86_sse_comigt_ss:
9183   case Intrinsic::x86_sse_comige_ss:
9184   case Intrinsic::x86_sse_comineq_ss:
9185   case Intrinsic::x86_sse_ucomieq_ss:
9186   case Intrinsic::x86_sse_ucomilt_ss:
9187   case Intrinsic::x86_sse_ucomile_ss:
9188   case Intrinsic::x86_sse_ucomigt_ss:
9189   case Intrinsic::x86_sse_ucomige_ss:
9190   case Intrinsic::x86_sse_ucomineq_ss:
9191   case Intrinsic::x86_sse2_comieq_sd:
9192   case Intrinsic::x86_sse2_comilt_sd:
9193   case Intrinsic::x86_sse2_comile_sd:
9194   case Intrinsic::x86_sse2_comigt_sd:
9195   case Intrinsic::x86_sse2_comige_sd:
9196   case Intrinsic::x86_sse2_comineq_sd:
9197   case Intrinsic::x86_sse2_ucomieq_sd:
9198   case Intrinsic::x86_sse2_ucomilt_sd:
9199   case Intrinsic::x86_sse2_ucomile_sd:
9200   case Intrinsic::x86_sse2_ucomigt_sd:
9201   case Intrinsic::x86_sse2_ucomige_sd:
9202   case Intrinsic::x86_sse2_ucomineq_sd: {
9203     unsigned Opc = 0;
9204     ISD::CondCode CC = ISD::SETCC_INVALID;
9205     switch (IntNo) {
9206     default: break;
9207     case Intrinsic::x86_sse_comieq_ss:
9208     case Intrinsic::x86_sse2_comieq_sd:
9209       Opc = X86ISD::COMI;
9210       CC = ISD::SETEQ;
9211       break;
9212     case Intrinsic::x86_sse_comilt_ss:
9213     case Intrinsic::x86_sse2_comilt_sd:
9214       Opc = X86ISD::COMI;
9215       CC = ISD::SETLT;
9216       break;
9217     case Intrinsic::x86_sse_comile_ss:
9218     case Intrinsic::x86_sse2_comile_sd:
9219       Opc = X86ISD::COMI;
9220       CC = ISD::SETLE;
9221       break;
9222     case Intrinsic::x86_sse_comigt_ss:
9223     case Intrinsic::x86_sse2_comigt_sd:
9224       Opc = X86ISD::COMI;
9225       CC = ISD::SETGT;
9226       break;
9227     case Intrinsic::x86_sse_comige_ss:
9228     case Intrinsic::x86_sse2_comige_sd:
9229       Opc = X86ISD::COMI;
9230       CC = ISD::SETGE;
9231       break;
9232     case Intrinsic::x86_sse_comineq_ss:
9233     case Intrinsic::x86_sse2_comineq_sd:
9234       Opc = X86ISD::COMI;
9235       CC = ISD::SETNE;
9236       break;
9237     case Intrinsic::x86_sse_ucomieq_ss:
9238     case Intrinsic::x86_sse2_ucomieq_sd:
9239       Opc = X86ISD::UCOMI;
9240       CC = ISD::SETEQ;
9241       break;
9242     case Intrinsic::x86_sse_ucomilt_ss:
9243     case Intrinsic::x86_sse2_ucomilt_sd:
9244       Opc = X86ISD::UCOMI;
9245       CC = ISD::SETLT;
9246       break;
9247     case Intrinsic::x86_sse_ucomile_ss:
9248     case Intrinsic::x86_sse2_ucomile_sd:
9249       Opc = X86ISD::UCOMI;
9250       CC = ISD::SETLE;
9251       break;
9252     case Intrinsic::x86_sse_ucomigt_ss:
9253     case Intrinsic::x86_sse2_ucomigt_sd:
9254       Opc = X86ISD::UCOMI;
9255       CC = ISD::SETGT;
9256       break;
9257     case Intrinsic::x86_sse_ucomige_ss:
9258     case Intrinsic::x86_sse2_ucomige_sd:
9259       Opc = X86ISD::UCOMI;
9260       CC = ISD::SETGE;
9261       break;
9262     case Intrinsic::x86_sse_ucomineq_ss:
9263     case Intrinsic::x86_sse2_ucomineq_sd:
9264       Opc = X86ISD::UCOMI;
9265       CC = ISD::SETNE;
9266       break;
9267     }
9268
9269     SDValue LHS = Op.getOperand(1);
9270     SDValue RHS = Op.getOperand(2);
9271     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9272     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9273     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9274     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9275                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9277   }
9278   // Arithmetic intrinsics.
9279   case Intrinsic::x86_sse3_hadd_ps:
9280   case Intrinsic::x86_sse3_hadd_pd:
9281   case Intrinsic::x86_avx_hadd_ps_256:
9282   case Intrinsic::x86_avx_hadd_pd_256:
9283     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9284                        Op.getOperand(1), Op.getOperand(2));
9285   case Intrinsic::x86_sse3_hsub_ps:
9286   case Intrinsic::x86_sse3_hsub_pd:
9287   case Intrinsic::x86_avx_hsub_ps_256:
9288   case Intrinsic::x86_avx_hsub_pd_256:
9289     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9290                        Op.getOperand(1), Op.getOperand(2));
9291   case Intrinsic::x86_avx2_psllv_d:
9292   case Intrinsic::x86_avx2_psllv_q:
9293   case Intrinsic::x86_avx2_psllv_d_256:
9294   case Intrinsic::x86_avx2_psllv_q_256:
9295     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9296                       Op.getOperand(1), Op.getOperand(2));
9297   case Intrinsic::x86_avx2_psrlv_d:
9298   case Intrinsic::x86_avx2_psrlv_q:
9299   case Intrinsic::x86_avx2_psrlv_d_256:
9300   case Intrinsic::x86_avx2_psrlv_q_256:
9301     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9302                       Op.getOperand(1), Op.getOperand(2));
9303   case Intrinsic::x86_avx2_psrav_d:
9304   case Intrinsic::x86_avx2_psrav_d_256:
9305     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9306                       Op.getOperand(1), Op.getOperand(2));
9307
9308   // ptest and testp intrinsics. The intrinsic these come from are designed to
9309   // return an integer value, not just an instruction so lower it to the ptest
9310   // or testp pattern and a setcc for the result.
9311   case Intrinsic::x86_sse41_ptestz:
9312   case Intrinsic::x86_sse41_ptestc:
9313   case Intrinsic::x86_sse41_ptestnzc:
9314   case Intrinsic::x86_avx_ptestz_256:
9315   case Intrinsic::x86_avx_ptestc_256:
9316   case Intrinsic::x86_avx_ptestnzc_256:
9317   case Intrinsic::x86_avx_vtestz_ps:
9318   case Intrinsic::x86_avx_vtestc_ps:
9319   case Intrinsic::x86_avx_vtestnzc_ps:
9320   case Intrinsic::x86_avx_vtestz_pd:
9321   case Intrinsic::x86_avx_vtestc_pd:
9322   case Intrinsic::x86_avx_vtestnzc_pd:
9323   case Intrinsic::x86_avx_vtestz_ps_256:
9324   case Intrinsic::x86_avx_vtestc_ps_256:
9325   case Intrinsic::x86_avx_vtestnzc_ps_256:
9326   case Intrinsic::x86_avx_vtestz_pd_256:
9327   case Intrinsic::x86_avx_vtestc_pd_256:
9328   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9329     bool IsTestPacked = false;
9330     unsigned X86CC = 0;
9331     switch (IntNo) {
9332     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9333     case Intrinsic::x86_avx_vtestz_ps:
9334     case Intrinsic::x86_avx_vtestz_pd:
9335     case Intrinsic::x86_avx_vtestz_ps_256:
9336     case Intrinsic::x86_avx_vtestz_pd_256:
9337       IsTestPacked = true; // Fallthrough
9338     case Intrinsic::x86_sse41_ptestz:
9339     case Intrinsic::x86_avx_ptestz_256:
9340       // ZF = 1
9341       X86CC = X86::COND_E;
9342       break;
9343     case Intrinsic::x86_avx_vtestc_ps:
9344     case Intrinsic::x86_avx_vtestc_pd:
9345     case Intrinsic::x86_avx_vtestc_ps_256:
9346     case Intrinsic::x86_avx_vtestc_pd_256:
9347       IsTestPacked = true; // Fallthrough
9348     case Intrinsic::x86_sse41_ptestc:
9349     case Intrinsic::x86_avx_ptestc_256:
9350       // CF = 1
9351       X86CC = X86::COND_B;
9352       break;
9353     case Intrinsic::x86_avx_vtestnzc_ps:
9354     case Intrinsic::x86_avx_vtestnzc_pd:
9355     case Intrinsic::x86_avx_vtestnzc_ps_256:
9356     case Intrinsic::x86_avx_vtestnzc_pd_256:
9357       IsTestPacked = true; // Fallthrough
9358     case Intrinsic::x86_sse41_ptestnzc:
9359     case Intrinsic::x86_avx_ptestnzc_256:
9360       // ZF and CF = 0
9361       X86CC = X86::COND_A;
9362       break;
9363     }
9364
9365     SDValue LHS = Op.getOperand(1);
9366     SDValue RHS = Op.getOperand(2);
9367     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9368     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9369     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9370     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9371     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9372   }
9373
9374   // Fix vector shift instructions where the last operand is a non-immediate
9375   // i32 value.
9376   case Intrinsic::x86_avx2_pslli_w:
9377   case Intrinsic::x86_avx2_pslli_d:
9378   case Intrinsic::x86_avx2_pslli_q:
9379   case Intrinsic::x86_avx2_psrli_w:
9380   case Intrinsic::x86_avx2_psrli_d:
9381   case Intrinsic::x86_avx2_psrli_q:
9382   case Intrinsic::x86_avx2_psrai_w:
9383   case Intrinsic::x86_avx2_psrai_d:
9384   case Intrinsic::x86_sse2_pslli_w:
9385   case Intrinsic::x86_sse2_pslli_d:
9386   case Intrinsic::x86_sse2_pslli_q:
9387   case Intrinsic::x86_sse2_psrli_w:
9388   case Intrinsic::x86_sse2_psrli_d:
9389   case Intrinsic::x86_sse2_psrli_q:
9390   case Intrinsic::x86_sse2_psrai_w:
9391   case Intrinsic::x86_sse2_psrai_d:
9392   case Intrinsic::x86_mmx_pslli_w:
9393   case Intrinsic::x86_mmx_pslli_d:
9394   case Intrinsic::x86_mmx_pslli_q:
9395   case Intrinsic::x86_mmx_psrli_w:
9396   case Intrinsic::x86_mmx_psrli_d:
9397   case Intrinsic::x86_mmx_psrli_q:
9398   case Intrinsic::x86_mmx_psrai_w:
9399   case Intrinsic::x86_mmx_psrai_d: {
9400     SDValue ShAmt = Op.getOperand(2);
9401     if (isa<ConstantSDNode>(ShAmt))
9402       return SDValue();
9403
9404     unsigned NewIntNo = 0;
9405     EVT ShAmtVT = MVT::v4i32;
9406     switch (IntNo) {
9407     case Intrinsic::x86_sse2_pslli_w:
9408       NewIntNo = Intrinsic::x86_sse2_psll_w;
9409       break;
9410     case Intrinsic::x86_sse2_pslli_d:
9411       NewIntNo = Intrinsic::x86_sse2_psll_d;
9412       break;
9413     case Intrinsic::x86_sse2_pslli_q:
9414       NewIntNo = Intrinsic::x86_sse2_psll_q;
9415       break;
9416     case Intrinsic::x86_sse2_psrli_w:
9417       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9418       break;
9419     case Intrinsic::x86_sse2_psrli_d:
9420       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9421       break;
9422     case Intrinsic::x86_sse2_psrli_q:
9423       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9424       break;
9425     case Intrinsic::x86_sse2_psrai_w:
9426       NewIntNo = Intrinsic::x86_sse2_psra_w;
9427       break;
9428     case Intrinsic::x86_sse2_psrai_d:
9429       NewIntNo = Intrinsic::x86_sse2_psra_d;
9430       break;
9431     case Intrinsic::x86_avx2_pslli_w:
9432       NewIntNo = Intrinsic::x86_avx2_psll_w;
9433       break;
9434     case Intrinsic::x86_avx2_pslli_d:
9435       NewIntNo = Intrinsic::x86_avx2_psll_d;
9436       break;
9437     case Intrinsic::x86_avx2_pslli_q:
9438       NewIntNo = Intrinsic::x86_avx2_psll_q;
9439       break;
9440     case Intrinsic::x86_avx2_psrli_w:
9441       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9442       break;
9443     case Intrinsic::x86_avx2_psrli_d:
9444       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9445       break;
9446     case Intrinsic::x86_avx2_psrli_q:
9447       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9448       break;
9449     case Intrinsic::x86_avx2_psrai_w:
9450       NewIntNo = Intrinsic::x86_avx2_psra_w;
9451       break;
9452     case Intrinsic::x86_avx2_psrai_d:
9453       NewIntNo = Intrinsic::x86_avx2_psra_d;
9454       break;
9455     default: {
9456       ShAmtVT = MVT::v2i32;
9457       switch (IntNo) {
9458       case Intrinsic::x86_mmx_pslli_w:
9459         NewIntNo = Intrinsic::x86_mmx_psll_w;
9460         break;
9461       case Intrinsic::x86_mmx_pslli_d:
9462         NewIntNo = Intrinsic::x86_mmx_psll_d;
9463         break;
9464       case Intrinsic::x86_mmx_pslli_q:
9465         NewIntNo = Intrinsic::x86_mmx_psll_q;
9466         break;
9467       case Intrinsic::x86_mmx_psrli_w:
9468         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9469         break;
9470       case Intrinsic::x86_mmx_psrli_d:
9471         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9472         break;
9473       case Intrinsic::x86_mmx_psrli_q:
9474         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9475         break;
9476       case Intrinsic::x86_mmx_psrai_w:
9477         NewIntNo = Intrinsic::x86_mmx_psra_w;
9478         break;
9479       case Intrinsic::x86_mmx_psrai_d:
9480         NewIntNo = Intrinsic::x86_mmx_psra_d;
9481         break;
9482       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9483       }
9484       break;
9485     }
9486     }
9487
9488     // The vector shift intrinsics with scalars uses 32b shift amounts but
9489     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9490     // to be zero.
9491     SDValue ShOps[4];
9492     ShOps[0] = ShAmt;
9493     ShOps[1] = DAG.getConstant(0, MVT::i32);
9494     if (ShAmtVT == MVT::v4i32) {
9495       ShOps[2] = DAG.getUNDEF(MVT::i32);
9496       ShOps[3] = DAG.getUNDEF(MVT::i32);
9497       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9498     } else {
9499       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9500 // FIXME this must be lowered to get rid of the invalid type.
9501     }
9502
9503     EVT VT = Op.getValueType();
9504     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9505     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9506                        DAG.getConstant(NewIntNo, MVT::i32),
9507                        Op.getOperand(1), ShAmt);
9508   }
9509   }
9510 }
9511
9512 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9513                                            SelectionDAG &DAG) const {
9514   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9515   MFI->setReturnAddressIsTaken(true);
9516
9517   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9518   DebugLoc dl = Op.getDebugLoc();
9519
9520   if (Depth > 0) {
9521     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9522     SDValue Offset =
9523       DAG.getConstant(TD->getPointerSize(),
9524                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9525     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9526                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9527                                    FrameAddr, Offset),
9528                        MachinePointerInfo(), false, false, false, 0);
9529   }
9530
9531   // Just load the return address.
9532   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9533   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9534                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9535 }
9536
9537 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9538   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9539   MFI->setFrameAddressIsTaken(true);
9540
9541   EVT VT = Op.getValueType();
9542   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9543   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9544   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9545   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9546   while (Depth--)
9547     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9548                             MachinePointerInfo(),
9549                             false, false, false, 0);
9550   return FrameAddr;
9551 }
9552
9553 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9554                                                      SelectionDAG &DAG) const {
9555   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9556 }
9557
9558 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9559   MachineFunction &MF = DAG.getMachineFunction();
9560   SDValue Chain     = Op.getOperand(0);
9561   SDValue Offset    = Op.getOperand(1);
9562   SDValue Handler   = Op.getOperand(2);
9563   DebugLoc dl       = Op.getDebugLoc();
9564
9565   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9566                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9567                                      getPointerTy());
9568   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9569
9570   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9571                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9572   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9573   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9574                        false, false, 0);
9575   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9576   MF.getRegInfo().addLiveOut(StoreAddrReg);
9577
9578   return DAG.getNode(X86ISD::EH_RETURN, dl,
9579                      MVT::Other,
9580                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9581 }
9582
9583 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9584                                                   SelectionDAG &DAG) const {
9585   return Op.getOperand(0);
9586 }
9587
9588 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9589                                                 SelectionDAG &DAG) const {
9590   SDValue Root = Op.getOperand(0);
9591   SDValue Trmp = Op.getOperand(1); // trampoline
9592   SDValue FPtr = Op.getOperand(2); // nested function
9593   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9594   DebugLoc dl  = Op.getDebugLoc();
9595
9596   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9597
9598   if (Subtarget->is64Bit()) {
9599     SDValue OutChains[6];
9600
9601     // Large code-model.
9602     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9603     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9604
9605     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9606     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9607
9608     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9609
9610     // Load the pointer to the nested function into R11.
9611     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9612     SDValue Addr = Trmp;
9613     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9614                                 Addr, MachinePointerInfo(TrmpAddr),
9615                                 false, false, 0);
9616
9617     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9618                        DAG.getConstant(2, MVT::i64));
9619     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9620                                 MachinePointerInfo(TrmpAddr, 2),
9621                                 false, false, 2);
9622
9623     // Load the 'nest' parameter value into R10.
9624     // R10 is specified in X86CallingConv.td
9625     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9626     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9627                        DAG.getConstant(10, MVT::i64));
9628     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9629                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9630                                 false, false, 0);
9631
9632     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9633                        DAG.getConstant(12, MVT::i64));
9634     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9635                                 MachinePointerInfo(TrmpAddr, 12),
9636                                 false, false, 2);
9637
9638     // Jump to the nested function.
9639     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9640     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9641                        DAG.getConstant(20, MVT::i64));
9642     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9643                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9644                                 false, false, 0);
9645
9646     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9647     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9648                        DAG.getConstant(22, MVT::i64));
9649     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9650                                 MachinePointerInfo(TrmpAddr, 22),
9651                                 false, false, 0);
9652
9653     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9654   } else {
9655     const Function *Func =
9656       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9657     CallingConv::ID CC = Func->getCallingConv();
9658     unsigned NestReg;
9659
9660     switch (CC) {
9661     default:
9662       llvm_unreachable("Unsupported calling convention");
9663     case CallingConv::C:
9664     case CallingConv::X86_StdCall: {
9665       // Pass 'nest' parameter in ECX.
9666       // Must be kept in sync with X86CallingConv.td
9667       NestReg = X86::ECX;
9668
9669       // Check that ECX wasn't needed by an 'inreg' parameter.
9670       FunctionType *FTy = Func->getFunctionType();
9671       const AttrListPtr &Attrs = Func->getAttributes();
9672
9673       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9674         unsigned InRegCount = 0;
9675         unsigned Idx = 1;
9676
9677         for (FunctionType::param_iterator I = FTy->param_begin(),
9678              E = FTy->param_end(); I != E; ++I, ++Idx)
9679           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9680             // FIXME: should only count parameters that are lowered to integers.
9681             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9682
9683         if (InRegCount > 2) {
9684           report_fatal_error("Nest register in use - reduce number of inreg"
9685                              " parameters!");
9686         }
9687       }
9688       break;
9689     }
9690     case CallingConv::X86_FastCall:
9691     case CallingConv::X86_ThisCall:
9692     case CallingConv::Fast:
9693       // Pass 'nest' parameter in EAX.
9694       // Must be kept in sync with X86CallingConv.td
9695       NestReg = X86::EAX;
9696       break;
9697     }
9698
9699     SDValue OutChains[4];
9700     SDValue Addr, Disp;
9701
9702     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9703                        DAG.getConstant(10, MVT::i32));
9704     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9705
9706     // This is storing the opcode for MOV32ri.
9707     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9708     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9709     OutChains[0] = DAG.getStore(Root, dl,
9710                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9711                                 Trmp, MachinePointerInfo(TrmpAddr),
9712                                 false, false, 0);
9713
9714     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9715                        DAG.getConstant(1, MVT::i32));
9716     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9717                                 MachinePointerInfo(TrmpAddr, 1),
9718                                 false, false, 1);
9719
9720     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9721     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9722                        DAG.getConstant(5, MVT::i32));
9723     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9724                                 MachinePointerInfo(TrmpAddr, 5),
9725                                 false, false, 1);
9726
9727     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9728                        DAG.getConstant(6, MVT::i32));
9729     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9730                                 MachinePointerInfo(TrmpAddr, 6),
9731                                 false, false, 1);
9732
9733     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9734   }
9735 }
9736
9737 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9738                                             SelectionDAG &DAG) const {
9739   /*
9740    The rounding mode is in bits 11:10 of FPSR, and has the following
9741    settings:
9742      00 Round to nearest
9743      01 Round to -inf
9744      10 Round to +inf
9745      11 Round to 0
9746
9747   FLT_ROUNDS, on the other hand, expects the following:
9748     -1 Undefined
9749      0 Round to 0
9750      1 Round to nearest
9751      2 Round to +inf
9752      3 Round to -inf
9753
9754   To perform the conversion, we do:
9755     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9756   */
9757
9758   MachineFunction &MF = DAG.getMachineFunction();
9759   const TargetMachine &TM = MF.getTarget();
9760   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9761   unsigned StackAlignment = TFI.getStackAlignment();
9762   EVT VT = Op.getValueType();
9763   DebugLoc DL = Op.getDebugLoc();
9764
9765   // Save FP Control Word to stack slot
9766   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9767   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9768
9769
9770   MachineMemOperand *MMO =
9771    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9772                            MachineMemOperand::MOStore, 2, 2);
9773
9774   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9775   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9776                                           DAG.getVTList(MVT::Other),
9777                                           Ops, 2, MVT::i16, MMO);
9778
9779   // Load FP Control Word from stack slot
9780   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9781                             MachinePointerInfo(), false, false, false, 0);
9782
9783   // Transform as necessary
9784   SDValue CWD1 =
9785     DAG.getNode(ISD::SRL, DL, MVT::i16,
9786                 DAG.getNode(ISD::AND, DL, MVT::i16,
9787                             CWD, DAG.getConstant(0x800, MVT::i16)),
9788                 DAG.getConstant(11, MVT::i8));
9789   SDValue CWD2 =
9790     DAG.getNode(ISD::SRL, DL, MVT::i16,
9791                 DAG.getNode(ISD::AND, DL, MVT::i16,
9792                             CWD, DAG.getConstant(0x400, MVT::i16)),
9793                 DAG.getConstant(9, MVT::i8));
9794
9795   SDValue RetVal =
9796     DAG.getNode(ISD::AND, DL, MVT::i16,
9797                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9798                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9799                             DAG.getConstant(1, MVT::i16)),
9800                 DAG.getConstant(3, MVT::i16));
9801
9802
9803   return DAG.getNode((VT.getSizeInBits() < 16 ?
9804                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9805 }
9806
9807 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9808   EVT VT = Op.getValueType();
9809   EVT OpVT = VT;
9810   unsigned NumBits = VT.getSizeInBits();
9811   DebugLoc dl = Op.getDebugLoc();
9812
9813   Op = Op.getOperand(0);
9814   if (VT == MVT::i8) {
9815     // Zero extend to i32 since there is not an i8 bsr.
9816     OpVT = MVT::i32;
9817     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9818   }
9819
9820   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9821   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9822   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9823
9824   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9825   SDValue Ops[] = {
9826     Op,
9827     DAG.getConstant(NumBits+NumBits-1, OpVT),
9828     DAG.getConstant(X86::COND_E, MVT::i8),
9829     Op.getValue(1)
9830   };
9831   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9832
9833   // Finally xor with NumBits-1.
9834   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9835
9836   if (VT == MVT::i8)
9837     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9838   return Op;
9839 }
9840
9841 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9842   EVT VT = Op.getValueType();
9843   EVT OpVT = VT;
9844   unsigned NumBits = VT.getSizeInBits();
9845   DebugLoc dl = Op.getDebugLoc();
9846
9847   Op = Op.getOperand(0);
9848   if (VT == MVT::i8) {
9849     OpVT = MVT::i32;
9850     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9851   }
9852
9853   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9854   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9855   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9856
9857   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9858   SDValue Ops[] = {
9859     Op,
9860     DAG.getConstant(NumBits, OpVT),
9861     DAG.getConstant(X86::COND_E, MVT::i8),
9862     Op.getValue(1)
9863   };
9864   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9865
9866   if (VT == MVT::i8)
9867     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9868   return Op;
9869 }
9870
9871 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9872 // ones, and then concatenate the result back.
9873 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9874   EVT VT = Op.getValueType();
9875
9876   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9877          "Unsupported value type for operation");
9878
9879   int NumElems = VT.getVectorNumElements();
9880   DebugLoc dl = Op.getDebugLoc();
9881   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9882   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9883
9884   // Extract the LHS vectors
9885   SDValue LHS = Op.getOperand(0);
9886   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9887   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9888
9889   // Extract the RHS vectors
9890   SDValue RHS = Op.getOperand(1);
9891   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9892   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9893
9894   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9895   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9896
9897   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9898                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9899                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9900 }
9901
9902 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9903   assert(Op.getValueType().getSizeInBits() == 256 &&
9904          Op.getValueType().isInteger() &&
9905          "Only handle AVX 256-bit vector integer operation");
9906   return Lower256IntArith(Op, DAG);
9907 }
9908
9909 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9910   assert(Op.getValueType().getSizeInBits() == 256 &&
9911          Op.getValueType().isInteger() &&
9912          "Only handle AVX 256-bit vector integer operation");
9913   return Lower256IntArith(Op, DAG);
9914 }
9915
9916 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9917   EVT VT = Op.getValueType();
9918
9919   // Decompose 256-bit ops into smaller 128-bit ops.
9920   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9921     return Lower256IntArith(Op, DAG);
9922
9923   DebugLoc dl = Op.getDebugLoc();
9924
9925   SDValue A = Op.getOperand(0);
9926   SDValue B = Op.getOperand(1);
9927
9928   if (VT == MVT::v4i64) {
9929     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9930
9931     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9932     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9933     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9934     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9935     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9936     //
9937     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9938     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9939     //  return AloBlo + AloBhi + AhiBlo;
9940
9941     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9942                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9943                          A, DAG.getConstant(32, MVT::i32));
9944     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9945                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9946                          B, DAG.getConstant(32, MVT::i32));
9947     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9948                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9949                          A, B);
9950     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9951                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9952                          A, Bhi);
9953     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9954                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9955                          Ahi, B);
9956     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9957                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9958                          AloBhi, DAG.getConstant(32, MVT::i32));
9959     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9960                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9961                          AhiBlo, DAG.getConstant(32, MVT::i32));
9962     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9963     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9964     return Res;
9965   }
9966
9967   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9968
9969   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9970   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9971   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9972   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9973   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9974   //
9975   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9976   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9977   //  return AloBlo + AloBhi + AhiBlo;
9978
9979   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9980                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9981                        A, DAG.getConstant(32, MVT::i32));
9982   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9983                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9984                        B, DAG.getConstant(32, MVT::i32));
9985   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9986                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9987                        A, B);
9988   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9989                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9990                        A, Bhi);
9991   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9992                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9993                        Ahi, B);
9994   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9995                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9996                        AloBhi, DAG.getConstant(32, MVT::i32));
9997   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9998                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9999                        AhiBlo, DAG.getConstant(32, MVT::i32));
10000   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10001   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10002   return Res;
10003 }
10004
10005 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10006
10007   EVT VT = Op.getValueType();
10008   DebugLoc dl = Op.getDebugLoc();
10009   SDValue R = Op.getOperand(0);
10010   SDValue Amt = Op.getOperand(1);
10011   LLVMContext *Context = DAG.getContext();
10012
10013   if (!Subtarget->hasXMMInt())
10014     return SDValue();
10015
10016   // Optimize shl/srl/sra with constant shift amount.
10017   if (isSplatVector(Amt.getNode())) {
10018     SDValue SclrAmt = Amt->getOperand(0);
10019     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10020       uint64_t ShiftAmt = C->getZExtValue();
10021
10022       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10023         // Make a large shift.
10024         SDValue SHL =
10025           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10026                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10027                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10028         // Zero out the rightmost bits.
10029         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10030                                                        MVT::i8));
10031         return DAG.getNode(ISD::AND, dl, VT, SHL,
10032                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10033       }
10034
10035       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10036        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10037                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10038                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10039
10040       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10041        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10042                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10043                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10044
10045       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10046        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10047                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10048                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10049
10050       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10051         // Make a large shift.
10052         SDValue SRL =
10053           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10054                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10055                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10056         // Zero out the leftmost bits.
10057         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10058                                                        MVT::i8));
10059         return DAG.getNode(ISD::AND, dl, VT, SRL,
10060                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10061       }
10062
10063       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10064        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10066                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10067
10068       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10069        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10070                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10071                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10072
10073       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10074        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10075                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10076                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10077
10078       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10079        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10080                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10081                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10082
10083       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10084        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10085                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10086                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10087
10088       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10089         if (ShiftAmt == 7) {
10090           // R s>> 7  ===  R s< 0
10091           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10092           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10093         }
10094
10095         // R s>> a === ((R u>> a) ^ m) - m
10096         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10097         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10098                                                        MVT::i8));
10099         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10100         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10101         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10102         return Res;
10103       }
10104
10105       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10106         if (Op.getOpcode() == ISD::SHL) {
10107           // Make a large shift.
10108           SDValue SHL =
10109             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10110                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10111                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10112           // Zero out the rightmost bits.
10113           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10114                                                          MVT::i8));
10115           return DAG.getNode(ISD::AND, dl, VT, SHL,
10116                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10117         }
10118         if (Op.getOpcode() == ISD::SRL) {
10119           // Make a large shift.
10120           SDValue SRL =
10121             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10122                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10123                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10124           // Zero out the leftmost bits.
10125           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10126                                                          MVT::i8));
10127           return DAG.getNode(ISD::AND, dl, VT, SRL,
10128                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10129         }
10130         if (Op.getOpcode() == ISD::SRA) {
10131           if (ShiftAmt == 7) {
10132             // R s>> 7  ===  R s< 0
10133             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10134             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10135           }
10136
10137           // R s>> a === ((R u>> a) ^ m) - m
10138           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10139           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10140                                                          MVT::i8));
10141           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10142           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10143           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10144           return Res;
10145         }
10146       }
10147     }
10148   }
10149
10150   // Lower SHL with variable shift amount.
10151   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10152     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10153                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10154                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10155
10156     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10157
10158     std::vector<Constant*> CV(4, CI);
10159     Constant *C = ConstantVector::get(CV);
10160     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10161     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10162                                  MachinePointerInfo::getConstantPool(),
10163                                  false, false, false, 16);
10164
10165     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10166     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10167     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10168     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10169   }
10170   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10171     // a = a << 5;
10172     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10173                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10174                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10175
10176     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10177     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10178
10179     std::vector<Constant*> CVM1(16, CM1);
10180     std::vector<Constant*> CVM2(16, CM2);
10181     Constant *C = ConstantVector::get(CVM1);
10182     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10183     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10184                             MachinePointerInfo::getConstantPool(),
10185                             false, false, false, 16);
10186
10187     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10188     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10189     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10190                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10191                     DAG.getConstant(4, MVT::i32));
10192     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, M, R);
10193     // a += a
10194     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10195
10196     C = ConstantVector::get(CVM2);
10197     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10198     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10199                     MachinePointerInfo::getConstantPool(),
10200                     false, false, false, 16);
10201
10202     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10203     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10204     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10205                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10206                     DAG.getConstant(2, MVT::i32));
10207     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, M, R);
10208     // a += a
10209     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10210
10211     // return pblendv(r, r+r, a);
10212     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10213                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10214     return R;
10215   }
10216
10217   // Decompose 256-bit shifts into smaller 128-bit shifts.
10218   if (VT.getSizeInBits() == 256) {
10219     int NumElems = VT.getVectorNumElements();
10220     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10221     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10222
10223     // Extract the two vectors
10224     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10225     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10226                                      DAG, dl);
10227
10228     // Recreate the shift amount vectors
10229     SDValue Amt1, Amt2;
10230     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10231       // Constant shift amount
10232       SmallVector<SDValue, 4> Amt1Csts;
10233       SmallVector<SDValue, 4> Amt2Csts;
10234       for (int i = 0; i < NumElems/2; ++i)
10235         Amt1Csts.push_back(Amt->getOperand(i));
10236       for (int i = NumElems/2; i < NumElems; ++i)
10237         Amt2Csts.push_back(Amt->getOperand(i));
10238
10239       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10240                                  &Amt1Csts[0], NumElems/2);
10241       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10242                                  &Amt2Csts[0], NumElems/2);
10243     } else {
10244       // Variable shift amount
10245       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10246       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10247                                  DAG, dl);
10248     }
10249
10250     // Issue new vector shifts for the smaller types
10251     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10252     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10253
10254     // Concatenate the result back
10255     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10256   }
10257
10258   return SDValue();
10259 }
10260
10261 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10262   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10263   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10264   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10265   // has only one use.
10266   SDNode *N = Op.getNode();
10267   SDValue LHS = N->getOperand(0);
10268   SDValue RHS = N->getOperand(1);
10269   unsigned BaseOp = 0;
10270   unsigned Cond = 0;
10271   DebugLoc DL = Op.getDebugLoc();
10272   switch (Op.getOpcode()) {
10273   default: llvm_unreachable("Unknown ovf instruction!");
10274   case ISD::SADDO:
10275     // A subtract of one will be selected as a INC. Note that INC doesn't
10276     // set CF, so we can't do this for UADDO.
10277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10278       if (C->isOne()) {
10279         BaseOp = X86ISD::INC;
10280         Cond = X86::COND_O;
10281         break;
10282       }
10283     BaseOp = X86ISD::ADD;
10284     Cond = X86::COND_O;
10285     break;
10286   case ISD::UADDO:
10287     BaseOp = X86ISD::ADD;
10288     Cond = X86::COND_B;
10289     break;
10290   case ISD::SSUBO:
10291     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10292     // set CF, so we can't do this for USUBO.
10293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10294       if (C->isOne()) {
10295         BaseOp = X86ISD::DEC;
10296         Cond = X86::COND_O;
10297         break;
10298       }
10299     BaseOp = X86ISD::SUB;
10300     Cond = X86::COND_O;
10301     break;
10302   case ISD::USUBO:
10303     BaseOp = X86ISD::SUB;
10304     Cond = X86::COND_B;
10305     break;
10306   case ISD::SMULO:
10307     BaseOp = X86ISD::SMUL;
10308     Cond = X86::COND_O;
10309     break;
10310   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10311     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10312                                  MVT::i32);
10313     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10314
10315     SDValue SetCC =
10316       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10317                   DAG.getConstant(X86::COND_O, MVT::i32),
10318                   SDValue(Sum.getNode(), 2));
10319
10320     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10321   }
10322   }
10323
10324   // Also sets EFLAGS.
10325   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10326   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10327
10328   SDValue SetCC =
10329     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10330                 DAG.getConstant(Cond, MVT::i32),
10331                 SDValue(Sum.getNode(), 1));
10332
10333   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10334 }
10335
10336 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10337   DebugLoc dl = Op.getDebugLoc();
10338   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10339   EVT VT = Op.getValueType();
10340
10341   if (Subtarget->hasXMMInt() && VT.isVector()) {
10342     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10343                         ExtraVT.getScalarType().getSizeInBits();
10344     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10345
10346     unsigned SHLIntrinsicsID = 0;
10347     unsigned SRAIntrinsicsID = 0;
10348     switch (VT.getSimpleVT().SimpleTy) {
10349       default:
10350         return SDValue();
10351       case MVT::v4i32:
10352         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10353         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10354         break;
10355       case MVT::v8i16:
10356         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10357         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10358         break;
10359       case MVT::v8i32:
10360       case MVT::v16i16:
10361         if (!Subtarget->hasAVX())
10362           return SDValue();
10363         if (!Subtarget->hasAVX2()) {
10364           // needs to be split
10365           int NumElems = VT.getVectorNumElements();
10366           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10367           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10368
10369           // Extract the LHS vectors
10370           SDValue LHS = Op.getOperand(0);
10371           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10372           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10373
10374           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10375           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10376
10377           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10378           int ExtraNumElems = ExtraVT.getVectorNumElements();
10379           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10380                                      ExtraNumElems/2);
10381           SDValue Extra = DAG.getValueType(ExtraVT);
10382
10383           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10384           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10385
10386           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10387         }
10388         if (VT == MVT::v8i32) {
10389           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10390           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10391         } else {
10392           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10393           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10394         }
10395     }
10396
10397     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10398                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10399                          Op.getOperand(0), ShAmt);
10400
10401     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10402                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10403                        Tmp1, ShAmt);
10404   }
10405
10406   return SDValue();
10407 }
10408
10409
10410 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10411   DebugLoc dl = Op.getDebugLoc();
10412
10413   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10414   // There isn't any reason to disable it if the target processor supports it.
10415   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10416     SDValue Chain = Op.getOperand(0);
10417     SDValue Zero = DAG.getConstant(0, MVT::i32);
10418     SDValue Ops[] = {
10419       DAG.getRegister(X86::ESP, MVT::i32), // Base
10420       DAG.getTargetConstant(1, MVT::i8),   // Scale
10421       DAG.getRegister(0, MVT::i32),        // Index
10422       DAG.getTargetConstant(0, MVT::i32),  // Disp
10423       DAG.getRegister(0, MVT::i32),        // Segment.
10424       Zero,
10425       Chain
10426     };
10427     SDNode *Res =
10428       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10429                           array_lengthof(Ops));
10430     return SDValue(Res, 0);
10431   }
10432
10433   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10434   if (!isDev)
10435     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10436
10437   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10438   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10439   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10440   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10441
10442   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10443   if (!Op1 && !Op2 && !Op3 && Op4)
10444     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10445
10446   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10447   if (Op1 && !Op2 && !Op3 && !Op4)
10448     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10449
10450   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10451   //           (MFENCE)>;
10452   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10453 }
10454
10455 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10456                                              SelectionDAG &DAG) const {
10457   DebugLoc dl = Op.getDebugLoc();
10458   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10459     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10460   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10461     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10462
10463   // The only fence that needs an instruction is a sequentially-consistent
10464   // cross-thread fence.
10465   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10466     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10467     // no-sse2). There isn't any reason to disable it if the target processor
10468     // supports it.
10469     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10470       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10471
10472     SDValue Chain = Op.getOperand(0);
10473     SDValue Zero = DAG.getConstant(0, MVT::i32);
10474     SDValue Ops[] = {
10475       DAG.getRegister(X86::ESP, MVT::i32), // Base
10476       DAG.getTargetConstant(1, MVT::i8),   // Scale
10477       DAG.getRegister(0, MVT::i32),        // Index
10478       DAG.getTargetConstant(0, MVT::i32),  // Disp
10479       DAG.getRegister(0, MVT::i32),        // Segment.
10480       Zero,
10481       Chain
10482     };
10483     SDNode *Res =
10484       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10485                          array_lengthof(Ops));
10486     return SDValue(Res, 0);
10487   }
10488
10489   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10490   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10491 }
10492
10493
10494 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10495   EVT T = Op.getValueType();
10496   DebugLoc DL = Op.getDebugLoc();
10497   unsigned Reg = 0;
10498   unsigned size = 0;
10499   switch(T.getSimpleVT().SimpleTy) {
10500   default:
10501     assert(false && "Invalid value type!");
10502   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10503   case MVT::i16: Reg = X86::AX;  size = 2; break;
10504   case MVT::i32: Reg = X86::EAX; size = 4; break;
10505   case MVT::i64:
10506     assert(Subtarget->is64Bit() && "Node not type legal!");
10507     Reg = X86::RAX; size = 8;
10508     break;
10509   }
10510   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10511                                     Op.getOperand(2), SDValue());
10512   SDValue Ops[] = { cpIn.getValue(0),
10513                     Op.getOperand(1),
10514                     Op.getOperand(3),
10515                     DAG.getTargetConstant(size, MVT::i8),
10516                     cpIn.getValue(1) };
10517   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10518   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10519   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10520                                            Ops, 5, T, MMO);
10521   SDValue cpOut =
10522     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10523   return cpOut;
10524 }
10525
10526 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10527                                                  SelectionDAG &DAG) const {
10528   assert(Subtarget->is64Bit() && "Result not type legalized?");
10529   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10530   SDValue TheChain = Op.getOperand(0);
10531   DebugLoc dl = Op.getDebugLoc();
10532   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10533   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10534   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10535                                    rax.getValue(2));
10536   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10537                             DAG.getConstant(32, MVT::i8));
10538   SDValue Ops[] = {
10539     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10540     rdx.getValue(1)
10541   };
10542   return DAG.getMergeValues(Ops, 2, dl);
10543 }
10544
10545 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10546                                             SelectionDAG &DAG) const {
10547   EVT SrcVT = Op.getOperand(0).getValueType();
10548   EVT DstVT = Op.getValueType();
10549   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10550          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10551   assert((DstVT == MVT::i64 ||
10552           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10553          "Unexpected custom BITCAST");
10554   // i64 <=> MMX conversions are Legal.
10555   if (SrcVT==MVT::i64 && DstVT.isVector())
10556     return Op;
10557   if (DstVT==MVT::i64 && SrcVT.isVector())
10558     return Op;
10559   // MMX <=> MMX conversions are Legal.
10560   if (SrcVT.isVector() && DstVT.isVector())
10561     return Op;
10562   // All other conversions need to be expanded.
10563   return SDValue();
10564 }
10565
10566 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10567   SDNode *Node = Op.getNode();
10568   DebugLoc dl = Node->getDebugLoc();
10569   EVT T = Node->getValueType(0);
10570   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10571                               DAG.getConstant(0, T), Node->getOperand(2));
10572   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10573                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10574                        Node->getOperand(0),
10575                        Node->getOperand(1), negOp,
10576                        cast<AtomicSDNode>(Node)->getSrcValue(),
10577                        cast<AtomicSDNode>(Node)->getAlignment(),
10578                        cast<AtomicSDNode>(Node)->getOrdering(),
10579                        cast<AtomicSDNode>(Node)->getSynchScope());
10580 }
10581
10582 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10583   SDNode *Node = Op.getNode();
10584   DebugLoc dl = Node->getDebugLoc();
10585   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10586
10587   // Convert seq_cst store -> xchg
10588   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10589   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10590   //        (The only way to get a 16-byte store is cmpxchg16b)
10591   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10592   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10593       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10594     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10595                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10596                                  Node->getOperand(0),
10597                                  Node->getOperand(1), Node->getOperand(2),
10598                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10599                                  cast<AtomicSDNode>(Node)->getOrdering(),
10600                                  cast<AtomicSDNode>(Node)->getSynchScope());
10601     return Swap.getValue(1);
10602   }
10603   // Other atomic stores have a simple pattern.
10604   return Op;
10605 }
10606
10607 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10608   EVT VT = Op.getNode()->getValueType(0);
10609
10610   // Let legalize expand this if it isn't a legal type yet.
10611   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10612     return SDValue();
10613
10614   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10615
10616   unsigned Opc;
10617   bool ExtraOp = false;
10618   switch (Op.getOpcode()) {
10619   default: assert(0 && "Invalid code");
10620   case ISD::ADDC: Opc = X86ISD::ADD; break;
10621   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10622   case ISD::SUBC: Opc = X86ISD::SUB; break;
10623   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10624   }
10625
10626   if (!ExtraOp)
10627     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10628                        Op.getOperand(1));
10629   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10630                      Op.getOperand(1), Op.getOperand(2));
10631 }
10632
10633 /// LowerOperation - Provide custom lowering hooks for some operations.
10634 ///
10635 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10636   switch (Op.getOpcode()) {
10637   default: llvm_unreachable("Should not custom lower this!");
10638   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10639   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10640   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10641   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10642   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10643   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10644   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10645   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10646   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10647   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10648   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10649   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10650   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10651   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10652   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10653   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10654   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10655   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10656   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10657   case ISD::SHL_PARTS:
10658   case ISD::SRA_PARTS:
10659   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10660   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10661   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10662   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10663   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10664   case ISD::FABS:               return LowerFABS(Op, DAG);
10665   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10666   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10667   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10668   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10669   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10670   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10671   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10672   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10673   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10674   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10675   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10676   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10677   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10678   case ISD::FRAME_TO_ARGS_OFFSET:
10679                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10680   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10681   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10682   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10683   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10684   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10685   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10686   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10687   case ISD::MUL:                return LowerMUL(Op, DAG);
10688   case ISD::SRA:
10689   case ISD::SRL:
10690   case ISD::SHL:                return LowerShift(Op, DAG);
10691   case ISD::SADDO:
10692   case ISD::UADDO:
10693   case ISD::SSUBO:
10694   case ISD::USUBO:
10695   case ISD::SMULO:
10696   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10697   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10698   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10699   case ISD::ADDC:
10700   case ISD::ADDE:
10701   case ISD::SUBC:
10702   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10703   case ISD::ADD:                return LowerADD(Op, DAG);
10704   case ISD::SUB:                return LowerSUB(Op, DAG);
10705   }
10706 }
10707
10708 static void ReplaceATOMIC_LOAD(SDNode *Node,
10709                                   SmallVectorImpl<SDValue> &Results,
10710                                   SelectionDAG &DAG) {
10711   DebugLoc dl = Node->getDebugLoc();
10712   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10713
10714   // Convert wide load -> cmpxchg8b/cmpxchg16b
10715   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10716   //        (The only way to get a 16-byte load is cmpxchg16b)
10717   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10718   SDValue Zero = DAG.getConstant(0, VT);
10719   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10720                                Node->getOperand(0),
10721                                Node->getOperand(1), Zero, Zero,
10722                                cast<AtomicSDNode>(Node)->getMemOperand(),
10723                                cast<AtomicSDNode>(Node)->getOrdering(),
10724                                cast<AtomicSDNode>(Node)->getSynchScope());
10725   Results.push_back(Swap.getValue(0));
10726   Results.push_back(Swap.getValue(1));
10727 }
10728
10729 void X86TargetLowering::
10730 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10731                         SelectionDAG &DAG, unsigned NewOp) const {
10732   DebugLoc dl = Node->getDebugLoc();
10733   assert (Node->getValueType(0) == MVT::i64 &&
10734           "Only know how to expand i64 atomics");
10735
10736   SDValue Chain = Node->getOperand(0);
10737   SDValue In1 = Node->getOperand(1);
10738   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10739                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10740   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10741                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10742   SDValue Ops[] = { Chain, In1, In2L, In2H };
10743   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10744   SDValue Result =
10745     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10746                             cast<MemSDNode>(Node)->getMemOperand());
10747   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10748   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10749   Results.push_back(Result.getValue(2));
10750 }
10751
10752 /// ReplaceNodeResults - Replace a node with an illegal result type
10753 /// with a new node built out of custom code.
10754 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10755                                            SmallVectorImpl<SDValue>&Results,
10756                                            SelectionDAG &DAG) const {
10757   DebugLoc dl = N->getDebugLoc();
10758   switch (N->getOpcode()) {
10759   default:
10760     assert(false && "Do not know how to custom type legalize this operation!");
10761     return;
10762   case ISD::SIGN_EXTEND_INREG:
10763   case ISD::ADDC:
10764   case ISD::ADDE:
10765   case ISD::SUBC:
10766   case ISD::SUBE:
10767     // We don't want to expand or promote these.
10768     return;
10769   case ISD::FP_TO_SINT: {
10770     std::pair<SDValue,SDValue> Vals =
10771         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10772     SDValue FIST = Vals.first, StackSlot = Vals.second;
10773     if (FIST.getNode() != 0) {
10774       EVT VT = N->getValueType(0);
10775       // Return a load from the stack slot.
10776       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10777                                     MachinePointerInfo(), 
10778                                     false, false, false, 0));
10779     }
10780     return;
10781   }
10782   case ISD::READCYCLECOUNTER: {
10783     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10784     SDValue TheChain = N->getOperand(0);
10785     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10786     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10787                                      rd.getValue(1));
10788     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10789                                      eax.getValue(2));
10790     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10791     SDValue Ops[] = { eax, edx };
10792     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10793     Results.push_back(edx.getValue(1));
10794     return;
10795   }
10796   case ISD::ATOMIC_CMP_SWAP: {
10797     EVT T = N->getValueType(0);
10798     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10799     bool Regs64bit = T == MVT::i128;
10800     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10801     SDValue cpInL, cpInH;
10802     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10803                         DAG.getConstant(0, HalfT));
10804     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10805                         DAG.getConstant(1, HalfT));
10806     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10807                              Regs64bit ? X86::RAX : X86::EAX,
10808                              cpInL, SDValue());
10809     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10810                              Regs64bit ? X86::RDX : X86::EDX,
10811                              cpInH, cpInL.getValue(1));
10812     SDValue swapInL, swapInH;
10813     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10814                           DAG.getConstant(0, HalfT));
10815     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10816                           DAG.getConstant(1, HalfT));
10817     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10818                                Regs64bit ? X86::RBX : X86::EBX,
10819                                swapInL, cpInH.getValue(1));
10820     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10821                                Regs64bit ? X86::RCX : X86::ECX, 
10822                                swapInH, swapInL.getValue(1));
10823     SDValue Ops[] = { swapInH.getValue(0),
10824                       N->getOperand(1),
10825                       swapInH.getValue(1) };
10826     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10827     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10828     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10829                                   X86ISD::LCMPXCHG8_DAG;
10830     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10831                                              Ops, 3, T, MMO);
10832     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10833                                         Regs64bit ? X86::RAX : X86::EAX,
10834                                         HalfT, Result.getValue(1));
10835     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10836                                         Regs64bit ? X86::RDX : X86::EDX,
10837                                         HalfT, cpOutL.getValue(2));
10838     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10839     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10840     Results.push_back(cpOutH.getValue(1));
10841     return;
10842   }
10843   case ISD::ATOMIC_LOAD_ADD:
10844     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10845     return;
10846   case ISD::ATOMIC_LOAD_AND:
10847     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10848     return;
10849   case ISD::ATOMIC_LOAD_NAND:
10850     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10851     return;
10852   case ISD::ATOMIC_LOAD_OR:
10853     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10854     return;
10855   case ISD::ATOMIC_LOAD_SUB:
10856     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10857     return;
10858   case ISD::ATOMIC_LOAD_XOR:
10859     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10860     return;
10861   case ISD::ATOMIC_SWAP:
10862     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10863     return;
10864   case ISD::ATOMIC_LOAD:
10865     ReplaceATOMIC_LOAD(N, Results, DAG);
10866   }
10867 }
10868
10869 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10870   switch (Opcode) {
10871   default: return NULL;
10872   case X86ISD::BSF:                return "X86ISD::BSF";
10873   case X86ISD::BSR:                return "X86ISD::BSR";
10874   case X86ISD::SHLD:               return "X86ISD::SHLD";
10875   case X86ISD::SHRD:               return "X86ISD::SHRD";
10876   case X86ISD::FAND:               return "X86ISD::FAND";
10877   case X86ISD::FOR:                return "X86ISD::FOR";
10878   case X86ISD::FXOR:               return "X86ISD::FXOR";
10879   case X86ISD::FSRL:               return "X86ISD::FSRL";
10880   case X86ISD::FILD:               return "X86ISD::FILD";
10881   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10882   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10883   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10884   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10885   case X86ISD::FLD:                return "X86ISD::FLD";
10886   case X86ISD::FST:                return "X86ISD::FST";
10887   case X86ISD::CALL:               return "X86ISD::CALL";
10888   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10889   case X86ISD::BT:                 return "X86ISD::BT";
10890   case X86ISD::CMP:                return "X86ISD::CMP";
10891   case X86ISD::COMI:               return "X86ISD::COMI";
10892   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10893   case X86ISD::SETCC:              return "X86ISD::SETCC";
10894   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10895   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10896   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10897   case X86ISD::CMOV:               return "X86ISD::CMOV";
10898   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10899   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10900   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10901   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10902   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10903   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10904   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10905   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10906   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10907   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10908   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10909   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10910   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10911   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10912   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
10913   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
10914   case X86ISD::HADD:               return "X86ISD::HADD";
10915   case X86ISD::HSUB:               return "X86ISD::HSUB";
10916   case X86ISD::FHADD:              return "X86ISD::FHADD";
10917   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10918   case X86ISD::FMAX:               return "X86ISD::FMAX";
10919   case X86ISD::FMIN:               return "X86ISD::FMIN";
10920   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10921   case X86ISD::FRCP:               return "X86ISD::FRCP";
10922   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10923   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10924   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10925   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10926   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10927   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10928   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10929   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10930   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10931   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10932   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10933   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10934   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10935   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10936   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10937   case X86ISD::VSHL:               return "X86ISD::VSHL";
10938   case X86ISD::VSRL:               return "X86ISD::VSRL";
10939   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10940   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10941   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10942   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10943   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10944   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10945   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10946   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10947   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10948   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10949   case X86ISD::ADD:                return "X86ISD::ADD";
10950   case X86ISD::SUB:                return "X86ISD::SUB";
10951   case X86ISD::ADC:                return "X86ISD::ADC";
10952   case X86ISD::SBB:                return "X86ISD::SBB";
10953   case X86ISD::SMUL:               return "X86ISD::SMUL";
10954   case X86ISD::UMUL:               return "X86ISD::UMUL";
10955   case X86ISD::INC:                return "X86ISD::INC";
10956   case X86ISD::DEC:                return "X86ISD::DEC";
10957   case X86ISD::OR:                 return "X86ISD::OR";
10958   case X86ISD::XOR:                return "X86ISD::XOR";
10959   case X86ISD::AND:                return "X86ISD::AND";
10960   case X86ISD::ANDN:               return "X86ISD::ANDN";
10961   case X86ISD::BLSI:               return "X86ISD::BLSI";
10962   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
10963   case X86ISD::BLSR:               return "X86ISD::BLSR";
10964   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10965   case X86ISD::PTEST:              return "X86ISD::PTEST";
10966   case X86ISD::TESTP:              return "X86ISD::TESTP";
10967   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10968   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10969   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10970   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10971   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10972   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10973   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10974   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10975   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10976   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10977   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10978   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10979   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10980   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10981   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10982   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10983   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10984   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10985   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10986   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10987   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10988   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
10989   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
10990   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10991   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
10992   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
10993   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10994   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10995   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10996   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10997   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10998   }
10999 }
11000
11001 // isLegalAddressingMode - Return true if the addressing mode represented
11002 // by AM is legal for this target, for a load/store of the specified type.
11003 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11004                                               Type *Ty) const {
11005   // X86 supports extremely general addressing modes.
11006   CodeModel::Model M = getTargetMachine().getCodeModel();
11007   Reloc::Model R = getTargetMachine().getRelocationModel();
11008
11009   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11010   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11011     return false;
11012
11013   if (AM.BaseGV) {
11014     unsigned GVFlags =
11015       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11016
11017     // If a reference to this global requires an extra load, we can't fold it.
11018     if (isGlobalStubReference(GVFlags))
11019       return false;
11020
11021     // If BaseGV requires a register for the PIC base, we cannot also have a
11022     // BaseReg specified.
11023     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11024       return false;
11025
11026     // If lower 4G is not available, then we must use rip-relative addressing.
11027     if ((M != CodeModel::Small || R != Reloc::Static) &&
11028         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11029       return false;
11030   }
11031
11032   switch (AM.Scale) {
11033   case 0:
11034   case 1:
11035   case 2:
11036   case 4:
11037   case 8:
11038     // These scales always work.
11039     break;
11040   case 3:
11041   case 5:
11042   case 9:
11043     // These scales are formed with basereg+scalereg.  Only accept if there is
11044     // no basereg yet.
11045     if (AM.HasBaseReg)
11046       return false;
11047     break;
11048   default:  // Other stuff never works.
11049     return false;
11050   }
11051
11052   return true;
11053 }
11054
11055
11056 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11057   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11058     return false;
11059   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11060   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11061   if (NumBits1 <= NumBits2)
11062     return false;
11063   return true;
11064 }
11065
11066 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11067   if (!VT1.isInteger() || !VT2.isInteger())
11068     return false;
11069   unsigned NumBits1 = VT1.getSizeInBits();
11070   unsigned NumBits2 = VT2.getSizeInBits();
11071   if (NumBits1 <= NumBits2)
11072     return false;
11073   return true;
11074 }
11075
11076 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11077   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11078   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11079 }
11080
11081 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11082   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11083   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11084 }
11085
11086 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11087   // i16 instructions are longer (0x66 prefix) and potentially slower.
11088   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11089 }
11090
11091 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11092 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11093 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11094 /// are assumed to be legal.
11095 bool
11096 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11097                                       EVT VT) const {
11098   // Very little shuffling can be done for 64-bit vectors right now.
11099   if (VT.getSizeInBits() == 64)
11100     return false;
11101
11102   // FIXME: pshufb, blends, shifts.
11103   return (VT.getVectorNumElements() == 2 ||
11104           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11105           isMOVLMask(M, VT) ||
11106           isSHUFPMask(M, VT) ||
11107           isPSHUFDMask(M, VT) ||
11108           isPSHUFHWMask(M, VT) ||
11109           isPSHUFLWMask(M, VT) ||
11110           isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11111           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11112           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11113           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11114           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11115 }
11116
11117 bool
11118 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11119                                           EVT VT) const {
11120   unsigned NumElts = VT.getVectorNumElements();
11121   // FIXME: This collection of masks seems suspect.
11122   if (NumElts == 2)
11123     return true;
11124   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11125     return (isMOVLMask(Mask, VT)  ||
11126             isCommutedMOVLMask(Mask, VT, true) ||
11127             isSHUFPMask(Mask, VT) ||
11128             isSHUFPMask(Mask, VT, /* Commuted */ true));
11129   }
11130   return false;
11131 }
11132
11133 //===----------------------------------------------------------------------===//
11134 //                           X86 Scheduler Hooks
11135 //===----------------------------------------------------------------------===//
11136
11137 // private utility function
11138 MachineBasicBlock *
11139 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11140                                                        MachineBasicBlock *MBB,
11141                                                        unsigned regOpc,
11142                                                        unsigned immOpc,
11143                                                        unsigned LoadOpc,
11144                                                        unsigned CXchgOpc,
11145                                                        unsigned notOpc,
11146                                                        unsigned EAXreg,
11147                                                        TargetRegisterClass *RC,
11148                                                        bool invSrc) const {
11149   // For the atomic bitwise operator, we generate
11150   //   thisMBB:
11151   //   newMBB:
11152   //     ld  t1 = [bitinstr.addr]
11153   //     op  t2 = t1, [bitinstr.val]
11154   //     mov EAX = t1
11155   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11156   //     bz  newMBB
11157   //     fallthrough -->nextMBB
11158   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11159   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11160   MachineFunction::iterator MBBIter = MBB;
11161   ++MBBIter;
11162
11163   /// First build the CFG
11164   MachineFunction *F = MBB->getParent();
11165   MachineBasicBlock *thisMBB = MBB;
11166   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11168   F->insert(MBBIter, newMBB);
11169   F->insert(MBBIter, nextMBB);
11170
11171   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11172   nextMBB->splice(nextMBB->begin(), thisMBB,
11173                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11174                   thisMBB->end());
11175   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11176
11177   // Update thisMBB to fall through to newMBB
11178   thisMBB->addSuccessor(newMBB);
11179
11180   // newMBB jumps to itself and fall through to nextMBB
11181   newMBB->addSuccessor(nextMBB);
11182   newMBB->addSuccessor(newMBB);
11183
11184   // Insert instructions into newMBB based on incoming instruction
11185   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11186          "unexpected number of operands");
11187   DebugLoc dl = bInstr->getDebugLoc();
11188   MachineOperand& destOper = bInstr->getOperand(0);
11189   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11190   int numArgs = bInstr->getNumOperands() - 1;
11191   for (int i=0; i < numArgs; ++i)
11192     argOpers[i] = &bInstr->getOperand(i+1);
11193
11194   // x86 address has 4 operands: base, index, scale, and displacement
11195   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11196   int valArgIndx = lastAddrIndx + 1;
11197
11198   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11199   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11200   for (int i=0; i <= lastAddrIndx; ++i)
11201     (*MIB).addOperand(*argOpers[i]);
11202
11203   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11204   if (invSrc) {
11205     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11206   }
11207   else
11208     tt = t1;
11209
11210   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11211   assert((argOpers[valArgIndx]->isReg() ||
11212           argOpers[valArgIndx]->isImm()) &&
11213          "invalid operand");
11214   if (argOpers[valArgIndx]->isReg())
11215     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11216   else
11217     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11218   MIB.addReg(tt);
11219   (*MIB).addOperand(*argOpers[valArgIndx]);
11220
11221   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11222   MIB.addReg(t1);
11223
11224   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11225   for (int i=0; i <= lastAddrIndx; ++i)
11226     (*MIB).addOperand(*argOpers[i]);
11227   MIB.addReg(t2);
11228   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11229   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11230                     bInstr->memoperands_end());
11231
11232   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11233   MIB.addReg(EAXreg);
11234
11235   // insert branch
11236   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11237
11238   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11239   return nextMBB;
11240 }
11241
11242 // private utility function:  64 bit atomics on 32 bit host.
11243 MachineBasicBlock *
11244 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11245                                                        MachineBasicBlock *MBB,
11246                                                        unsigned regOpcL,
11247                                                        unsigned regOpcH,
11248                                                        unsigned immOpcL,
11249                                                        unsigned immOpcH,
11250                                                        bool invSrc) const {
11251   // For the atomic bitwise operator, we generate
11252   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11253   //     ld t1,t2 = [bitinstr.addr]
11254   //   newMBB:
11255   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11256   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11257   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11258   //     mov ECX, EBX <- t5, t6
11259   //     mov EAX, EDX <- t1, t2
11260   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11261   //     mov t3, t4 <- EAX, EDX
11262   //     bz  newMBB
11263   //     result in out1, out2
11264   //     fallthrough -->nextMBB
11265
11266   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11267   const unsigned LoadOpc = X86::MOV32rm;
11268   const unsigned NotOpc = X86::NOT32r;
11269   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11270   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11271   MachineFunction::iterator MBBIter = MBB;
11272   ++MBBIter;
11273
11274   /// First build the CFG
11275   MachineFunction *F = MBB->getParent();
11276   MachineBasicBlock *thisMBB = MBB;
11277   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11278   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11279   F->insert(MBBIter, newMBB);
11280   F->insert(MBBIter, nextMBB);
11281
11282   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11283   nextMBB->splice(nextMBB->begin(), thisMBB,
11284                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11285                   thisMBB->end());
11286   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11287
11288   // Update thisMBB to fall through to newMBB
11289   thisMBB->addSuccessor(newMBB);
11290
11291   // newMBB jumps to itself and fall through to nextMBB
11292   newMBB->addSuccessor(nextMBB);
11293   newMBB->addSuccessor(newMBB);
11294
11295   DebugLoc dl = bInstr->getDebugLoc();
11296   // Insert instructions into newMBB based on incoming instruction
11297   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11298   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11299          "unexpected number of operands");
11300   MachineOperand& dest1Oper = bInstr->getOperand(0);
11301   MachineOperand& dest2Oper = bInstr->getOperand(1);
11302   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11303   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11304     argOpers[i] = &bInstr->getOperand(i+2);
11305
11306     // We use some of the operands multiple times, so conservatively just
11307     // clear any kill flags that might be present.
11308     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11309       argOpers[i]->setIsKill(false);
11310   }
11311
11312   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11313   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11314
11315   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11316   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11317   for (int i=0; i <= lastAddrIndx; ++i)
11318     (*MIB).addOperand(*argOpers[i]);
11319   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11320   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11321   // add 4 to displacement.
11322   for (int i=0; i <= lastAddrIndx-2; ++i)
11323     (*MIB).addOperand(*argOpers[i]);
11324   MachineOperand newOp3 = *(argOpers[3]);
11325   if (newOp3.isImm())
11326     newOp3.setImm(newOp3.getImm()+4);
11327   else
11328     newOp3.setOffset(newOp3.getOffset()+4);
11329   (*MIB).addOperand(newOp3);
11330   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11331
11332   // t3/4 are defined later, at the bottom of the loop
11333   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11334   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11335   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11336     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11337   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11338     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11339
11340   // The subsequent operations should be using the destination registers of
11341   //the PHI instructions.
11342   if (invSrc) {
11343     t1 = F->getRegInfo().createVirtualRegister(RC);
11344     t2 = F->getRegInfo().createVirtualRegister(RC);
11345     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11346     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11347   } else {
11348     t1 = dest1Oper.getReg();
11349     t2 = dest2Oper.getReg();
11350   }
11351
11352   int valArgIndx = lastAddrIndx + 1;
11353   assert((argOpers[valArgIndx]->isReg() ||
11354           argOpers[valArgIndx]->isImm()) &&
11355          "invalid operand");
11356   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11357   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11358   if (argOpers[valArgIndx]->isReg())
11359     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11360   else
11361     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11362   if (regOpcL != X86::MOV32rr)
11363     MIB.addReg(t1);
11364   (*MIB).addOperand(*argOpers[valArgIndx]);
11365   assert(argOpers[valArgIndx + 1]->isReg() ==
11366          argOpers[valArgIndx]->isReg());
11367   assert(argOpers[valArgIndx + 1]->isImm() ==
11368          argOpers[valArgIndx]->isImm());
11369   if (argOpers[valArgIndx + 1]->isReg())
11370     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11371   else
11372     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11373   if (regOpcH != X86::MOV32rr)
11374     MIB.addReg(t2);
11375   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11376
11377   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11378   MIB.addReg(t1);
11379   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11380   MIB.addReg(t2);
11381
11382   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11383   MIB.addReg(t5);
11384   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11385   MIB.addReg(t6);
11386
11387   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11388   for (int i=0; i <= lastAddrIndx; ++i)
11389     (*MIB).addOperand(*argOpers[i]);
11390
11391   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11392   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11393                     bInstr->memoperands_end());
11394
11395   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11396   MIB.addReg(X86::EAX);
11397   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11398   MIB.addReg(X86::EDX);
11399
11400   // insert branch
11401   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11402
11403   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11404   return nextMBB;
11405 }
11406
11407 // private utility function
11408 MachineBasicBlock *
11409 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11410                                                       MachineBasicBlock *MBB,
11411                                                       unsigned cmovOpc) const {
11412   // For the atomic min/max operator, we generate
11413   //   thisMBB:
11414   //   newMBB:
11415   //     ld t1 = [min/max.addr]
11416   //     mov t2 = [min/max.val]
11417   //     cmp  t1, t2
11418   //     cmov[cond] t2 = t1
11419   //     mov EAX = t1
11420   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11421   //     bz   newMBB
11422   //     fallthrough -->nextMBB
11423   //
11424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11425   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11426   MachineFunction::iterator MBBIter = MBB;
11427   ++MBBIter;
11428
11429   /// First build the CFG
11430   MachineFunction *F = MBB->getParent();
11431   MachineBasicBlock *thisMBB = MBB;
11432   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11433   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11434   F->insert(MBBIter, newMBB);
11435   F->insert(MBBIter, nextMBB);
11436
11437   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11438   nextMBB->splice(nextMBB->begin(), thisMBB,
11439                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11440                   thisMBB->end());
11441   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11442
11443   // Update thisMBB to fall through to newMBB
11444   thisMBB->addSuccessor(newMBB);
11445
11446   // newMBB jumps to newMBB and fall through to nextMBB
11447   newMBB->addSuccessor(nextMBB);
11448   newMBB->addSuccessor(newMBB);
11449
11450   DebugLoc dl = mInstr->getDebugLoc();
11451   // Insert instructions into newMBB based on incoming instruction
11452   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11453          "unexpected number of operands");
11454   MachineOperand& destOper = mInstr->getOperand(0);
11455   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11456   int numArgs = mInstr->getNumOperands() - 1;
11457   for (int i=0; i < numArgs; ++i)
11458     argOpers[i] = &mInstr->getOperand(i+1);
11459
11460   // x86 address has 4 operands: base, index, scale, and displacement
11461   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11462   int valArgIndx = lastAddrIndx + 1;
11463
11464   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11465   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11466   for (int i=0; i <= lastAddrIndx; ++i)
11467     (*MIB).addOperand(*argOpers[i]);
11468
11469   // We only support register and immediate values
11470   assert((argOpers[valArgIndx]->isReg() ||
11471           argOpers[valArgIndx]->isImm()) &&
11472          "invalid operand");
11473
11474   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11475   if (argOpers[valArgIndx]->isReg())
11476     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11477   else
11478     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11479   (*MIB).addOperand(*argOpers[valArgIndx]);
11480
11481   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11482   MIB.addReg(t1);
11483
11484   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11485   MIB.addReg(t1);
11486   MIB.addReg(t2);
11487
11488   // Generate movc
11489   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11490   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11491   MIB.addReg(t2);
11492   MIB.addReg(t1);
11493
11494   // Cmp and exchange if none has modified the memory location
11495   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11496   for (int i=0; i <= lastAddrIndx; ++i)
11497     (*MIB).addOperand(*argOpers[i]);
11498   MIB.addReg(t3);
11499   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11500   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11501                     mInstr->memoperands_end());
11502
11503   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11504   MIB.addReg(X86::EAX);
11505
11506   // insert branch
11507   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11508
11509   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11510   return nextMBB;
11511 }
11512
11513 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11514 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11515 // in the .td file.
11516 MachineBasicBlock *
11517 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11518                             unsigned numArgs, bool memArg) const {
11519   assert(Subtarget->hasSSE42orAVX() &&
11520          "Target must have SSE4.2 or AVX features enabled");
11521
11522   DebugLoc dl = MI->getDebugLoc();
11523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11524   unsigned Opc;
11525   if (!Subtarget->hasAVX()) {
11526     if (memArg)
11527       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11528     else
11529       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11530   } else {
11531     if (memArg)
11532       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11533     else
11534       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11535   }
11536
11537   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11538   for (unsigned i = 0; i < numArgs; ++i) {
11539     MachineOperand &Op = MI->getOperand(i+1);
11540     if (!(Op.isReg() && Op.isImplicit()))
11541       MIB.addOperand(Op);
11542   }
11543   BuildMI(*BB, MI, dl,
11544     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11545              MI->getOperand(0).getReg())
11546     .addReg(X86::XMM0);
11547
11548   MI->eraseFromParent();
11549   return BB;
11550 }
11551
11552 MachineBasicBlock *
11553 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11554   DebugLoc dl = MI->getDebugLoc();
11555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11556
11557   // Address into RAX/EAX, other two args into ECX, EDX.
11558   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11559   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11560   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11561   for (int i = 0; i < X86::AddrNumOperands; ++i)
11562     MIB.addOperand(MI->getOperand(i));
11563
11564   unsigned ValOps = X86::AddrNumOperands;
11565   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11566     .addReg(MI->getOperand(ValOps).getReg());
11567   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11568     .addReg(MI->getOperand(ValOps+1).getReg());
11569
11570   // The instruction doesn't actually take any operands though.
11571   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11572
11573   MI->eraseFromParent(); // The pseudo is gone now.
11574   return BB;
11575 }
11576
11577 MachineBasicBlock *
11578 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11579   DebugLoc dl = MI->getDebugLoc();
11580   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11581
11582   // First arg in ECX, the second in EAX.
11583   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11584     .addReg(MI->getOperand(0).getReg());
11585   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11586     .addReg(MI->getOperand(1).getReg());
11587
11588   // The instruction doesn't actually take any operands though.
11589   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11590
11591   MI->eraseFromParent(); // The pseudo is gone now.
11592   return BB;
11593 }
11594
11595 MachineBasicBlock *
11596 X86TargetLowering::EmitVAARG64WithCustomInserter(
11597                    MachineInstr *MI,
11598                    MachineBasicBlock *MBB) const {
11599   // Emit va_arg instruction on X86-64.
11600
11601   // Operands to this pseudo-instruction:
11602   // 0  ) Output        : destination address (reg)
11603   // 1-5) Input         : va_list address (addr, i64mem)
11604   // 6  ) ArgSize       : Size (in bytes) of vararg type
11605   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11606   // 8  ) Align         : Alignment of type
11607   // 9  ) EFLAGS (implicit-def)
11608
11609   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11610   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11611
11612   unsigned DestReg = MI->getOperand(0).getReg();
11613   MachineOperand &Base = MI->getOperand(1);
11614   MachineOperand &Scale = MI->getOperand(2);
11615   MachineOperand &Index = MI->getOperand(3);
11616   MachineOperand &Disp = MI->getOperand(4);
11617   MachineOperand &Segment = MI->getOperand(5);
11618   unsigned ArgSize = MI->getOperand(6).getImm();
11619   unsigned ArgMode = MI->getOperand(7).getImm();
11620   unsigned Align = MI->getOperand(8).getImm();
11621
11622   // Memory Reference
11623   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11624   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11625   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11626
11627   // Machine Information
11628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11629   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11630   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11631   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11632   DebugLoc DL = MI->getDebugLoc();
11633
11634   // struct va_list {
11635   //   i32   gp_offset
11636   //   i32   fp_offset
11637   //   i64   overflow_area (address)
11638   //   i64   reg_save_area (address)
11639   // }
11640   // sizeof(va_list) = 24
11641   // alignment(va_list) = 8
11642
11643   unsigned TotalNumIntRegs = 6;
11644   unsigned TotalNumXMMRegs = 8;
11645   bool UseGPOffset = (ArgMode == 1);
11646   bool UseFPOffset = (ArgMode == 2);
11647   unsigned MaxOffset = TotalNumIntRegs * 8 +
11648                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11649
11650   /* Align ArgSize to a multiple of 8 */
11651   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11652   bool NeedsAlign = (Align > 8);
11653
11654   MachineBasicBlock *thisMBB = MBB;
11655   MachineBasicBlock *overflowMBB;
11656   MachineBasicBlock *offsetMBB;
11657   MachineBasicBlock *endMBB;
11658
11659   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11660   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11661   unsigned OffsetReg = 0;
11662
11663   if (!UseGPOffset && !UseFPOffset) {
11664     // If we only pull from the overflow region, we don't create a branch.
11665     // We don't need to alter control flow.
11666     OffsetDestReg = 0; // unused
11667     OverflowDestReg = DestReg;
11668
11669     offsetMBB = NULL;
11670     overflowMBB = thisMBB;
11671     endMBB = thisMBB;
11672   } else {
11673     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11674     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11675     // If not, pull from overflow_area. (branch to overflowMBB)
11676     //
11677     //       thisMBB
11678     //         |     .
11679     //         |        .
11680     //     offsetMBB   overflowMBB
11681     //         |        .
11682     //         |     .
11683     //        endMBB
11684
11685     // Registers for the PHI in endMBB
11686     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11687     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11688
11689     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11690     MachineFunction *MF = MBB->getParent();
11691     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11692     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11693     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11694
11695     MachineFunction::iterator MBBIter = MBB;
11696     ++MBBIter;
11697
11698     // Insert the new basic blocks
11699     MF->insert(MBBIter, offsetMBB);
11700     MF->insert(MBBIter, overflowMBB);
11701     MF->insert(MBBIter, endMBB);
11702
11703     // Transfer the remainder of MBB and its successor edges to endMBB.
11704     endMBB->splice(endMBB->begin(), thisMBB,
11705                     llvm::next(MachineBasicBlock::iterator(MI)),
11706                     thisMBB->end());
11707     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11708
11709     // Make offsetMBB and overflowMBB successors of thisMBB
11710     thisMBB->addSuccessor(offsetMBB);
11711     thisMBB->addSuccessor(overflowMBB);
11712
11713     // endMBB is a successor of both offsetMBB and overflowMBB
11714     offsetMBB->addSuccessor(endMBB);
11715     overflowMBB->addSuccessor(endMBB);
11716
11717     // Load the offset value into a register
11718     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11719     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11720       .addOperand(Base)
11721       .addOperand(Scale)
11722       .addOperand(Index)
11723       .addDisp(Disp, UseFPOffset ? 4 : 0)
11724       .addOperand(Segment)
11725       .setMemRefs(MMOBegin, MMOEnd);
11726
11727     // Check if there is enough room left to pull this argument.
11728     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11729       .addReg(OffsetReg)
11730       .addImm(MaxOffset + 8 - ArgSizeA8);
11731
11732     // Branch to "overflowMBB" if offset >= max
11733     // Fall through to "offsetMBB" otherwise
11734     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11735       .addMBB(overflowMBB);
11736   }
11737
11738   // In offsetMBB, emit code to use the reg_save_area.
11739   if (offsetMBB) {
11740     assert(OffsetReg != 0);
11741
11742     // Read the reg_save_area address.
11743     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11744     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11745       .addOperand(Base)
11746       .addOperand(Scale)
11747       .addOperand(Index)
11748       .addDisp(Disp, 16)
11749       .addOperand(Segment)
11750       .setMemRefs(MMOBegin, MMOEnd);
11751
11752     // Zero-extend the offset
11753     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11754       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11755         .addImm(0)
11756         .addReg(OffsetReg)
11757         .addImm(X86::sub_32bit);
11758
11759     // Add the offset to the reg_save_area to get the final address.
11760     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11761       .addReg(OffsetReg64)
11762       .addReg(RegSaveReg);
11763
11764     // Compute the offset for the next argument
11765     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11766     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11767       .addReg(OffsetReg)
11768       .addImm(UseFPOffset ? 16 : 8);
11769
11770     // Store it back into the va_list.
11771     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11772       .addOperand(Base)
11773       .addOperand(Scale)
11774       .addOperand(Index)
11775       .addDisp(Disp, UseFPOffset ? 4 : 0)
11776       .addOperand(Segment)
11777       .addReg(NextOffsetReg)
11778       .setMemRefs(MMOBegin, MMOEnd);
11779
11780     // Jump to endMBB
11781     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11782       .addMBB(endMBB);
11783   }
11784
11785   //
11786   // Emit code to use overflow area
11787   //
11788
11789   // Load the overflow_area address into a register.
11790   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11791   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11792     .addOperand(Base)
11793     .addOperand(Scale)
11794     .addOperand(Index)
11795     .addDisp(Disp, 8)
11796     .addOperand(Segment)
11797     .setMemRefs(MMOBegin, MMOEnd);
11798
11799   // If we need to align it, do so. Otherwise, just copy the address
11800   // to OverflowDestReg.
11801   if (NeedsAlign) {
11802     // Align the overflow address
11803     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11804     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11805
11806     // aligned_addr = (addr + (align-1)) & ~(align-1)
11807     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11808       .addReg(OverflowAddrReg)
11809       .addImm(Align-1);
11810
11811     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11812       .addReg(TmpReg)
11813       .addImm(~(uint64_t)(Align-1));
11814   } else {
11815     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11816       .addReg(OverflowAddrReg);
11817   }
11818
11819   // Compute the next overflow address after this argument.
11820   // (the overflow address should be kept 8-byte aligned)
11821   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11822   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11823     .addReg(OverflowDestReg)
11824     .addImm(ArgSizeA8);
11825
11826   // Store the new overflow address.
11827   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11828     .addOperand(Base)
11829     .addOperand(Scale)
11830     .addOperand(Index)
11831     .addDisp(Disp, 8)
11832     .addOperand(Segment)
11833     .addReg(NextAddrReg)
11834     .setMemRefs(MMOBegin, MMOEnd);
11835
11836   // If we branched, emit the PHI to the front of endMBB.
11837   if (offsetMBB) {
11838     BuildMI(*endMBB, endMBB->begin(), DL,
11839             TII->get(X86::PHI), DestReg)
11840       .addReg(OffsetDestReg).addMBB(offsetMBB)
11841       .addReg(OverflowDestReg).addMBB(overflowMBB);
11842   }
11843
11844   // Erase the pseudo instruction
11845   MI->eraseFromParent();
11846
11847   return endMBB;
11848 }
11849
11850 MachineBasicBlock *
11851 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11852                                                  MachineInstr *MI,
11853                                                  MachineBasicBlock *MBB) const {
11854   // Emit code to save XMM registers to the stack. The ABI says that the
11855   // number of registers to save is given in %al, so it's theoretically
11856   // possible to do an indirect jump trick to avoid saving all of them,
11857   // however this code takes a simpler approach and just executes all
11858   // of the stores if %al is non-zero. It's less code, and it's probably
11859   // easier on the hardware branch predictor, and stores aren't all that
11860   // expensive anyway.
11861
11862   // Create the new basic blocks. One block contains all the XMM stores,
11863   // and one block is the final destination regardless of whether any
11864   // stores were performed.
11865   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11866   MachineFunction *F = MBB->getParent();
11867   MachineFunction::iterator MBBIter = MBB;
11868   ++MBBIter;
11869   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11870   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11871   F->insert(MBBIter, XMMSaveMBB);
11872   F->insert(MBBIter, EndMBB);
11873
11874   // Transfer the remainder of MBB and its successor edges to EndMBB.
11875   EndMBB->splice(EndMBB->begin(), MBB,
11876                  llvm::next(MachineBasicBlock::iterator(MI)),
11877                  MBB->end());
11878   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11879
11880   // The original block will now fall through to the XMM save block.
11881   MBB->addSuccessor(XMMSaveMBB);
11882   // The XMMSaveMBB will fall through to the end block.
11883   XMMSaveMBB->addSuccessor(EndMBB);
11884
11885   // Now add the instructions.
11886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887   DebugLoc DL = MI->getDebugLoc();
11888
11889   unsigned CountReg = MI->getOperand(0).getReg();
11890   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11891   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11892
11893   if (!Subtarget->isTargetWin64()) {
11894     // If %al is 0, branch around the XMM save block.
11895     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11896     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11897     MBB->addSuccessor(EndMBB);
11898   }
11899
11900   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11901   // In the XMM save block, save all the XMM argument registers.
11902   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11903     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11904     MachineMemOperand *MMO =
11905       F->getMachineMemOperand(
11906           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11907         MachineMemOperand::MOStore,
11908         /*Size=*/16, /*Align=*/16);
11909     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11910       .addFrameIndex(RegSaveFrameIndex)
11911       .addImm(/*Scale=*/1)
11912       .addReg(/*IndexReg=*/0)
11913       .addImm(/*Disp=*/Offset)
11914       .addReg(/*Segment=*/0)
11915       .addReg(MI->getOperand(i).getReg())
11916       .addMemOperand(MMO);
11917   }
11918
11919   MI->eraseFromParent();   // The pseudo instruction is gone now.
11920
11921   return EndMBB;
11922 }
11923
11924 MachineBasicBlock *
11925 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11926                                      MachineBasicBlock *BB) const {
11927   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11928   DebugLoc DL = MI->getDebugLoc();
11929
11930   // To "insert" a SELECT_CC instruction, we actually have to insert the
11931   // diamond control-flow pattern.  The incoming instruction knows the
11932   // destination vreg to set, the condition code register to branch on, the
11933   // true/false values to select between, and a branch opcode to use.
11934   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11935   MachineFunction::iterator It = BB;
11936   ++It;
11937
11938   //  thisMBB:
11939   //  ...
11940   //   TrueVal = ...
11941   //   cmpTY ccX, r1, r2
11942   //   bCC copy1MBB
11943   //   fallthrough --> copy0MBB
11944   MachineBasicBlock *thisMBB = BB;
11945   MachineFunction *F = BB->getParent();
11946   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11947   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11948   F->insert(It, copy0MBB);
11949   F->insert(It, sinkMBB);
11950
11951   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11952   // live into the sink and copy blocks.
11953   if (!MI->killsRegister(X86::EFLAGS)) {
11954     copy0MBB->addLiveIn(X86::EFLAGS);
11955     sinkMBB->addLiveIn(X86::EFLAGS);
11956   }
11957
11958   // Transfer the remainder of BB and its successor edges to sinkMBB.
11959   sinkMBB->splice(sinkMBB->begin(), BB,
11960                   llvm::next(MachineBasicBlock::iterator(MI)),
11961                   BB->end());
11962   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11963
11964   // Add the true and fallthrough blocks as its successors.
11965   BB->addSuccessor(copy0MBB);
11966   BB->addSuccessor(sinkMBB);
11967
11968   // Create the conditional branch instruction.
11969   unsigned Opc =
11970     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11971   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11972
11973   //  copy0MBB:
11974   //   %FalseValue = ...
11975   //   # fallthrough to sinkMBB
11976   copy0MBB->addSuccessor(sinkMBB);
11977
11978   //  sinkMBB:
11979   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11980   //  ...
11981   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11982           TII->get(X86::PHI), MI->getOperand(0).getReg())
11983     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11984     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11985
11986   MI->eraseFromParent();   // The pseudo instruction is gone now.
11987   return sinkMBB;
11988 }
11989
11990 MachineBasicBlock *
11991 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11992                                         bool Is64Bit) const {
11993   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11994   DebugLoc DL = MI->getDebugLoc();
11995   MachineFunction *MF = BB->getParent();
11996   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11997
11998   assert(getTargetMachine().Options.EnableSegmentedStacks);
11999
12000   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12001   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12002
12003   // BB:
12004   //  ... [Till the alloca]
12005   // If stacklet is not large enough, jump to mallocMBB
12006   //
12007   // bumpMBB:
12008   //  Allocate by subtracting from RSP
12009   //  Jump to continueMBB
12010   //
12011   // mallocMBB:
12012   //  Allocate by call to runtime
12013   //
12014   // continueMBB:
12015   //  ...
12016   //  [rest of original BB]
12017   //
12018
12019   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12020   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12021   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12022
12023   MachineRegisterInfo &MRI = MF->getRegInfo();
12024   const TargetRegisterClass *AddrRegClass =
12025     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12026
12027   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12028     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12029     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12030     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12031     sizeVReg = MI->getOperand(1).getReg(),
12032     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12033
12034   MachineFunction::iterator MBBIter = BB;
12035   ++MBBIter;
12036
12037   MF->insert(MBBIter, bumpMBB);
12038   MF->insert(MBBIter, mallocMBB);
12039   MF->insert(MBBIter, continueMBB);
12040
12041   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12042                       (MachineBasicBlock::iterator(MI)), BB->end());
12043   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12044
12045   // Add code to the main basic block to check if the stack limit has been hit,
12046   // and if so, jump to mallocMBB otherwise to bumpMBB.
12047   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12048   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12049     .addReg(tmpSPVReg).addReg(sizeVReg);
12050   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12051     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12052     .addReg(SPLimitVReg);
12053   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12054
12055   // bumpMBB simply decreases the stack pointer, since we know the current
12056   // stacklet has enough space.
12057   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12058     .addReg(SPLimitVReg);
12059   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12060     .addReg(SPLimitVReg);
12061   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12062
12063   // Calls into a routine in libgcc to allocate more space from the heap.
12064   if (Is64Bit) {
12065     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12066       .addReg(sizeVReg);
12067     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12068     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12069   } else {
12070     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12071       .addImm(12);
12072     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12073     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12074       .addExternalSymbol("__morestack_allocate_stack_space");
12075   }
12076
12077   if (!Is64Bit)
12078     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12079       .addImm(16);
12080
12081   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12082     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12083   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12084
12085   // Set up the CFG correctly.
12086   BB->addSuccessor(bumpMBB);
12087   BB->addSuccessor(mallocMBB);
12088   mallocMBB->addSuccessor(continueMBB);
12089   bumpMBB->addSuccessor(continueMBB);
12090
12091   // Take care of the PHI nodes.
12092   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12093           MI->getOperand(0).getReg())
12094     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12095     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12096
12097   // Delete the original pseudo instruction.
12098   MI->eraseFromParent();
12099
12100   // And we're done.
12101   return continueMBB;
12102 }
12103
12104 MachineBasicBlock *
12105 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12106                                           MachineBasicBlock *BB) const {
12107   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12108   DebugLoc DL = MI->getDebugLoc();
12109
12110   assert(!Subtarget->isTargetEnvMacho());
12111
12112   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12113   // non-trivial part is impdef of ESP.
12114
12115   if (Subtarget->isTargetWin64()) {
12116     if (Subtarget->isTargetCygMing()) {
12117       // ___chkstk(Mingw64):
12118       // Clobbers R10, R11, RAX and EFLAGS.
12119       // Updates RSP.
12120       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12121         .addExternalSymbol("___chkstk")
12122         .addReg(X86::RAX, RegState::Implicit)
12123         .addReg(X86::RSP, RegState::Implicit)
12124         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12125         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12126         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12127     } else {
12128       // __chkstk(MSVCRT): does not update stack pointer.
12129       // Clobbers R10, R11 and EFLAGS.
12130       // FIXME: RAX(allocated size) might be reused and not killed.
12131       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12132         .addExternalSymbol("__chkstk")
12133         .addReg(X86::RAX, RegState::Implicit)
12134         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12135       // RAX has the offset to subtracted from RSP.
12136       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12137         .addReg(X86::RSP)
12138         .addReg(X86::RAX);
12139     }
12140   } else {
12141     const char *StackProbeSymbol =
12142       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12143
12144     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12145       .addExternalSymbol(StackProbeSymbol)
12146       .addReg(X86::EAX, RegState::Implicit)
12147       .addReg(X86::ESP, RegState::Implicit)
12148       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12149       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12150       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12151   }
12152
12153   MI->eraseFromParent();   // The pseudo instruction is gone now.
12154   return BB;
12155 }
12156
12157 MachineBasicBlock *
12158 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12159                                       MachineBasicBlock *BB) const {
12160   // This is pretty easy.  We're taking the value that we received from
12161   // our load from the relocation, sticking it in either RDI (x86-64)
12162   // or EAX and doing an indirect call.  The return value will then
12163   // be in the normal return register.
12164   const X86InstrInfo *TII
12165     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12166   DebugLoc DL = MI->getDebugLoc();
12167   MachineFunction *F = BB->getParent();
12168
12169   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12170   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12171
12172   if (Subtarget->is64Bit()) {
12173     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12174                                       TII->get(X86::MOV64rm), X86::RDI)
12175     .addReg(X86::RIP)
12176     .addImm(0).addReg(0)
12177     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12178                       MI->getOperand(3).getTargetFlags())
12179     .addReg(0);
12180     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12181     addDirectMem(MIB, X86::RDI);
12182   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12183     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12184                                       TII->get(X86::MOV32rm), X86::EAX)
12185     .addReg(0)
12186     .addImm(0).addReg(0)
12187     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12188                       MI->getOperand(3).getTargetFlags())
12189     .addReg(0);
12190     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12191     addDirectMem(MIB, X86::EAX);
12192   } else {
12193     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12194                                       TII->get(X86::MOV32rm), X86::EAX)
12195     .addReg(TII->getGlobalBaseReg(F))
12196     .addImm(0).addReg(0)
12197     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12198                       MI->getOperand(3).getTargetFlags())
12199     .addReg(0);
12200     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12201     addDirectMem(MIB, X86::EAX);
12202   }
12203
12204   MI->eraseFromParent(); // The pseudo instruction is gone now.
12205   return BB;
12206 }
12207
12208 MachineBasicBlock *
12209 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12210                                                MachineBasicBlock *BB) const {
12211   switch (MI->getOpcode()) {
12212   default: assert(0 && "Unexpected instr type to insert");
12213   case X86::TAILJMPd64:
12214   case X86::TAILJMPr64:
12215   case X86::TAILJMPm64:
12216     assert(0 && "TAILJMP64 would not be touched here.");
12217   case X86::TCRETURNdi64:
12218   case X86::TCRETURNri64:
12219   case X86::TCRETURNmi64:
12220     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12221     // On AMD64, additional defs should be added before register allocation.
12222     if (!Subtarget->isTargetWin64()) {
12223       MI->addRegisterDefined(X86::RSI);
12224       MI->addRegisterDefined(X86::RDI);
12225       MI->addRegisterDefined(X86::XMM6);
12226       MI->addRegisterDefined(X86::XMM7);
12227       MI->addRegisterDefined(X86::XMM8);
12228       MI->addRegisterDefined(X86::XMM9);
12229       MI->addRegisterDefined(X86::XMM10);
12230       MI->addRegisterDefined(X86::XMM11);
12231       MI->addRegisterDefined(X86::XMM12);
12232       MI->addRegisterDefined(X86::XMM13);
12233       MI->addRegisterDefined(X86::XMM14);
12234       MI->addRegisterDefined(X86::XMM15);
12235     }
12236     return BB;
12237   case X86::WIN_ALLOCA:
12238     return EmitLoweredWinAlloca(MI, BB);
12239   case X86::SEG_ALLOCA_32:
12240     return EmitLoweredSegAlloca(MI, BB, false);
12241   case X86::SEG_ALLOCA_64:
12242     return EmitLoweredSegAlloca(MI, BB, true);
12243   case X86::TLSCall_32:
12244   case X86::TLSCall_64:
12245     return EmitLoweredTLSCall(MI, BB);
12246   case X86::CMOV_GR8:
12247   case X86::CMOV_FR32:
12248   case X86::CMOV_FR64:
12249   case X86::CMOV_V4F32:
12250   case X86::CMOV_V2F64:
12251   case X86::CMOV_V2I64:
12252   case X86::CMOV_V8F32:
12253   case X86::CMOV_V4F64:
12254   case X86::CMOV_V4I64:
12255   case X86::CMOV_GR16:
12256   case X86::CMOV_GR32:
12257   case X86::CMOV_RFP32:
12258   case X86::CMOV_RFP64:
12259   case X86::CMOV_RFP80:
12260     return EmitLoweredSelect(MI, BB);
12261
12262   case X86::FP32_TO_INT16_IN_MEM:
12263   case X86::FP32_TO_INT32_IN_MEM:
12264   case X86::FP32_TO_INT64_IN_MEM:
12265   case X86::FP64_TO_INT16_IN_MEM:
12266   case X86::FP64_TO_INT32_IN_MEM:
12267   case X86::FP64_TO_INT64_IN_MEM:
12268   case X86::FP80_TO_INT16_IN_MEM:
12269   case X86::FP80_TO_INT32_IN_MEM:
12270   case X86::FP80_TO_INT64_IN_MEM: {
12271     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272     DebugLoc DL = MI->getDebugLoc();
12273
12274     // Change the floating point control register to use "round towards zero"
12275     // mode when truncating to an integer value.
12276     MachineFunction *F = BB->getParent();
12277     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12278     addFrameReference(BuildMI(*BB, MI, DL,
12279                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12280
12281     // Load the old value of the high byte of the control word...
12282     unsigned OldCW =
12283       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12284     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12285                       CWFrameIdx);
12286
12287     // Set the high part to be round to zero...
12288     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12289       .addImm(0xC7F);
12290
12291     // Reload the modified control word now...
12292     addFrameReference(BuildMI(*BB, MI, DL,
12293                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12294
12295     // Restore the memory image of control word to original value
12296     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12297       .addReg(OldCW);
12298
12299     // Get the X86 opcode to use.
12300     unsigned Opc;
12301     switch (MI->getOpcode()) {
12302     default: llvm_unreachable("illegal opcode!");
12303     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12304     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12305     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12306     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12307     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12308     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12309     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12310     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12311     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12312     }
12313
12314     X86AddressMode AM;
12315     MachineOperand &Op = MI->getOperand(0);
12316     if (Op.isReg()) {
12317       AM.BaseType = X86AddressMode::RegBase;
12318       AM.Base.Reg = Op.getReg();
12319     } else {
12320       AM.BaseType = X86AddressMode::FrameIndexBase;
12321       AM.Base.FrameIndex = Op.getIndex();
12322     }
12323     Op = MI->getOperand(1);
12324     if (Op.isImm())
12325       AM.Scale = Op.getImm();
12326     Op = MI->getOperand(2);
12327     if (Op.isImm())
12328       AM.IndexReg = Op.getImm();
12329     Op = MI->getOperand(3);
12330     if (Op.isGlobal()) {
12331       AM.GV = Op.getGlobal();
12332     } else {
12333       AM.Disp = Op.getImm();
12334     }
12335     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12336                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12337
12338     // Reload the original control word now.
12339     addFrameReference(BuildMI(*BB, MI, DL,
12340                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12341
12342     MI->eraseFromParent();   // The pseudo instruction is gone now.
12343     return BB;
12344   }
12345     // String/text processing lowering.
12346   case X86::PCMPISTRM128REG:
12347   case X86::VPCMPISTRM128REG:
12348     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12349   case X86::PCMPISTRM128MEM:
12350   case X86::VPCMPISTRM128MEM:
12351     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12352   case X86::PCMPESTRM128REG:
12353   case X86::VPCMPESTRM128REG:
12354     return EmitPCMP(MI, BB, 5, false /* in mem */);
12355   case X86::PCMPESTRM128MEM:
12356   case X86::VPCMPESTRM128MEM:
12357     return EmitPCMP(MI, BB, 5, true /* in mem */);
12358
12359     // Thread synchronization.
12360   case X86::MONITOR:
12361     return EmitMonitor(MI, BB);
12362   case X86::MWAIT:
12363     return EmitMwait(MI, BB);
12364
12365     // Atomic Lowering.
12366   case X86::ATOMAND32:
12367     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12368                                                X86::AND32ri, X86::MOV32rm,
12369                                                X86::LCMPXCHG32,
12370                                                X86::NOT32r, X86::EAX,
12371                                                X86::GR32RegisterClass);
12372   case X86::ATOMOR32:
12373     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12374                                                X86::OR32ri, X86::MOV32rm,
12375                                                X86::LCMPXCHG32,
12376                                                X86::NOT32r, X86::EAX,
12377                                                X86::GR32RegisterClass);
12378   case X86::ATOMXOR32:
12379     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12380                                                X86::XOR32ri, X86::MOV32rm,
12381                                                X86::LCMPXCHG32,
12382                                                X86::NOT32r, X86::EAX,
12383                                                X86::GR32RegisterClass);
12384   case X86::ATOMNAND32:
12385     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12386                                                X86::AND32ri, X86::MOV32rm,
12387                                                X86::LCMPXCHG32,
12388                                                X86::NOT32r, X86::EAX,
12389                                                X86::GR32RegisterClass, true);
12390   case X86::ATOMMIN32:
12391     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12392   case X86::ATOMMAX32:
12393     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12394   case X86::ATOMUMIN32:
12395     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12396   case X86::ATOMUMAX32:
12397     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12398
12399   case X86::ATOMAND16:
12400     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12401                                                X86::AND16ri, X86::MOV16rm,
12402                                                X86::LCMPXCHG16,
12403                                                X86::NOT16r, X86::AX,
12404                                                X86::GR16RegisterClass);
12405   case X86::ATOMOR16:
12406     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12407                                                X86::OR16ri, X86::MOV16rm,
12408                                                X86::LCMPXCHG16,
12409                                                X86::NOT16r, X86::AX,
12410                                                X86::GR16RegisterClass);
12411   case X86::ATOMXOR16:
12412     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12413                                                X86::XOR16ri, X86::MOV16rm,
12414                                                X86::LCMPXCHG16,
12415                                                X86::NOT16r, X86::AX,
12416                                                X86::GR16RegisterClass);
12417   case X86::ATOMNAND16:
12418     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12419                                                X86::AND16ri, X86::MOV16rm,
12420                                                X86::LCMPXCHG16,
12421                                                X86::NOT16r, X86::AX,
12422                                                X86::GR16RegisterClass, true);
12423   case X86::ATOMMIN16:
12424     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12425   case X86::ATOMMAX16:
12426     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12427   case X86::ATOMUMIN16:
12428     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12429   case X86::ATOMUMAX16:
12430     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12431
12432   case X86::ATOMAND8:
12433     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12434                                                X86::AND8ri, X86::MOV8rm,
12435                                                X86::LCMPXCHG8,
12436                                                X86::NOT8r, X86::AL,
12437                                                X86::GR8RegisterClass);
12438   case X86::ATOMOR8:
12439     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12440                                                X86::OR8ri, X86::MOV8rm,
12441                                                X86::LCMPXCHG8,
12442                                                X86::NOT8r, X86::AL,
12443                                                X86::GR8RegisterClass);
12444   case X86::ATOMXOR8:
12445     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12446                                                X86::XOR8ri, X86::MOV8rm,
12447                                                X86::LCMPXCHG8,
12448                                                X86::NOT8r, X86::AL,
12449                                                X86::GR8RegisterClass);
12450   case X86::ATOMNAND8:
12451     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12452                                                X86::AND8ri, X86::MOV8rm,
12453                                                X86::LCMPXCHG8,
12454                                                X86::NOT8r, X86::AL,
12455                                                X86::GR8RegisterClass, true);
12456   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12457   // This group is for 64-bit host.
12458   case X86::ATOMAND64:
12459     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12460                                                X86::AND64ri32, X86::MOV64rm,
12461                                                X86::LCMPXCHG64,
12462                                                X86::NOT64r, X86::RAX,
12463                                                X86::GR64RegisterClass);
12464   case X86::ATOMOR64:
12465     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12466                                                X86::OR64ri32, X86::MOV64rm,
12467                                                X86::LCMPXCHG64,
12468                                                X86::NOT64r, X86::RAX,
12469                                                X86::GR64RegisterClass);
12470   case X86::ATOMXOR64:
12471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12472                                                X86::XOR64ri32, X86::MOV64rm,
12473                                                X86::LCMPXCHG64,
12474                                                X86::NOT64r, X86::RAX,
12475                                                X86::GR64RegisterClass);
12476   case X86::ATOMNAND64:
12477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12478                                                X86::AND64ri32, X86::MOV64rm,
12479                                                X86::LCMPXCHG64,
12480                                                X86::NOT64r, X86::RAX,
12481                                                X86::GR64RegisterClass, true);
12482   case X86::ATOMMIN64:
12483     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12484   case X86::ATOMMAX64:
12485     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12486   case X86::ATOMUMIN64:
12487     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12488   case X86::ATOMUMAX64:
12489     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12490
12491   // This group does 64-bit operations on a 32-bit host.
12492   case X86::ATOMAND6432:
12493     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12494                                                X86::AND32rr, X86::AND32rr,
12495                                                X86::AND32ri, X86::AND32ri,
12496                                                false);
12497   case X86::ATOMOR6432:
12498     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12499                                                X86::OR32rr, X86::OR32rr,
12500                                                X86::OR32ri, X86::OR32ri,
12501                                                false);
12502   case X86::ATOMXOR6432:
12503     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12504                                                X86::XOR32rr, X86::XOR32rr,
12505                                                X86::XOR32ri, X86::XOR32ri,
12506                                                false);
12507   case X86::ATOMNAND6432:
12508     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12509                                                X86::AND32rr, X86::AND32rr,
12510                                                X86::AND32ri, X86::AND32ri,
12511                                                true);
12512   case X86::ATOMADD6432:
12513     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12514                                                X86::ADD32rr, X86::ADC32rr,
12515                                                X86::ADD32ri, X86::ADC32ri,
12516                                                false);
12517   case X86::ATOMSUB6432:
12518     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12519                                                X86::SUB32rr, X86::SBB32rr,
12520                                                X86::SUB32ri, X86::SBB32ri,
12521                                                false);
12522   case X86::ATOMSWAP6432:
12523     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12524                                                X86::MOV32rr, X86::MOV32rr,
12525                                                X86::MOV32ri, X86::MOV32ri,
12526                                                false);
12527   case X86::VASTART_SAVE_XMM_REGS:
12528     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12529
12530   case X86::VAARG_64:
12531     return EmitVAARG64WithCustomInserter(MI, BB);
12532   }
12533 }
12534
12535 //===----------------------------------------------------------------------===//
12536 //                           X86 Optimization Hooks
12537 //===----------------------------------------------------------------------===//
12538
12539 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12540                                                        const APInt &Mask,
12541                                                        APInt &KnownZero,
12542                                                        APInt &KnownOne,
12543                                                        const SelectionDAG &DAG,
12544                                                        unsigned Depth) const {
12545   unsigned Opc = Op.getOpcode();
12546   assert((Opc >= ISD::BUILTIN_OP_END ||
12547           Opc == ISD::INTRINSIC_WO_CHAIN ||
12548           Opc == ISD::INTRINSIC_W_CHAIN ||
12549           Opc == ISD::INTRINSIC_VOID) &&
12550          "Should use MaskedValueIsZero if you don't know whether Op"
12551          " is a target node!");
12552
12553   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12554   switch (Opc) {
12555   default: break;
12556   case X86ISD::ADD:
12557   case X86ISD::SUB:
12558   case X86ISD::ADC:
12559   case X86ISD::SBB:
12560   case X86ISD::SMUL:
12561   case X86ISD::UMUL:
12562   case X86ISD::INC:
12563   case X86ISD::DEC:
12564   case X86ISD::OR:
12565   case X86ISD::XOR:
12566   case X86ISD::AND:
12567     // These nodes' second result is a boolean.
12568     if (Op.getResNo() == 0)
12569       break;
12570     // Fallthrough
12571   case X86ISD::SETCC:
12572     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12573                                        Mask.getBitWidth() - 1);
12574     break;
12575   case ISD::INTRINSIC_WO_CHAIN: {
12576     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12577     unsigned NumLoBits = 0;
12578     switch (IntId) {
12579     default: break;
12580     case Intrinsic::x86_sse_movmsk_ps:
12581     case Intrinsic::x86_avx_movmsk_ps_256:
12582     case Intrinsic::x86_sse2_movmsk_pd:
12583     case Intrinsic::x86_avx_movmsk_pd_256:
12584     case Intrinsic::x86_mmx_pmovmskb:
12585     case Intrinsic::x86_sse2_pmovmskb_128: {
12586       // High bits of movmskp{s|d}, pmovmskb are known zero.
12587       switch (IntId) {
12588         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12589         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12590         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12591         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12592         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12593         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12594       }
12595       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12596                                         Mask.getBitWidth() - NumLoBits);
12597       break;
12598     }
12599     }
12600     break;
12601   }
12602   }
12603 }
12604
12605 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12606                                                          unsigned Depth) const {
12607   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12608   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12609     return Op.getValueType().getScalarType().getSizeInBits();
12610
12611   // Fallback case.
12612   return 1;
12613 }
12614
12615 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12616 /// node is a GlobalAddress + offset.
12617 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12618                                        const GlobalValue* &GA,
12619                                        int64_t &Offset) const {
12620   if (N->getOpcode() == X86ISD::Wrapper) {
12621     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12622       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12623       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12624       return true;
12625     }
12626   }
12627   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12628 }
12629
12630 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12631 /// same as extracting the high 128-bit part of 256-bit vector and then
12632 /// inserting the result into the low part of a new 256-bit vector
12633 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12634   EVT VT = SVOp->getValueType(0);
12635   int NumElems = VT.getVectorNumElements();
12636
12637   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12638   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12639     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12640         SVOp->getMaskElt(j) >= 0)
12641       return false;
12642
12643   return true;
12644 }
12645
12646 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12647 /// same as extracting the low 128-bit part of 256-bit vector and then
12648 /// inserting the result into the high part of a new 256-bit vector
12649 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12650   EVT VT = SVOp->getValueType(0);
12651   int NumElems = VT.getVectorNumElements();
12652
12653   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12654   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12655     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12656         SVOp->getMaskElt(j) >= 0)
12657       return false;
12658
12659   return true;
12660 }
12661
12662 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12663 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12664                                         TargetLowering::DAGCombinerInfo &DCI) {
12665   DebugLoc dl = N->getDebugLoc();
12666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12667   SDValue V1 = SVOp->getOperand(0);
12668   SDValue V2 = SVOp->getOperand(1);
12669   EVT VT = SVOp->getValueType(0);
12670   int NumElems = VT.getVectorNumElements();
12671
12672   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12673       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12674     //
12675     //                   0,0,0,...
12676     //                      |
12677     //    V      UNDEF    BUILD_VECTOR    UNDEF
12678     //     \      /           \           /
12679     //  CONCAT_VECTOR         CONCAT_VECTOR
12680     //         \                  /
12681     //          \                /
12682     //          RESULT: V + zero extended
12683     //
12684     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12685         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12686         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12687       return SDValue();
12688
12689     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12690       return SDValue();
12691
12692     // To match the shuffle mask, the first half of the mask should
12693     // be exactly the first vector, and all the rest a splat with the
12694     // first element of the second one.
12695     for (int i = 0; i < NumElems/2; ++i)
12696       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12697           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12698         return SDValue();
12699
12700     // Emit a zeroed vector and insert the desired subvector on its
12701     // first half.
12702     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12703     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12704                          DAG.getConstant(0, MVT::i32), DAG, dl);
12705     return DCI.CombineTo(N, InsV);
12706   }
12707
12708   //===--------------------------------------------------------------------===//
12709   // Combine some shuffles into subvector extracts and inserts:
12710   //
12711
12712   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12713   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12714     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12715                                     DAG, dl);
12716     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12717                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12718     return DCI.CombineTo(N, InsV);
12719   }
12720
12721   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12722   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12723     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12724     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12725                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12726     return DCI.CombineTo(N, InsV);
12727   }
12728
12729   return SDValue();
12730 }
12731
12732 /// PerformShuffleCombine - Performs several different shuffle combines.
12733 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12734                                      TargetLowering::DAGCombinerInfo &DCI,
12735                                      const X86Subtarget *Subtarget) {
12736   DebugLoc dl = N->getDebugLoc();
12737   EVT VT = N->getValueType(0);
12738
12739   // Don't create instructions with illegal types after legalize types has run.
12740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12741   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12742     return SDValue();
12743
12744   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12745   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12746       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12747     return PerformShuffleCombine256(N, DAG, DCI);
12748
12749   // Only handle 128 wide vector from here on.
12750   if (VT.getSizeInBits() != 128)
12751     return SDValue();
12752
12753   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12754   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12755   // consecutive, non-overlapping, and in the right order.
12756   SmallVector<SDValue, 16> Elts;
12757   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12758     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12759
12760   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12761 }
12762
12763 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12764 /// generation and convert it from being a bunch of shuffles and extracts
12765 /// to a simple store and scalar loads to extract the elements.
12766 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12767                                                 const TargetLowering &TLI) {
12768   SDValue InputVector = N->getOperand(0);
12769
12770   // Only operate on vectors of 4 elements, where the alternative shuffling
12771   // gets to be more expensive.
12772   if (InputVector.getValueType() != MVT::v4i32)
12773     return SDValue();
12774
12775   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12776   // single use which is a sign-extend or zero-extend, and all elements are
12777   // used.
12778   SmallVector<SDNode *, 4> Uses;
12779   unsigned ExtractedElements = 0;
12780   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12781        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12782     if (UI.getUse().getResNo() != InputVector.getResNo())
12783       return SDValue();
12784
12785     SDNode *Extract = *UI;
12786     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12787       return SDValue();
12788
12789     if (Extract->getValueType(0) != MVT::i32)
12790       return SDValue();
12791     if (!Extract->hasOneUse())
12792       return SDValue();
12793     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12794         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12795       return SDValue();
12796     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12797       return SDValue();
12798
12799     // Record which element was extracted.
12800     ExtractedElements |=
12801       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12802
12803     Uses.push_back(Extract);
12804   }
12805
12806   // If not all the elements were used, this may not be worthwhile.
12807   if (ExtractedElements != 15)
12808     return SDValue();
12809
12810   // Ok, we've now decided to do the transformation.
12811   DebugLoc dl = InputVector.getDebugLoc();
12812
12813   // Store the value to a temporary stack slot.
12814   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12815   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12816                             MachinePointerInfo(), false, false, 0);
12817
12818   // Replace each use (extract) with a load of the appropriate element.
12819   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12820        UE = Uses.end(); UI != UE; ++UI) {
12821     SDNode *Extract = *UI;
12822
12823     // cOMpute the element's address.
12824     SDValue Idx = Extract->getOperand(1);
12825     unsigned EltSize =
12826         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12827     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12828     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12829
12830     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12831                                      StackPtr, OffsetVal);
12832
12833     // Load the scalar.
12834     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12835                                      ScalarAddr, MachinePointerInfo(),
12836                                      false, false, false, 0);
12837
12838     // Replace the exact with the load.
12839     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12840   }
12841
12842   // The replacement was made in place; don't return anything.
12843   return SDValue();
12844 }
12845
12846 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12847 /// nodes.
12848 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12849                                     const X86Subtarget *Subtarget) {
12850   DebugLoc DL = N->getDebugLoc();
12851   SDValue Cond = N->getOperand(0);
12852   // Get the LHS/RHS of the select.
12853   SDValue LHS = N->getOperand(1);
12854   SDValue RHS = N->getOperand(2);
12855   EVT VT = LHS.getValueType();
12856
12857   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12858   // instructions match the semantics of the common C idiom x<y?x:y but not
12859   // x<=y?x:y, because of how they handle negative zero (which can be
12860   // ignored in unsafe-math mode).
12861   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12862       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12863       (Subtarget->hasXMMInt() ||
12864        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12865     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12866
12867     unsigned Opcode = 0;
12868     // Check for x CC y ? x : y.
12869     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12870         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12871       switch (CC) {
12872       default: break;
12873       case ISD::SETULT:
12874         // Converting this to a min would handle NaNs incorrectly, and swapping
12875         // the operands would cause it to handle comparisons between positive
12876         // and negative zero incorrectly.
12877         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12878           if (!DAG.getTarget().Options.UnsafeFPMath &&
12879               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12880             break;
12881           std::swap(LHS, RHS);
12882         }
12883         Opcode = X86ISD::FMIN;
12884         break;
12885       case ISD::SETOLE:
12886         // Converting this to a min would handle comparisons between positive
12887         // and negative zero incorrectly.
12888         if (!DAG.getTarget().Options.UnsafeFPMath &&
12889             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12890           break;
12891         Opcode = X86ISD::FMIN;
12892         break;
12893       case ISD::SETULE:
12894         // Converting this to a min would handle both negative zeros and NaNs
12895         // incorrectly, but we can swap the operands to fix both.
12896         std::swap(LHS, RHS);
12897       case ISD::SETOLT:
12898       case ISD::SETLT:
12899       case ISD::SETLE:
12900         Opcode = X86ISD::FMIN;
12901         break;
12902
12903       case ISD::SETOGE:
12904         // Converting this to a max would handle comparisons between positive
12905         // and negative zero incorrectly.
12906         if (!DAG.getTarget().Options.UnsafeFPMath &&
12907             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12908           break;
12909         Opcode = X86ISD::FMAX;
12910         break;
12911       case ISD::SETUGT:
12912         // Converting this to a max would handle NaNs incorrectly, and swapping
12913         // the operands would cause it to handle comparisons between positive
12914         // and negative zero incorrectly.
12915         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12916           if (!DAG.getTarget().Options.UnsafeFPMath &&
12917               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12918             break;
12919           std::swap(LHS, RHS);
12920         }
12921         Opcode = X86ISD::FMAX;
12922         break;
12923       case ISD::SETUGE:
12924         // Converting this to a max would handle both negative zeros and NaNs
12925         // incorrectly, but we can swap the operands to fix both.
12926         std::swap(LHS, RHS);
12927       case ISD::SETOGT:
12928       case ISD::SETGT:
12929       case ISD::SETGE:
12930         Opcode = X86ISD::FMAX;
12931         break;
12932       }
12933     // Check for x CC y ? y : x -- a min/max with reversed arms.
12934     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12935                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12936       switch (CC) {
12937       default: break;
12938       case ISD::SETOGE:
12939         // Converting this to a min would handle comparisons between positive
12940         // and negative zero incorrectly, and swapping the operands would
12941         // cause it to handle NaNs incorrectly.
12942         if (!DAG.getTarget().Options.UnsafeFPMath &&
12943             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12944           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12945             break;
12946           std::swap(LHS, RHS);
12947         }
12948         Opcode = X86ISD::FMIN;
12949         break;
12950       case ISD::SETUGT:
12951         // Converting this to a min would handle NaNs incorrectly.
12952         if (!DAG.getTarget().Options.UnsafeFPMath &&
12953             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12954           break;
12955         Opcode = X86ISD::FMIN;
12956         break;
12957       case ISD::SETUGE:
12958         // Converting this to a min would handle both negative zeros and NaNs
12959         // incorrectly, but we can swap the operands to fix both.
12960         std::swap(LHS, RHS);
12961       case ISD::SETOGT:
12962       case ISD::SETGT:
12963       case ISD::SETGE:
12964         Opcode = X86ISD::FMIN;
12965         break;
12966
12967       case ISD::SETULT:
12968         // Converting this to a max would handle NaNs incorrectly.
12969         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12970           break;
12971         Opcode = X86ISD::FMAX;
12972         break;
12973       case ISD::SETOLE:
12974         // Converting this to a max would handle comparisons between positive
12975         // and negative zero incorrectly, and swapping the operands would
12976         // cause it to handle NaNs incorrectly.
12977         if (!DAG.getTarget().Options.UnsafeFPMath &&
12978             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12979           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12980             break;
12981           std::swap(LHS, RHS);
12982         }
12983         Opcode = X86ISD::FMAX;
12984         break;
12985       case ISD::SETULE:
12986         // Converting this to a max would handle both negative zeros and NaNs
12987         // incorrectly, but we can swap the operands to fix both.
12988         std::swap(LHS, RHS);
12989       case ISD::SETOLT:
12990       case ISD::SETLT:
12991       case ISD::SETLE:
12992         Opcode = X86ISD::FMAX;
12993         break;
12994       }
12995     }
12996
12997     if (Opcode)
12998       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12999   }
13000
13001   // If this is a select between two integer constants, try to do some
13002   // optimizations.
13003   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13004     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13005       // Don't do this for crazy integer types.
13006       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13007         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13008         // so that TrueC (the true value) is larger than FalseC.
13009         bool NeedsCondInvert = false;
13010
13011         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13012             // Efficiently invertible.
13013             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13014              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13015               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13016           NeedsCondInvert = true;
13017           std::swap(TrueC, FalseC);
13018         }
13019
13020         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13021         if (FalseC->getAPIntValue() == 0 &&
13022             TrueC->getAPIntValue().isPowerOf2()) {
13023           if (NeedsCondInvert) // Invert the condition if needed.
13024             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13025                                DAG.getConstant(1, Cond.getValueType()));
13026
13027           // Zero extend the condition if needed.
13028           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13029
13030           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13031           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13032                              DAG.getConstant(ShAmt, MVT::i8));
13033         }
13034
13035         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13036         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13037           if (NeedsCondInvert) // Invert the condition if needed.
13038             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13039                                DAG.getConstant(1, Cond.getValueType()));
13040
13041           // Zero extend the condition if needed.
13042           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13043                              FalseC->getValueType(0), Cond);
13044           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13045                              SDValue(FalseC, 0));
13046         }
13047
13048         // Optimize cases that will turn into an LEA instruction.  This requires
13049         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13050         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13051           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13052           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13053
13054           bool isFastMultiplier = false;
13055           if (Diff < 10) {
13056             switch ((unsigned char)Diff) {
13057               default: break;
13058               case 1:  // result = add base, cond
13059               case 2:  // result = lea base(    , cond*2)
13060               case 3:  // result = lea base(cond, cond*2)
13061               case 4:  // result = lea base(    , cond*4)
13062               case 5:  // result = lea base(cond, cond*4)
13063               case 8:  // result = lea base(    , cond*8)
13064               case 9:  // result = lea base(cond, cond*8)
13065                 isFastMultiplier = true;
13066                 break;
13067             }
13068           }
13069
13070           if (isFastMultiplier) {
13071             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13072             if (NeedsCondInvert) // Invert the condition if needed.
13073               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13074                                  DAG.getConstant(1, Cond.getValueType()));
13075
13076             // Zero extend the condition if needed.
13077             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13078                                Cond);
13079             // Scale the condition by the difference.
13080             if (Diff != 1)
13081               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13082                                  DAG.getConstant(Diff, Cond.getValueType()));
13083
13084             // Add the base if non-zero.
13085             if (FalseC->getAPIntValue() != 0)
13086               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13087                                  SDValue(FalseC, 0));
13088             return Cond;
13089           }
13090         }
13091       }
13092   }
13093
13094   return SDValue();
13095 }
13096
13097 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13098 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13099                                   TargetLowering::DAGCombinerInfo &DCI) {
13100   DebugLoc DL = N->getDebugLoc();
13101
13102   // If the flag operand isn't dead, don't touch this CMOV.
13103   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13104     return SDValue();
13105
13106   SDValue FalseOp = N->getOperand(0);
13107   SDValue TrueOp = N->getOperand(1);
13108   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13109   SDValue Cond = N->getOperand(3);
13110   if (CC == X86::COND_E || CC == X86::COND_NE) {
13111     switch (Cond.getOpcode()) {
13112     default: break;
13113     case X86ISD::BSR:
13114     case X86ISD::BSF:
13115       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13116       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13117         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13118     }
13119   }
13120
13121   // If this is a select between two integer constants, try to do some
13122   // optimizations.  Note that the operands are ordered the opposite of SELECT
13123   // operands.
13124   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13125     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13126       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13127       // larger than FalseC (the false value).
13128       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13129         CC = X86::GetOppositeBranchCondition(CC);
13130         std::swap(TrueC, FalseC);
13131       }
13132
13133       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13134       // This is efficient for any integer data type (including i8/i16) and
13135       // shift amount.
13136       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13137         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13138                            DAG.getConstant(CC, MVT::i8), Cond);
13139
13140         // Zero extend the condition if needed.
13141         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13142
13143         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13144         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13145                            DAG.getConstant(ShAmt, MVT::i8));
13146         if (N->getNumValues() == 2)  // Dead flag value?
13147           return DCI.CombineTo(N, Cond, SDValue());
13148         return Cond;
13149       }
13150
13151       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13152       // for any integer data type, including i8/i16.
13153       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13154         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13155                            DAG.getConstant(CC, MVT::i8), Cond);
13156
13157         // Zero extend the condition if needed.
13158         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13159                            FalseC->getValueType(0), Cond);
13160         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13161                            SDValue(FalseC, 0));
13162
13163         if (N->getNumValues() == 2)  // Dead flag value?
13164           return DCI.CombineTo(N, Cond, SDValue());
13165         return Cond;
13166       }
13167
13168       // Optimize cases that will turn into an LEA instruction.  This requires
13169       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13170       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13171         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13172         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13173
13174         bool isFastMultiplier = false;
13175         if (Diff < 10) {
13176           switch ((unsigned char)Diff) {
13177           default: break;
13178           case 1:  // result = add base, cond
13179           case 2:  // result = lea base(    , cond*2)
13180           case 3:  // result = lea base(cond, cond*2)
13181           case 4:  // result = lea base(    , cond*4)
13182           case 5:  // result = lea base(cond, cond*4)
13183           case 8:  // result = lea base(    , cond*8)
13184           case 9:  // result = lea base(cond, cond*8)
13185             isFastMultiplier = true;
13186             break;
13187           }
13188         }
13189
13190         if (isFastMultiplier) {
13191           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13192           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13193                              DAG.getConstant(CC, MVT::i8), Cond);
13194           // Zero extend the condition if needed.
13195           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13196                              Cond);
13197           // Scale the condition by the difference.
13198           if (Diff != 1)
13199             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13200                                DAG.getConstant(Diff, Cond.getValueType()));
13201
13202           // Add the base if non-zero.
13203           if (FalseC->getAPIntValue() != 0)
13204             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13205                                SDValue(FalseC, 0));
13206           if (N->getNumValues() == 2)  // Dead flag value?
13207             return DCI.CombineTo(N, Cond, SDValue());
13208           return Cond;
13209         }
13210       }
13211     }
13212   }
13213   return SDValue();
13214 }
13215
13216
13217 /// PerformMulCombine - Optimize a single multiply with constant into two
13218 /// in order to implement it with two cheaper instructions, e.g.
13219 /// LEA + SHL, LEA + LEA.
13220 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13221                                  TargetLowering::DAGCombinerInfo &DCI) {
13222   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13223     return SDValue();
13224
13225   EVT VT = N->getValueType(0);
13226   if (VT != MVT::i64)
13227     return SDValue();
13228
13229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13230   if (!C)
13231     return SDValue();
13232   uint64_t MulAmt = C->getZExtValue();
13233   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13234     return SDValue();
13235
13236   uint64_t MulAmt1 = 0;
13237   uint64_t MulAmt2 = 0;
13238   if ((MulAmt % 9) == 0) {
13239     MulAmt1 = 9;
13240     MulAmt2 = MulAmt / 9;
13241   } else if ((MulAmt % 5) == 0) {
13242     MulAmt1 = 5;
13243     MulAmt2 = MulAmt / 5;
13244   } else if ((MulAmt % 3) == 0) {
13245     MulAmt1 = 3;
13246     MulAmt2 = MulAmt / 3;
13247   }
13248   if (MulAmt2 &&
13249       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13250     DebugLoc DL = N->getDebugLoc();
13251
13252     if (isPowerOf2_64(MulAmt2) &&
13253         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13254       // If second multiplifer is pow2, issue it first. We want the multiply by
13255       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13256       // is an add.
13257       std::swap(MulAmt1, MulAmt2);
13258
13259     SDValue NewMul;
13260     if (isPowerOf2_64(MulAmt1))
13261       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13262                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13263     else
13264       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13265                            DAG.getConstant(MulAmt1, VT));
13266
13267     if (isPowerOf2_64(MulAmt2))
13268       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13269                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13270     else
13271       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13272                            DAG.getConstant(MulAmt2, VT));
13273
13274     // Do not add new nodes to DAG combiner worklist.
13275     DCI.CombineTo(N, NewMul, false);
13276   }
13277   return SDValue();
13278 }
13279
13280 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13281   SDValue N0 = N->getOperand(0);
13282   SDValue N1 = N->getOperand(1);
13283   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13284   EVT VT = N0.getValueType();
13285
13286   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13287   // since the result of setcc_c is all zero's or all ones.
13288   if (VT.isInteger() && !VT.isVector() &&
13289       N1C && N0.getOpcode() == ISD::AND &&
13290       N0.getOperand(1).getOpcode() == ISD::Constant) {
13291     SDValue N00 = N0.getOperand(0);
13292     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13293         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13294           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13295          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13296       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13297       APInt ShAmt = N1C->getAPIntValue();
13298       Mask = Mask.shl(ShAmt);
13299       if (Mask != 0)
13300         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13301                            N00, DAG.getConstant(Mask, VT));
13302     }
13303   }
13304
13305
13306   // Hardware support for vector shifts is sparse which makes us scalarize the
13307   // vector operations in many cases. Also, on sandybridge ADD is faster than
13308   // shl.
13309   // (shl V, 1) -> add V,V
13310   if (isSplatVector(N1.getNode())) {
13311     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13312     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13313     // We shift all of the values by one. In many cases we do not have
13314     // hardware support for this operation. This is better expressed as an ADD
13315     // of two values.
13316     if (N1C && (1 == N1C->getZExtValue())) {
13317       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13318     }
13319   }
13320
13321   return SDValue();
13322 }
13323
13324 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13325 ///                       when possible.
13326 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13327                                    const X86Subtarget *Subtarget) {
13328   EVT VT = N->getValueType(0);
13329   if (N->getOpcode() == ISD::SHL) {
13330     SDValue V = PerformSHLCombine(N, DAG);
13331     if (V.getNode()) return V;
13332   }
13333
13334   // On X86 with SSE2 support, we can transform this to a vector shift if
13335   // all elements are shifted by the same amount.  We can't do this in legalize
13336   // because the a constant vector is typically transformed to a constant pool
13337   // so we have no knowledge of the shift amount.
13338   if (!Subtarget->hasXMMInt())
13339     return SDValue();
13340
13341   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13342       (!Subtarget->hasAVX2() ||
13343        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13344     return SDValue();
13345
13346   SDValue ShAmtOp = N->getOperand(1);
13347   EVT EltVT = VT.getVectorElementType();
13348   DebugLoc DL = N->getDebugLoc();
13349   SDValue BaseShAmt = SDValue();
13350   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13351     unsigned NumElts = VT.getVectorNumElements();
13352     unsigned i = 0;
13353     for (; i != NumElts; ++i) {
13354       SDValue Arg = ShAmtOp.getOperand(i);
13355       if (Arg.getOpcode() == ISD::UNDEF) continue;
13356       BaseShAmt = Arg;
13357       break;
13358     }
13359     for (; i != NumElts; ++i) {
13360       SDValue Arg = ShAmtOp.getOperand(i);
13361       if (Arg.getOpcode() == ISD::UNDEF) continue;
13362       if (Arg != BaseShAmt) {
13363         return SDValue();
13364       }
13365     }
13366   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13367              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13368     SDValue InVec = ShAmtOp.getOperand(0);
13369     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13370       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13371       unsigned i = 0;
13372       for (; i != NumElts; ++i) {
13373         SDValue Arg = InVec.getOperand(i);
13374         if (Arg.getOpcode() == ISD::UNDEF) continue;
13375         BaseShAmt = Arg;
13376         break;
13377       }
13378     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13379        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13380          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13381          if (C->getZExtValue() == SplatIdx)
13382            BaseShAmt = InVec.getOperand(1);
13383        }
13384     }
13385     if (BaseShAmt.getNode() == 0)
13386       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13387                               DAG.getIntPtrConstant(0));
13388   } else
13389     return SDValue();
13390
13391   // The shift amount is an i32.
13392   if (EltVT.bitsGT(MVT::i32))
13393     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13394   else if (EltVT.bitsLT(MVT::i32))
13395     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13396
13397   // The shift amount is identical so we can do a vector shift.
13398   SDValue  ValOp = N->getOperand(0);
13399   switch (N->getOpcode()) {
13400   default:
13401     llvm_unreachable("Unknown shift opcode!");
13402     break;
13403   case ISD::SHL:
13404     if (VT == MVT::v2i64)
13405       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13406                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13407                          ValOp, BaseShAmt);
13408     if (VT == MVT::v4i32)
13409       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13410                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13411                          ValOp, BaseShAmt);
13412     if (VT == MVT::v8i16)
13413       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13414                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13415                          ValOp, BaseShAmt);
13416     if (VT == MVT::v4i64)
13417       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13418                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13419                          ValOp, BaseShAmt);
13420     if (VT == MVT::v8i32)
13421       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13422                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13423                          ValOp, BaseShAmt);
13424     if (VT == MVT::v16i16)
13425       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13426                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13427                          ValOp, BaseShAmt);
13428     break;
13429   case ISD::SRA:
13430     if (VT == MVT::v4i32)
13431       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13432                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13433                          ValOp, BaseShAmt);
13434     if (VT == MVT::v8i16)
13435       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13436                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13437                          ValOp, BaseShAmt);
13438     if (VT == MVT::v8i32)
13439       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13440                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13441                          ValOp, BaseShAmt);
13442     if (VT == MVT::v16i16)
13443       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13444                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13445                          ValOp, BaseShAmt);
13446     break;
13447   case ISD::SRL:
13448     if (VT == MVT::v2i64)
13449       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13450                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13451                          ValOp, BaseShAmt);
13452     if (VT == MVT::v4i32)
13453       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13454                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13455                          ValOp, BaseShAmt);
13456     if (VT ==  MVT::v8i16)
13457       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13458                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13459                          ValOp, BaseShAmt);
13460     if (VT == MVT::v4i64)
13461       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13462                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13463                          ValOp, BaseShAmt);
13464     if (VT == MVT::v8i32)
13465       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13466                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13467                          ValOp, BaseShAmt);
13468     if (VT ==  MVT::v16i16)
13469       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13470                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13471                          ValOp, BaseShAmt);
13472     break;
13473   }
13474   return SDValue();
13475 }
13476
13477
13478 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13479 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13480 // and friends.  Likewise for OR -> CMPNEQSS.
13481 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13482                             TargetLowering::DAGCombinerInfo &DCI,
13483                             const X86Subtarget *Subtarget) {
13484   unsigned opcode;
13485
13486   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13487   // we're requiring SSE2 for both.
13488   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13489     SDValue N0 = N->getOperand(0);
13490     SDValue N1 = N->getOperand(1);
13491     SDValue CMP0 = N0->getOperand(1);
13492     SDValue CMP1 = N1->getOperand(1);
13493     DebugLoc DL = N->getDebugLoc();
13494
13495     // The SETCCs should both refer to the same CMP.
13496     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13497       return SDValue();
13498
13499     SDValue CMP00 = CMP0->getOperand(0);
13500     SDValue CMP01 = CMP0->getOperand(1);
13501     EVT     VT    = CMP00.getValueType();
13502
13503     if (VT == MVT::f32 || VT == MVT::f64) {
13504       bool ExpectingFlags = false;
13505       // Check for any users that want flags:
13506       for (SDNode::use_iterator UI = N->use_begin(),
13507              UE = N->use_end();
13508            !ExpectingFlags && UI != UE; ++UI)
13509         switch (UI->getOpcode()) {
13510         default:
13511         case ISD::BR_CC:
13512         case ISD::BRCOND:
13513         case ISD::SELECT:
13514           ExpectingFlags = true;
13515           break;
13516         case ISD::CopyToReg:
13517         case ISD::SIGN_EXTEND:
13518         case ISD::ZERO_EXTEND:
13519         case ISD::ANY_EXTEND:
13520           break;
13521         }
13522
13523       if (!ExpectingFlags) {
13524         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13525         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13526
13527         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13528           X86::CondCode tmp = cc0;
13529           cc0 = cc1;
13530           cc1 = tmp;
13531         }
13532
13533         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13534             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13535           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13536           X86ISD::NodeType NTOperator = is64BitFP ?
13537             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13538           // FIXME: need symbolic constants for these magic numbers.
13539           // See X86ATTInstPrinter.cpp:printSSECC().
13540           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13541           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13542                                               DAG.getConstant(x86cc, MVT::i8));
13543           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13544                                               OnesOrZeroesF);
13545           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13546                                       DAG.getConstant(1, MVT::i32));
13547           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13548           return OneBitOfTruth;
13549         }
13550       }
13551     }
13552   }
13553   return SDValue();
13554 }
13555
13556 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13557 /// so it can be folded inside ANDNP.
13558 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13559   EVT VT = N->getValueType(0);
13560
13561   // Match direct AllOnes for 128 and 256-bit vectors
13562   if (ISD::isBuildVectorAllOnes(N))
13563     return true;
13564
13565   // Look through a bit convert.
13566   if (N->getOpcode() == ISD::BITCAST)
13567     N = N->getOperand(0).getNode();
13568
13569   // Sometimes the operand may come from a insert_subvector building a 256-bit
13570   // allones vector
13571   if (VT.getSizeInBits() == 256 &&
13572       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13573     SDValue V1 = N->getOperand(0);
13574     SDValue V2 = N->getOperand(1);
13575
13576     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13577         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13578         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13579         ISD::isBuildVectorAllOnes(V2.getNode()))
13580       return true;
13581   }
13582
13583   return false;
13584 }
13585
13586 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13587                                  TargetLowering::DAGCombinerInfo &DCI,
13588                                  const X86Subtarget *Subtarget) {
13589   if (DCI.isBeforeLegalizeOps())
13590     return SDValue();
13591
13592   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13593   if (R.getNode())
13594     return R;
13595
13596   EVT VT = N->getValueType(0);
13597
13598   // Create ANDN, BLSI, and BLSR instructions
13599   // BLSI is X & (-X)
13600   // BLSR is X & (X-1)
13601   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13602     SDValue N0 = N->getOperand(0);
13603     SDValue N1 = N->getOperand(1);
13604     DebugLoc DL = N->getDebugLoc();
13605
13606     // Check LHS for not
13607     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13608       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13609     // Check RHS for not
13610     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13611       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13612
13613     // Check LHS for neg
13614     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13615         isZero(N0.getOperand(0)))
13616       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13617
13618     // Check RHS for neg
13619     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13620         isZero(N1.getOperand(0)))
13621       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13622
13623     // Check LHS for X-1
13624     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13625         isAllOnes(N0.getOperand(1)))
13626       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13627
13628     // Check RHS for X-1
13629     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13630         isAllOnes(N1.getOperand(1)))
13631       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13632
13633     return SDValue();
13634   }
13635
13636   // Want to form ANDNP nodes:
13637   // 1) In the hopes of then easily combining them with OR and AND nodes
13638   //    to form PBLEND/PSIGN.
13639   // 2) To match ANDN packed intrinsics
13640   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13641     return SDValue();
13642
13643   SDValue N0 = N->getOperand(0);
13644   SDValue N1 = N->getOperand(1);
13645   DebugLoc DL = N->getDebugLoc();
13646
13647   // Check LHS for vnot
13648   if (N0.getOpcode() == ISD::XOR &&
13649       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13650       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13651     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13652
13653   // Check RHS for vnot
13654   if (N1.getOpcode() == ISD::XOR &&
13655       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13656       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13657     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13658
13659   return SDValue();
13660 }
13661
13662 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13663                                 TargetLowering::DAGCombinerInfo &DCI,
13664                                 const X86Subtarget *Subtarget) {
13665   if (DCI.isBeforeLegalizeOps())
13666     return SDValue();
13667
13668   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13669   if (R.getNode())
13670     return R;
13671
13672   EVT VT = N->getValueType(0);
13673
13674   SDValue N0 = N->getOperand(0);
13675   SDValue N1 = N->getOperand(1);
13676
13677   // look for psign/blend
13678   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13679     if (!Subtarget->hasSSSE3orAVX() ||
13680         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13681       return SDValue();
13682
13683     // Canonicalize pandn to RHS
13684     if (N0.getOpcode() == X86ISD::ANDNP)
13685       std::swap(N0, N1);
13686     // or (and (m, x), (pandn m, y))
13687     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13688       SDValue Mask = N1.getOperand(0);
13689       SDValue X    = N1.getOperand(1);
13690       SDValue Y;
13691       if (N0.getOperand(0) == Mask)
13692         Y = N0.getOperand(1);
13693       if (N0.getOperand(1) == Mask)
13694         Y = N0.getOperand(0);
13695
13696       // Check to see if the mask appeared in both the AND and ANDNP and
13697       if (!Y.getNode())
13698         return SDValue();
13699
13700       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13701       if (Mask.getOpcode() != ISD::BITCAST ||
13702           X.getOpcode() != ISD::BITCAST ||
13703           Y.getOpcode() != ISD::BITCAST)
13704         return SDValue();
13705
13706       // Look through mask bitcast.
13707       Mask = Mask.getOperand(0);
13708       EVT MaskVT = Mask.getValueType();
13709
13710       // Validate that the Mask operand is a vector sra node.  The sra node
13711       // will be an intrinsic.
13712       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13713         return SDValue();
13714
13715       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13716       // there is no psrai.b
13717       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13718       case Intrinsic::x86_sse2_psrai_w:
13719       case Intrinsic::x86_sse2_psrai_d:
13720       case Intrinsic::x86_avx2_psrai_w:
13721       case Intrinsic::x86_avx2_psrai_d:
13722         break;
13723       default: return SDValue();
13724       }
13725
13726       // Check that the SRA is all signbits.
13727       SDValue SraC = Mask.getOperand(2);
13728       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13729       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13730       if ((SraAmt + 1) != EltBits)
13731         return SDValue();
13732
13733       DebugLoc DL = N->getDebugLoc();
13734
13735       // Now we know we at least have a plendvb with the mask val.  See if
13736       // we can form a psignb/w/d.
13737       // psign = x.type == y.type == mask.type && y = sub(0, x);
13738       X = X.getOperand(0);
13739       Y = Y.getOperand(0);
13740       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13741           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13742           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13743           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13744         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13745                                    Mask.getOperand(1));
13746         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13747       }
13748       // PBLENDVB only available on SSE 4.1
13749       if (!Subtarget->hasSSE41orAVX())
13750         return SDValue();
13751
13752       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13753
13754       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13755       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13756       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13757       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13758       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13759     }
13760   }
13761
13762   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13763     return SDValue();
13764
13765   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13766   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13767     std::swap(N0, N1);
13768   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13769     return SDValue();
13770   if (!N0.hasOneUse() || !N1.hasOneUse())
13771     return SDValue();
13772
13773   SDValue ShAmt0 = N0.getOperand(1);
13774   if (ShAmt0.getValueType() != MVT::i8)
13775     return SDValue();
13776   SDValue ShAmt1 = N1.getOperand(1);
13777   if (ShAmt1.getValueType() != MVT::i8)
13778     return SDValue();
13779   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13780     ShAmt0 = ShAmt0.getOperand(0);
13781   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13782     ShAmt1 = ShAmt1.getOperand(0);
13783
13784   DebugLoc DL = N->getDebugLoc();
13785   unsigned Opc = X86ISD::SHLD;
13786   SDValue Op0 = N0.getOperand(0);
13787   SDValue Op1 = N1.getOperand(0);
13788   if (ShAmt0.getOpcode() == ISD::SUB) {
13789     Opc = X86ISD::SHRD;
13790     std::swap(Op0, Op1);
13791     std::swap(ShAmt0, ShAmt1);
13792   }
13793
13794   unsigned Bits = VT.getSizeInBits();
13795   if (ShAmt1.getOpcode() == ISD::SUB) {
13796     SDValue Sum = ShAmt1.getOperand(0);
13797     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13798       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13799       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13800         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13801       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13802         return DAG.getNode(Opc, DL, VT,
13803                            Op0, Op1,
13804                            DAG.getNode(ISD::TRUNCATE, DL,
13805                                        MVT::i8, ShAmt0));
13806     }
13807   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13808     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13809     if (ShAmt0C &&
13810         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13811       return DAG.getNode(Opc, DL, VT,
13812                          N0.getOperand(0), N1.getOperand(0),
13813                          DAG.getNode(ISD::TRUNCATE, DL,
13814                                        MVT::i8, ShAmt0));
13815   }
13816
13817   return SDValue();
13818 }
13819
13820 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13821                                  TargetLowering::DAGCombinerInfo &DCI,
13822                                  const X86Subtarget *Subtarget) {
13823   if (DCI.isBeforeLegalizeOps())
13824     return SDValue();
13825
13826   EVT VT = N->getValueType(0);
13827
13828   if (VT != MVT::i32 && VT != MVT::i64)
13829     return SDValue();
13830
13831   // Create BLSMSK instructions by finding X ^ (X-1)
13832   SDValue N0 = N->getOperand(0);
13833   SDValue N1 = N->getOperand(1);
13834   DebugLoc DL = N->getDebugLoc();
13835
13836   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13837       isAllOnes(N0.getOperand(1)))
13838     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13839
13840   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13841       isAllOnes(N1.getOperand(1)))
13842     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13843
13844   return SDValue();
13845 }
13846
13847 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13848 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13849                                    const X86Subtarget *Subtarget) {
13850   LoadSDNode *Ld = cast<LoadSDNode>(N);
13851   EVT RegVT = Ld->getValueType(0);
13852   EVT MemVT = Ld->getMemoryVT();
13853   DebugLoc dl = Ld->getDebugLoc();
13854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13855
13856   ISD::LoadExtType Ext = Ld->getExtensionType();
13857
13858   // If this is a vector EXT Load then attempt to optimize it using a
13859   // shuffle. We need SSE4 for the shuffles.
13860   // TODO: It is possible to support ZExt by zeroing the undef values
13861   // during the shuffle phase or after the shuffle.
13862   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13863     assert(MemVT != RegVT && "Cannot extend to the same type");
13864     assert(MemVT.isVector() && "Must load a vector from memory");
13865
13866     unsigned NumElems = RegVT.getVectorNumElements();
13867     unsigned RegSz = RegVT.getSizeInBits();
13868     unsigned MemSz = MemVT.getSizeInBits();
13869     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13870     // All sizes must be a power of two
13871     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13872
13873     // Attempt to load the original value using a single load op.
13874     // Find a scalar type which is equal to the loaded word size.
13875     MVT SclrLoadTy = MVT::i8;
13876     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13877          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13878       MVT Tp = (MVT::SimpleValueType)tp;
13879       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13880         SclrLoadTy = Tp;
13881         break;
13882       }
13883     }
13884
13885     // Proceed if a load word is found.
13886     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13887
13888     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13889       RegSz/SclrLoadTy.getSizeInBits());
13890
13891     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13892                                   RegSz/MemVT.getScalarType().getSizeInBits());
13893     // Can't shuffle using an illegal type.
13894     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13895
13896     // Perform a single load.
13897     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13898                                   Ld->getBasePtr(),
13899                                   Ld->getPointerInfo(), Ld->isVolatile(),
13900                                   Ld->isNonTemporal(), Ld->isInvariant(),
13901                                   Ld->getAlignment());
13902
13903     // Insert the word loaded into a vector.
13904     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13905       LoadUnitVecVT, ScalarLoad);
13906
13907     // Bitcast the loaded value to a vector of the original element type, in
13908     // the size of the target vector type.
13909     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13910     unsigned SizeRatio = RegSz/MemSz;
13911
13912     // Redistribute the loaded elements into the different locations.
13913     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13914     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13915
13916     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13917                                 DAG.getUNDEF(SlicedVec.getValueType()),
13918                                 ShuffleVec.data());
13919
13920     // Bitcast to the requested type.
13921     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13922     // Replace the original load with the new sequence
13923     // and return the new chain.
13924     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13925     return SDValue(ScalarLoad.getNode(), 1);
13926   }
13927
13928   return SDValue();
13929 }
13930
13931 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13932 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13933                                    const X86Subtarget *Subtarget) {
13934   StoreSDNode *St = cast<StoreSDNode>(N);
13935   EVT VT = St->getValue().getValueType();
13936   EVT StVT = St->getMemoryVT();
13937   DebugLoc dl = St->getDebugLoc();
13938   SDValue StoredVal = St->getOperand(1);
13939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13940
13941   // If we are saving a concatenation of two XMM registers, perform two stores.
13942   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13943   // 128-bit ones. If in the future the cost becomes only one memory access the
13944   // first version would be better.
13945   if (VT.getSizeInBits() == 256 &&
13946     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13947     StoredVal.getNumOperands() == 2) {
13948
13949     SDValue Value0 = StoredVal.getOperand(0);
13950     SDValue Value1 = StoredVal.getOperand(1);
13951
13952     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13953     SDValue Ptr0 = St->getBasePtr();
13954     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13955
13956     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13957                                 St->getPointerInfo(), St->isVolatile(),
13958                                 St->isNonTemporal(), St->getAlignment());
13959     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13960                                 St->getPointerInfo(), St->isVolatile(),
13961                                 St->isNonTemporal(), St->getAlignment());
13962     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13963   }
13964
13965   // Optimize trunc store (of multiple scalars) to shuffle and store.
13966   // First, pack all of the elements in one place. Next, store to memory
13967   // in fewer chunks.
13968   if (St->isTruncatingStore() && VT.isVector()) {
13969     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13970     unsigned NumElems = VT.getVectorNumElements();
13971     assert(StVT != VT && "Cannot truncate to the same type");
13972     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13973     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13974
13975     // From, To sizes and ElemCount must be pow of two
13976     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13977     // We are going to use the original vector elt for storing.
13978     // Accumulated smaller vector elements must be a multiple of the store size.
13979     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13980
13981     unsigned SizeRatio  = FromSz / ToSz;
13982
13983     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13984
13985     // Create a type on which we perform the shuffle
13986     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13987             StVT.getScalarType(), NumElems*SizeRatio);
13988
13989     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13990
13991     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13992     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13993     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13994
13995     // Can't shuffle using an illegal type
13996     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13997
13998     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13999                                 DAG.getUNDEF(WideVec.getValueType()),
14000                                 ShuffleVec.data());
14001     // At this point all of the data is stored at the bottom of the
14002     // register. We now need to save it to mem.
14003
14004     // Find the largest store unit
14005     MVT StoreType = MVT::i8;
14006     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14007          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14008       MVT Tp = (MVT::SimpleValueType)tp;
14009       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14010         StoreType = Tp;
14011     }
14012
14013     // Bitcast the original vector into a vector of store-size units
14014     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14015             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14016     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14017     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14018     SmallVector<SDValue, 8> Chains;
14019     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14020                                         TLI.getPointerTy());
14021     SDValue Ptr = St->getBasePtr();
14022
14023     // Perform one or more big stores into memory.
14024     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14025       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14026                                    StoreType, ShuffWide,
14027                                    DAG.getIntPtrConstant(i));
14028       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14029                                 St->getPointerInfo(), St->isVolatile(),
14030                                 St->isNonTemporal(), St->getAlignment());
14031       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14032       Chains.push_back(Ch);
14033     }
14034
14035     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14036                                Chains.size());
14037   }
14038
14039
14040   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14041   // the FP state in cases where an emms may be missing.
14042   // A preferable solution to the general problem is to figure out the right
14043   // places to insert EMMS.  This qualifies as a quick hack.
14044
14045   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14046   if (VT.getSizeInBits() != 64)
14047     return SDValue();
14048
14049   const Function *F = DAG.getMachineFunction().getFunction();
14050   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14051   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14052                      && Subtarget->hasXMMInt();
14053   if ((VT.isVector() ||
14054        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14055       isa<LoadSDNode>(St->getValue()) &&
14056       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14057       St->getChain().hasOneUse() && !St->isVolatile()) {
14058     SDNode* LdVal = St->getValue().getNode();
14059     LoadSDNode *Ld = 0;
14060     int TokenFactorIndex = -1;
14061     SmallVector<SDValue, 8> Ops;
14062     SDNode* ChainVal = St->getChain().getNode();
14063     // Must be a store of a load.  We currently handle two cases:  the load
14064     // is a direct child, and it's under an intervening TokenFactor.  It is
14065     // possible to dig deeper under nested TokenFactors.
14066     if (ChainVal == LdVal)
14067       Ld = cast<LoadSDNode>(St->getChain());
14068     else if (St->getValue().hasOneUse() &&
14069              ChainVal->getOpcode() == ISD::TokenFactor) {
14070       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14071         if (ChainVal->getOperand(i).getNode() == LdVal) {
14072           TokenFactorIndex = i;
14073           Ld = cast<LoadSDNode>(St->getValue());
14074         } else
14075           Ops.push_back(ChainVal->getOperand(i));
14076       }
14077     }
14078
14079     if (!Ld || !ISD::isNormalLoad(Ld))
14080       return SDValue();
14081
14082     // If this is not the MMX case, i.e. we are just turning i64 load/store
14083     // into f64 load/store, avoid the transformation if there are multiple
14084     // uses of the loaded value.
14085     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14086       return SDValue();
14087
14088     DebugLoc LdDL = Ld->getDebugLoc();
14089     DebugLoc StDL = N->getDebugLoc();
14090     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14091     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14092     // pair instead.
14093     if (Subtarget->is64Bit() || F64IsLegal) {
14094       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14095       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14096                                   Ld->getPointerInfo(), Ld->isVolatile(),
14097                                   Ld->isNonTemporal(), Ld->isInvariant(),
14098                                   Ld->getAlignment());
14099       SDValue NewChain = NewLd.getValue(1);
14100       if (TokenFactorIndex != -1) {
14101         Ops.push_back(NewChain);
14102         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14103                                Ops.size());
14104       }
14105       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14106                           St->getPointerInfo(),
14107                           St->isVolatile(), St->isNonTemporal(),
14108                           St->getAlignment());
14109     }
14110
14111     // Otherwise, lower to two pairs of 32-bit loads / stores.
14112     SDValue LoAddr = Ld->getBasePtr();
14113     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14114                                  DAG.getConstant(4, MVT::i32));
14115
14116     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14117                                Ld->getPointerInfo(),
14118                                Ld->isVolatile(), Ld->isNonTemporal(),
14119                                Ld->isInvariant(), Ld->getAlignment());
14120     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14121                                Ld->getPointerInfo().getWithOffset(4),
14122                                Ld->isVolatile(), Ld->isNonTemporal(),
14123                                Ld->isInvariant(),
14124                                MinAlign(Ld->getAlignment(), 4));
14125
14126     SDValue NewChain = LoLd.getValue(1);
14127     if (TokenFactorIndex != -1) {
14128       Ops.push_back(LoLd);
14129       Ops.push_back(HiLd);
14130       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14131                              Ops.size());
14132     }
14133
14134     LoAddr = St->getBasePtr();
14135     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14136                          DAG.getConstant(4, MVT::i32));
14137
14138     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14139                                 St->getPointerInfo(),
14140                                 St->isVolatile(), St->isNonTemporal(),
14141                                 St->getAlignment());
14142     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14143                                 St->getPointerInfo().getWithOffset(4),
14144                                 St->isVolatile(),
14145                                 St->isNonTemporal(),
14146                                 MinAlign(St->getAlignment(), 4));
14147     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14148   }
14149   return SDValue();
14150 }
14151
14152 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14153 /// and return the operands for the horizontal operation in LHS and RHS.  A
14154 /// horizontal operation performs the binary operation on successive elements
14155 /// of its first operand, then on successive elements of its second operand,
14156 /// returning the resulting values in a vector.  For example, if
14157 ///   A = < float a0, float a1, float a2, float a3 >
14158 /// and
14159 ///   B = < float b0, float b1, float b2, float b3 >
14160 /// then the result of doing a horizontal operation on A and B is
14161 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14162 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14163 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14164 /// set to A, RHS to B, and the routine returns 'true'.
14165 /// Note that the binary operation should have the property that if one of the
14166 /// operands is UNDEF then the result is UNDEF.
14167 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14168   // Look for the following pattern: if
14169   //   A = < float a0, float a1, float a2, float a3 >
14170   //   B = < float b0, float b1, float b2, float b3 >
14171   // and
14172   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14173   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14174   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14175   // which is A horizontal-op B.
14176
14177   // At least one of the operands should be a vector shuffle.
14178   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14179       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14180     return false;
14181
14182   EVT VT = LHS.getValueType();
14183
14184   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14185          "Unsupported vector type for horizontal add/sub");
14186
14187   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14188   // operate independently on 128-bit lanes.
14189   unsigned NumElts = VT.getVectorNumElements();
14190   unsigned NumLanes = VT.getSizeInBits()/128;
14191   unsigned NumLaneElts = NumElts / NumLanes;
14192   assert((NumLaneElts % 2 == 0) &&
14193          "Vector type should have an even number of elements in each lane");
14194   unsigned HalfLaneElts = NumLaneElts/2;
14195
14196   // View LHS in the form
14197   //   LHS = VECTOR_SHUFFLE A, B, LMask
14198   // If LHS is not a shuffle then pretend it is the shuffle
14199   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14200   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14201   // type VT.
14202   SDValue A, B;
14203   SmallVector<int, 16> LMask(NumElts);
14204   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14205     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14206       A = LHS.getOperand(0);
14207     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14208       B = LHS.getOperand(1);
14209     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14210   } else {
14211     if (LHS.getOpcode() != ISD::UNDEF)
14212       A = LHS;
14213     for (unsigned i = 0; i != NumElts; ++i)
14214       LMask[i] = i;
14215   }
14216
14217   // Likewise, view RHS in the form
14218   //   RHS = VECTOR_SHUFFLE C, D, RMask
14219   SDValue C, D;
14220   SmallVector<int, 16> RMask(NumElts);
14221   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14222     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14223       C = RHS.getOperand(0);
14224     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14225       D = RHS.getOperand(1);
14226     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14227   } else {
14228     if (RHS.getOpcode() != ISD::UNDEF)
14229       C = RHS;
14230     for (unsigned i = 0; i != NumElts; ++i)
14231       RMask[i] = i;
14232   }
14233
14234   // Check that the shuffles are both shuffling the same vectors.
14235   if (!(A == C && B == D) && !(A == D && B == C))
14236     return false;
14237
14238   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14239   if (!A.getNode() && !B.getNode())
14240     return false;
14241
14242   // If A and B occur in reverse order in RHS, then "swap" them (which means
14243   // rewriting the mask).
14244   if (A != C)
14245     CommuteVectorShuffleMask(RMask, NumElts);
14246
14247   // At this point LHS and RHS are equivalent to
14248   //   LHS = VECTOR_SHUFFLE A, B, LMask
14249   //   RHS = VECTOR_SHUFFLE A, B, RMask
14250   // Check that the masks correspond to performing a horizontal operation.
14251   for (unsigned i = 0; i != NumElts; ++i) {
14252     int LIdx = LMask[i], RIdx = RMask[i];
14253
14254     // Ignore any UNDEF components.
14255     if (LIdx < 0 || RIdx < 0 ||
14256         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14257         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14258       continue;
14259
14260     // Check that successive elements are being operated on.  If not, this is
14261     // not a horizontal operation.
14262     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14263     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14264     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14265     if (!(LIdx == Index && RIdx == Index + 1) &&
14266         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14267       return false;
14268   }
14269
14270   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14271   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14272   return true;
14273 }
14274
14275 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14276 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14277                                   const X86Subtarget *Subtarget) {
14278   EVT VT = N->getValueType(0);
14279   SDValue LHS = N->getOperand(0);
14280   SDValue RHS = N->getOperand(1);
14281
14282   // Try to synthesize horizontal adds from adds of shuffles.
14283   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14284        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14285       isHorizontalBinOp(LHS, RHS, true))
14286     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14287   return SDValue();
14288 }
14289
14290 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14291 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14292                                   const X86Subtarget *Subtarget) {
14293   EVT VT = N->getValueType(0);
14294   SDValue LHS = N->getOperand(0);
14295   SDValue RHS = N->getOperand(1);
14296
14297   // Try to synthesize horizontal subs from subs of shuffles.
14298   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14299        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14300       isHorizontalBinOp(LHS, RHS, false))
14301     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14302   return SDValue();
14303 }
14304
14305 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14306 /// X86ISD::FXOR nodes.
14307 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14308   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14309   // F[X]OR(0.0, x) -> x
14310   // F[X]OR(x, 0.0) -> x
14311   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14312     if (C->getValueAPF().isPosZero())
14313       return N->getOperand(1);
14314   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14315     if (C->getValueAPF().isPosZero())
14316       return N->getOperand(0);
14317   return SDValue();
14318 }
14319
14320 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14321 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14322   // FAND(0.0, x) -> 0.0
14323   // FAND(x, 0.0) -> 0.0
14324   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14325     if (C->getValueAPF().isPosZero())
14326       return N->getOperand(0);
14327   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14328     if (C->getValueAPF().isPosZero())
14329       return N->getOperand(1);
14330   return SDValue();
14331 }
14332
14333 static SDValue PerformBTCombine(SDNode *N,
14334                                 SelectionDAG &DAG,
14335                                 TargetLowering::DAGCombinerInfo &DCI) {
14336   // BT ignores high bits in the bit index operand.
14337   SDValue Op1 = N->getOperand(1);
14338   if (Op1.hasOneUse()) {
14339     unsigned BitWidth = Op1.getValueSizeInBits();
14340     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14341     APInt KnownZero, KnownOne;
14342     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14343                                           !DCI.isBeforeLegalizeOps());
14344     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14345     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14346         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14347       DCI.CommitTargetLoweringOpt(TLO);
14348   }
14349   return SDValue();
14350 }
14351
14352 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14353   SDValue Op = N->getOperand(0);
14354   if (Op.getOpcode() == ISD::BITCAST)
14355     Op = Op.getOperand(0);
14356   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14357   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14358       VT.getVectorElementType().getSizeInBits() ==
14359       OpVT.getVectorElementType().getSizeInBits()) {
14360     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14361   }
14362   return SDValue();
14363 }
14364
14365 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14366   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14367   //           (and (i32 x86isd::setcc_carry), 1)
14368   // This eliminates the zext. This transformation is necessary because
14369   // ISD::SETCC is always legalized to i8.
14370   DebugLoc dl = N->getDebugLoc();
14371   SDValue N0 = N->getOperand(0);
14372   EVT VT = N->getValueType(0);
14373   if (N0.getOpcode() == ISD::AND &&
14374       N0.hasOneUse() &&
14375       N0.getOperand(0).hasOneUse()) {
14376     SDValue N00 = N0.getOperand(0);
14377     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14378       return SDValue();
14379     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14380     if (!C || C->getZExtValue() != 1)
14381       return SDValue();
14382     return DAG.getNode(ISD::AND, dl, VT,
14383                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14384                                    N00.getOperand(0), N00.getOperand(1)),
14385                        DAG.getConstant(1, VT));
14386   }
14387
14388   return SDValue();
14389 }
14390
14391 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14392 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14393   unsigned X86CC = N->getConstantOperandVal(0);
14394   SDValue EFLAG = N->getOperand(1);
14395   DebugLoc DL = N->getDebugLoc();
14396
14397   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14398   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14399   // cases.
14400   if (X86CC == X86::COND_B)
14401     return DAG.getNode(ISD::AND, DL, MVT::i8,
14402                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14403                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14404                        DAG.getConstant(1, MVT::i8));
14405
14406   return SDValue();
14407 }
14408
14409 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14410                                         const X86TargetLowering *XTLI) {
14411   SDValue Op0 = N->getOperand(0);
14412   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14413   // a 32-bit target where SSE doesn't support i64->FP operations.
14414   if (Op0.getOpcode() == ISD::LOAD) {
14415     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14416     EVT VT = Ld->getValueType(0);
14417     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14418         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14419         !XTLI->getSubtarget()->is64Bit() &&
14420         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14421       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14422                                           Ld->getChain(), Op0, DAG);
14423       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14424       return FILDChain;
14425     }
14426   }
14427   return SDValue();
14428 }
14429
14430 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14431 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14432                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14433   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14434   // the result is either zero or one (depending on the input carry bit).
14435   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14436   if (X86::isZeroNode(N->getOperand(0)) &&
14437       X86::isZeroNode(N->getOperand(1)) &&
14438       // We don't have a good way to replace an EFLAGS use, so only do this when
14439       // dead right now.
14440       SDValue(N, 1).use_empty()) {
14441     DebugLoc DL = N->getDebugLoc();
14442     EVT VT = N->getValueType(0);
14443     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14444     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14445                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14446                                            DAG.getConstant(X86::COND_B,MVT::i8),
14447                                            N->getOperand(2)),
14448                                DAG.getConstant(1, VT));
14449     return DCI.CombineTo(N, Res1, CarryOut);
14450   }
14451
14452   return SDValue();
14453 }
14454
14455 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14456 //      (add Y, (setne X, 0)) -> sbb -1, Y
14457 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14458 //      (sub (setne X, 0), Y) -> adc -1, Y
14459 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14460   DebugLoc DL = N->getDebugLoc();
14461
14462   // Look through ZExts.
14463   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14464   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14465     return SDValue();
14466
14467   SDValue SetCC = Ext.getOperand(0);
14468   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14469     return SDValue();
14470
14471   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14472   if (CC != X86::COND_E && CC != X86::COND_NE)
14473     return SDValue();
14474
14475   SDValue Cmp = SetCC.getOperand(1);
14476   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14477       !X86::isZeroNode(Cmp.getOperand(1)) ||
14478       !Cmp.getOperand(0).getValueType().isInteger())
14479     return SDValue();
14480
14481   SDValue CmpOp0 = Cmp.getOperand(0);
14482   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14483                                DAG.getConstant(1, CmpOp0.getValueType()));
14484
14485   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14486   if (CC == X86::COND_NE)
14487     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14488                        DL, OtherVal.getValueType(), OtherVal,
14489                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14490   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14491                      DL, OtherVal.getValueType(), OtherVal,
14492                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14493 }
14494
14495 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14496 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14497                                  const X86Subtarget *Subtarget) {
14498   EVT VT = N->getValueType(0);
14499   SDValue Op0 = N->getOperand(0);
14500   SDValue Op1 = N->getOperand(1);
14501
14502   // Try to synthesize horizontal adds from adds of shuffles.
14503   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14504        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14505       isHorizontalBinOp(Op0, Op1, true))
14506     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14507
14508   return OptimizeConditionalInDecrement(N, DAG);
14509 }
14510
14511 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14512                                  const X86Subtarget *Subtarget) {
14513   SDValue Op0 = N->getOperand(0);
14514   SDValue Op1 = N->getOperand(1);
14515
14516   // X86 can't encode an immediate LHS of a sub. See if we can push the
14517   // negation into a preceding instruction.
14518   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14519     // If the RHS of the sub is a XOR with one use and a constant, invert the
14520     // immediate. Then add one to the LHS of the sub so we can turn
14521     // X-Y -> X+~Y+1, saving one register.
14522     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14523         isa<ConstantSDNode>(Op1.getOperand(1))) {
14524       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14525       EVT VT = Op0.getValueType();
14526       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14527                                    Op1.getOperand(0),
14528                                    DAG.getConstant(~XorC, VT));
14529       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14530                          DAG.getConstant(C->getAPIntValue()+1, VT));
14531     }
14532   }
14533
14534   // Try to synthesize horizontal adds from adds of shuffles.
14535   EVT VT = N->getValueType(0);
14536   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14537        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14538       isHorizontalBinOp(Op0, Op1, true))
14539     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14540
14541   return OptimizeConditionalInDecrement(N, DAG);
14542 }
14543
14544 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14545                                              DAGCombinerInfo &DCI) const {
14546   SelectionDAG &DAG = DCI.DAG;
14547   switch (N->getOpcode()) {
14548   default: break;
14549   case ISD::EXTRACT_VECTOR_ELT:
14550     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14551   case ISD::VSELECT:
14552   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14553   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14554   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14555   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14556   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14557   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14558   case ISD::SHL:
14559   case ISD::SRA:
14560   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14561   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14562   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14563   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14564   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14565   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14566   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14567   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14568   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14569   case X86ISD::FXOR:
14570   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14571   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14572   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14573   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14574   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14575   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14576   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14577   case X86ISD::SHUFPD:
14578   case X86ISD::PALIGN:
14579   case X86ISD::UNPCKH:
14580   case X86ISD::UNPCKL:
14581   case X86ISD::MOVHLPS:
14582   case X86ISD::MOVLHPS:
14583   case X86ISD::PSHUFD:
14584   case X86ISD::PSHUFHW:
14585   case X86ISD::PSHUFLW:
14586   case X86ISD::MOVSS:
14587   case X86ISD::MOVSD:
14588   case X86ISD::VPERMILP:
14589   case X86ISD::VPERM2X128:
14590   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14591   }
14592
14593   return SDValue();
14594 }
14595
14596 /// isTypeDesirableForOp - Return true if the target has native support for
14597 /// the specified value type and it is 'desirable' to use the type for the
14598 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14599 /// instruction encodings are longer and some i16 instructions are slow.
14600 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14601   if (!isTypeLegal(VT))
14602     return false;
14603   if (VT != MVT::i16)
14604     return true;
14605
14606   switch (Opc) {
14607   default:
14608     return true;
14609   case ISD::LOAD:
14610   case ISD::SIGN_EXTEND:
14611   case ISD::ZERO_EXTEND:
14612   case ISD::ANY_EXTEND:
14613   case ISD::SHL:
14614   case ISD::SRL:
14615   case ISD::SUB:
14616   case ISD::ADD:
14617   case ISD::MUL:
14618   case ISD::AND:
14619   case ISD::OR:
14620   case ISD::XOR:
14621     return false;
14622   }
14623 }
14624
14625 /// IsDesirableToPromoteOp - This method query the target whether it is
14626 /// beneficial for dag combiner to promote the specified node. If true, it
14627 /// should return the desired promotion type by reference.
14628 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14629   EVT VT = Op.getValueType();
14630   if (VT != MVT::i16)
14631     return false;
14632
14633   bool Promote = false;
14634   bool Commute = false;
14635   switch (Op.getOpcode()) {
14636   default: break;
14637   case ISD::LOAD: {
14638     LoadSDNode *LD = cast<LoadSDNode>(Op);
14639     // If the non-extending load has a single use and it's not live out, then it
14640     // might be folded.
14641     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14642                                                      Op.hasOneUse()*/) {
14643       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14644              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14645         // The only case where we'd want to promote LOAD (rather then it being
14646         // promoted as an operand is when it's only use is liveout.
14647         if (UI->getOpcode() != ISD::CopyToReg)
14648           return false;
14649       }
14650     }
14651     Promote = true;
14652     break;
14653   }
14654   case ISD::SIGN_EXTEND:
14655   case ISD::ZERO_EXTEND:
14656   case ISD::ANY_EXTEND:
14657     Promote = true;
14658     break;
14659   case ISD::SHL:
14660   case ISD::SRL: {
14661     SDValue N0 = Op.getOperand(0);
14662     // Look out for (store (shl (load), x)).
14663     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14664       return false;
14665     Promote = true;
14666     break;
14667   }
14668   case ISD::ADD:
14669   case ISD::MUL:
14670   case ISD::AND:
14671   case ISD::OR:
14672   case ISD::XOR:
14673     Commute = true;
14674     // fallthrough
14675   case ISD::SUB: {
14676     SDValue N0 = Op.getOperand(0);
14677     SDValue N1 = Op.getOperand(1);
14678     if (!Commute && MayFoldLoad(N1))
14679       return false;
14680     // Avoid disabling potential load folding opportunities.
14681     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14682       return false;
14683     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14684       return false;
14685     Promote = true;
14686   }
14687   }
14688
14689   PVT = MVT::i32;
14690   return Promote;
14691 }
14692
14693 //===----------------------------------------------------------------------===//
14694 //                           X86 Inline Assembly Support
14695 //===----------------------------------------------------------------------===//
14696
14697 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14698   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14699
14700   std::string AsmStr = IA->getAsmString();
14701
14702   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14703   SmallVector<StringRef, 4> AsmPieces;
14704   SplitString(AsmStr, AsmPieces, ";\n");
14705
14706   switch (AsmPieces.size()) {
14707   default: return false;
14708   case 1:
14709     AsmStr = AsmPieces[0];
14710     AsmPieces.clear();
14711     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14712
14713     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14714     // we will turn this bswap into something that will be lowered to logical ops
14715     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14716     // so don't worry about this.
14717     // bswap $0
14718     if (AsmPieces.size() == 2 &&
14719         (AsmPieces[0] == "bswap" ||
14720          AsmPieces[0] == "bswapq" ||
14721          AsmPieces[0] == "bswapl") &&
14722         (AsmPieces[1] == "$0" ||
14723          AsmPieces[1] == "${0:q}")) {
14724       // No need to check constraints, nothing other than the equivalent of
14725       // "=r,0" would be valid here.
14726       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14727       if (!Ty || Ty->getBitWidth() % 16 != 0)
14728         return false;
14729       return IntrinsicLowering::LowerToByteSwap(CI);
14730     }
14731     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14732     if (CI->getType()->isIntegerTy(16) &&
14733         AsmPieces.size() == 3 &&
14734         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14735         AsmPieces[1] == "$$8," &&
14736         AsmPieces[2] == "${0:w}" &&
14737         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14738       AsmPieces.clear();
14739       const std::string &ConstraintsStr = IA->getConstraintString();
14740       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14741       std::sort(AsmPieces.begin(), AsmPieces.end());
14742       if (AsmPieces.size() == 4 &&
14743           AsmPieces[0] == "~{cc}" &&
14744           AsmPieces[1] == "~{dirflag}" &&
14745           AsmPieces[2] == "~{flags}" &&
14746           AsmPieces[3] == "~{fpsr}") {
14747         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14748         if (!Ty || Ty->getBitWidth() % 16 != 0)
14749           return false;
14750         return IntrinsicLowering::LowerToByteSwap(CI);
14751       }
14752     }
14753     break;
14754   case 3:
14755     if (CI->getType()->isIntegerTy(32) &&
14756         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14757       SmallVector<StringRef, 4> Words;
14758       SplitString(AsmPieces[0], Words, " \t,");
14759       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14760           Words[2] == "${0:w}") {
14761         Words.clear();
14762         SplitString(AsmPieces[1], Words, " \t,");
14763         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14764             Words[2] == "$0") {
14765           Words.clear();
14766           SplitString(AsmPieces[2], Words, " \t,");
14767           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14768               Words[2] == "${0:w}") {
14769             AsmPieces.clear();
14770             const std::string &ConstraintsStr = IA->getConstraintString();
14771             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14772             std::sort(AsmPieces.begin(), AsmPieces.end());
14773             if (AsmPieces.size() == 4 &&
14774                 AsmPieces[0] == "~{cc}" &&
14775                 AsmPieces[1] == "~{dirflag}" &&
14776                 AsmPieces[2] == "~{flags}" &&
14777                 AsmPieces[3] == "~{fpsr}") {
14778               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14779               if (!Ty || Ty->getBitWidth() % 16 != 0)
14780                 return false;
14781               return IntrinsicLowering::LowerToByteSwap(CI);
14782             }
14783           }
14784         }
14785       }
14786     }
14787
14788     if (CI->getType()->isIntegerTy(64)) {
14789       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14790       if (Constraints.size() >= 2 &&
14791           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14792           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14793         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14794         SmallVector<StringRef, 4> Words;
14795         SplitString(AsmPieces[0], Words, " \t");
14796         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14797           Words.clear();
14798           SplitString(AsmPieces[1], Words, " \t");
14799           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14800             Words.clear();
14801             SplitString(AsmPieces[2], Words, " \t,");
14802             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14803                 Words[2] == "%edx") {
14804               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14805               if (!Ty || Ty->getBitWidth() % 16 != 0)
14806                 return false;
14807               return IntrinsicLowering::LowerToByteSwap(CI);
14808             }
14809           }
14810         }
14811       }
14812     }
14813     break;
14814   }
14815   return false;
14816 }
14817
14818
14819
14820 /// getConstraintType - Given a constraint letter, return the type of
14821 /// constraint it is for this target.
14822 X86TargetLowering::ConstraintType
14823 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14824   if (Constraint.size() == 1) {
14825     switch (Constraint[0]) {
14826     case 'R':
14827     case 'q':
14828     case 'Q':
14829     case 'f':
14830     case 't':
14831     case 'u':
14832     case 'y':
14833     case 'x':
14834     case 'Y':
14835     case 'l':
14836       return C_RegisterClass;
14837     case 'a':
14838     case 'b':
14839     case 'c':
14840     case 'd':
14841     case 'S':
14842     case 'D':
14843     case 'A':
14844       return C_Register;
14845     case 'I':
14846     case 'J':
14847     case 'K':
14848     case 'L':
14849     case 'M':
14850     case 'N':
14851     case 'G':
14852     case 'C':
14853     case 'e':
14854     case 'Z':
14855       return C_Other;
14856     default:
14857       break;
14858     }
14859   }
14860   return TargetLowering::getConstraintType(Constraint);
14861 }
14862
14863 /// Examine constraint type and operand type and determine a weight value.
14864 /// This object must already have been set up with the operand type
14865 /// and the current alternative constraint selected.
14866 TargetLowering::ConstraintWeight
14867   X86TargetLowering::getSingleConstraintMatchWeight(
14868     AsmOperandInfo &info, const char *constraint) const {
14869   ConstraintWeight weight = CW_Invalid;
14870   Value *CallOperandVal = info.CallOperandVal;
14871     // If we don't have a value, we can't do a match,
14872     // but allow it at the lowest weight.
14873   if (CallOperandVal == NULL)
14874     return CW_Default;
14875   Type *type = CallOperandVal->getType();
14876   // Look at the constraint type.
14877   switch (*constraint) {
14878   default:
14879     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14880   case 'R':
14881   case 'q':
14882   case 'Q':
14883   case 'a':
14884   case 'b':
14885   case 'c':
14886   case 'd':
14887   case 'S':
14888   case 'D':
14889   case 'A':
14890     if (CallOperandVal->getType()->isIntegerTy())
14891       weight = CW_SpecificReg;
14892     break;
14893   case 'f':
14894   case 't':
14895   case 'u':
14896       if (type->isFloatingPointTy())
14897         weight = CW_SpecificReg;
14898       break;
14899   case 'y':
14900       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14901         weight = CW_SpecificReg;
14902       break;
14903   case 'x':
14904   case 'Y':
14905     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14906       weight = CW_Register;
14907     break;
14908   case 'I':
14909     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14910       if (C->getZExtValue() <= 31)
14911         weight = CW_Constant;
14912     }
14913     break;
14914   case 'J':
14915     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14916       if (C->getZExtValue() <= 63)
14917         weight = CW_Constant;
14918     }
14919     break;
14920   case 'K':
14921     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14922       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14923         weight = CW_Constant;
14924     }
14925     break;
14926   case 'L':
14927     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14928       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14929         weight = CW_Constant;
14930     }
14931     break;
14932   case 'M':
14933     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14934       if (C->getZExtValue() <= 3)
14935         weight = CW_Constant;
14936     }
14937     break;
14938   case 'N':
14939     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14940       if (C->getZExtValue() <= 0xff)
14941         weight = CW_Constant;
14942     }
14943     break;
14944   case 'G':
14945   case 'C':
14946     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14947       weight = CW_Constant;
14948     }
14949     break;
14950   case 'e':
14951     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14952       if ((C->getSExtValue() >= -0x80000000LL) &&
14953           (C->getSExtValue() <= 0x7fffffffLL))
14954         weight = CW_Constant;
14955     }
14956     break;
14957   case 'Z':
14958     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14959       if (C->getZExtValue() <= 0xffffffff)
14960         weight = CW_Constant;
14961     }
14962     break;
14963   }
14964   return weight;
14965 }
14966
14967 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14968 /// with another that has more specific requirements based on the type of the
14969 /// corresponding operand.
14970 const char *X86TargetLowering::
14971 LowerXConstraint(EVT ConstraintVT) const {
14972   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14973   // 'f' like normal targets.
14974   if (ConstraintVT.isFloatingPoint()) {
14975     if (Subtarget->hasXMMInt())
14976       return "Y";
14977     if (Subtarget->hasXMM())
14978       return "x";
14979   }
14980
14981   return TargetLowering::LowerXConstraint(ConstraintVT);
14982 }
14983
14984 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14985 /// vector.  If it is invalid, don't add anything to Ops.
14986 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14987                                                      std::string &Constraint,
14988                                                      std::vector<SDValue>&Ops,
14989                                                      SelectionDAG &DAG) const {
14990   SDValue Result(0, 0);
14991
14992   // Only support length 1 constraints for now.
14993   if (Constraint.length() > 1) return;
14994
14995   char ConstraintLetter = Constraint[0];
14996   switch (ConstraintLetter) {
14997   default: break;
14998   case 'I':
14999     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15000       if (C->getZExtValue() <= 31) {
15001         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15002         break;
15003       }
15004     }
15005     return;
15006   case 'J':
15007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15008       if (C->getZExtValue() <= 63) {
15009         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15010         break;
15011       }
15012     }
15013     return;
15014   case 'K':
15015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15016       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15017         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15018         break;
15019       }
15020     }
15021     return;
15022   case 'N':
15023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15024       if (C->getZExtValue() <= 255) {
15025         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15026         break;
15027       }
15028     }
15029     return;
15030   case 'e': {
15031     // 32-bit signed value
15032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15033       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15034                                            C->getSExtValue())) {
15035         // Widen to 64 bits here to get it sign extended.
15036         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15037         break;
15038       }
15039     // FIXME gcc accepts some relocatable values here too, but only in certain
15040     // memory models; it's complicated.
15041     }
15042     return;
15043   }
15044   case 'Z': {
15045     // 32-bit unsigned value
15046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15047       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15048                                            C->getZExtValue())) {
15049         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15050         break;
15051       }
15052     }
15053     // FIXME gcc accepts some relocatable values here too, but only in certain
15054     // memory models; it's complicated.
15055     return;
15056   }
15057   case 'i': {
15058     // Literal immediates are always ok.
15059     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15060       // Widen to 64 bits here to get it sign extended.
15061       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15062       break;
15063     }
15064
15065     // In any sort of PIC mode addresses need to be computed at runtime by
15066     // adding in a register or some sort of table lookup.  These can't
15067     // be used as immediates.
15068     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15069       return;
15070
15071     // If we are in non-pic codegen mode, we allow the address of a global (with
15072     // an optional displacement) to be used with 'i'.
15073     GlobalAddressSDNode *GA = 0;
15074     int64_t Offset = 0;
15075
15076     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15077     while (1) {
15078       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15079         Offset += GA->getOffset();
15080         break;
15081       } else if (Op.getOpcode() == ISD::ADD) {
15082         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15083           Offset += C->getZExtValue();
15084           Op = Op.getOperand(0);
15085           continue;
15086         }
15087       } else if (Op.getOpcode() == ISD::SUB) {
15088         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15089           Offset += -C->getZExtValue();
15090           Op = Op.getOperand(0);
15091           continue;
15092         }
15093       }
15094
15095       // Otherwise, this isn't something we can handle, reject it.
15096       return;
15097     }
15098
15099     const GlobalValue *GV = GA->getGlobal();
15100     // If we require an extra load to get this address, as in PIC mode, we
15101     // can't accept it.
15102     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15103                                                         getTargetMachine())))
15104       return;
15105
15106     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15107                                         GA->getValueType(0), Offset);
15108     break;
15109   }
15110   }
15111
15112   if (Result.getNode()) {
15113     Ops.push_back(Result);
15114     return;
15115   }
15116   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15117 }
15118
15119 std::pair<unsigned, const TargetRegisterClass*>
15120 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15121                                                 EVT VT) const {
15122   // First, see if this is a constraint that directly corresponds to an LLVM
15123   // register class.
15124   if (Constraint.size() == 1) {
15125     // GCC Constraint Letters
15126     switch (Constraint[0]) {
15127     default: break;
15128       // TODO: Slight differences here in allocation order and leaving
15129       // RIP in the class. Do they matter any more here than they do
15130       // in the normal allocation?
15131     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15132       if (Subtarget->is64Bit()) {
15133         if (VT == MVT::i32 || VT == MVT::f32)
15134           return std::make_pair(0U, X86::GR32RegisterClass);
15135         else if (VT == MVT::i16)
15136           return std::make_pair(0U, X86::GR16RegisterClass);
15137         else if (VT == MVT::i8 || VT == MVT::i1)
15138           return std::make_pair(0U, X86::GR8RegisterClass);
15139         else if (VT == MVT::i64 || VT == MVT::f64)
15140           return std::make_pair(0U, X86::GR64RegisterClass);
15141         break;
15142       }
15143       // 32-bit fallthrough
15144     case 'Q':   // Q_REGS
15145       if (VT == MVT::i32 || VT == MVT::f32)
15146         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15147       else if (VT == MVT::i16)
15148         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15149       else if (VT == MVT::i8 || VT == MVT::i1)
15150         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15151       else if (VT == MVT::i64)
15152         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15153       break;
15154     case 'r':   // GENERAL_REGS
15155     case 'l':   // INDEX_REGS
15156       if (VT == MVT::i8 || VT == MVT::i1)
15157         return std::make_pair(0U, X86::GR8RegisterClass);
15158       if (VT == MVT::i16)
15159         return std::make_pair(0U, X86::GR16RegisterClass);
15160       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15161         return std::make_pair(0U, X86::GR32RegisterClass);
15162       return std::make_pair(0U, X86::GR64RegisterClass);
15163     case 'R':   // LEGACY_REGS
15164       if (VT == MVT::i8 || VT == MVT::i1)
15165         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15166       if (VT == MVT::i16)
15167         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15168       if (VT == MVT::i32 || !Subtarget->is64Bit())
15169         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15170       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15171     case 'f':  // FP Stack registers.
15172       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15173       // value to the correct fpstack register class.
15174       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15175         return std::make_pair(0U, X86::RFP32RegisterClass);
15176       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15177         return std::make_pair(0U, X86::RFP64RegisterClass);
15178       return std::make_pair(0U, X86::RFP80RegisterClass);
15179     case 'y':   // MMX_REGS if MMX allowed.
15180       if (!Subtarget->hasMMX()) break;
15181       return std::make_pair(0U, X86::VR64RegisterClass);
15182     case 'Y':   // SSE_REGS if SSE2 allowed
15183       if (!Subtarget->hasXMMInt()) break;
15184       // FALL THROUGH.
15185     case 'x':   // SSE_REGS if SSE1 allowed
15186       if (!Subtarget->hasXMM()) break;
15187
15188       switch (VT.getSimpleVT().SimpleTy) {
15189       default: break;
15190       // Scalar SSE types.
15191       case MVT::f32:
15192       case MVT::i32:
15193         return std::make_pair(0U, X86::FR32RegisterClass);
15194       case MVT::f64:
15195       case MVT::i64:
15196         return std::make_pair(0U, X86::FR64RegisterClass);
15197       // Vector types.
15198       case MVT::v16i8:
15199       case MVT::v8i16:
15200       case MVT::v4i32:
15201       case MVT::v2i64:
15202       case MVT::v4f32:
15203       case MVT::v2f64:
15204         return std::make_pair(0U, X86::VR128RegisterClass);
15205       }
15206       break;
15207     }
15208   }
15209
15210   // Use the default implementation in TargetLowering to convert the register
15211   // constraint into a member of a register class.
15212   std::pair<unsigned, const TargetRegisterClass*> Res;
15213   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15214
15215   // Not found as a standard register?
15216   if (Res.second == 0) {
15217     // Map st(0) -> st(7) -> ST0
15218     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15219         tolower(Constraint[1]) == 's' &&
15220         tolower(Constraint[2]) == 't' &&
15221         Constraint[3] == '(' &&
15222         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15223         Constraint[5] == ')' &&
15224         Constraint[6] == '}') {
15225
15226       Res.first = X86::ST0+Constraint[4]-'0';
15227       Res.second = X86::RFP80RegisterClass;
15228       return Res;
15229     }
15230
15231     // GCC allows "st(0)" to be called just plain "st".
15232     if (StringRef("{st}").equals_lower(Constraint)) {
15233       Res.first = X86::ST0;
15234       Res.second = X86::RFP80RegisterClass;
15235       return Res;
15236     }
15237
15238     // flags -> EFLAGS
15239     if (StringRef("{flags}").equals_lower(Constraint)) {
15240       Res.first = X86::EFLAGS;
15241       Res.second = X86::CCRRegisterClass;
15242       return Res;
15243     }
15244
15245     // 'A' means EAX + EDX.
15246     if (Constraint == "A") {
15247       Res.first = X86::EAX;
15248       Res.second = X86::GR32_ADRegisterClass;
15249       return Res;
15250     }
15251     return Res;
15252   }
15253
15254   // Otherwise, check to see if this is a register class of the wrong value
15255   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15256   // turn into {ax},{dx}.
15257   if (Res.second->hasType(VT))
15258     return Res;   // Correct type already, nothing to do.
15259
15260   // All of the single-register GCC register classes map their values onto
15261   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15262   // really want an 8-bit or 32-bit register, map to the appropriate register
15263   // class and return the appropriate register.
15264   if (Res.second == X86::GR16RegisterClass) {
15265     if (VT == MVT::i8) {
15266       unsigned DestReg = 0;
15267       switch (Res.first) {
15268       default: break;
15269       case X86::AX: DestReg = X86::AL; break;
15270       case X86::DX: DestReg = X86::DL; break;
15271       case X86::CX: DestReg = X86::CL; break;
15272       case X86::BX: DestReg = X86::BL; break;
15273       }
15274       if (DestReg) {
15275         Res.first = DestReg;
15276         Res.second = X86::GR8RegisterClass;
15277       }
15278     } else if (VT == MVT::i32) {
15279       unsigned DestReg = 0;
15280       switch (Res.first) {
15281       default: break;
15282       case X86::AX: DestReg = X86::EAX; break;
15283       case X86::DX: DestReg = X86::EDX; break;
15284       case X86::CX: DestReg = X86::ECX; break;
15285       case X86::BX: DestReg = X86::EBX; break;
15286       case X86::SI: DestReg = X86::ESI; break;
15287       case X86::DI: DestReg = X86::EDI; break;
15288       case X86::BP: DestReg = X86::EBP; break;
15289       case X86::SP: DestReg = X86::ESP; break;
15290       }
15291       if (DestReg) {
15292         Res.first = DestReg;
15293         Res.second = X86::GR32RegisterClass;
15294       }
15295     } else if (VT == MVT::i64) {
15296       unsigned DestReg = 0;
15297       switch (Res.first) {
15298       default: break;
15299       case X86::AX: DestReg = X86::RAX; break;
15300       case X86::DX: DestReg = X86::RDX; break;
15301       case X86::CX: DestReg = X86::RCX; break;
15302       case X86::BX: DestReg = X86::RBX; break;
15303       case X86::SI: DestReg = X86::RSI; break;
15304       case X86::DI: DestReg = X86::RDI; break;
15305       case X86::BP: DestReg = X86::RBP; break;
15306       case X86::SP: DestReg = X86::RSP; break;
15307       }
15308       if (DestReg) {
15309         Res.first = DestReg;
15310         Res.second = X86::GR64RegisterClass;
15311       }
15312     }
15313   } else if (Res.second == X86::FR32RegisterClass ||
15314              Res.second == X86::FR64RegisterClass ||
15315              Res.second == X86::VR128RegisterClass) {
15316     // Handle references to XMM physical registers that got mapped into the
15317     // wrong class.  This can happen with constraints like {xmm0} where the
15318     // target independent register mapper will just pick the first match it can
15319     // find, ignoring the required type.
15320     if (VT == MVT::f32)
15321       Res.second = X86::FR32RegisterClass;
15322     else if (VT == MVT::f64)
15323       Res.second = X86::FR64RegisterClass;
15324     else if (X86::VR128RegisterClass->hasType(VT))
15325       Res.second = X86::VR128RegisterClass;
15326   }
15327
15328   return Res;
15329 }