Eliminate LegalizeOps' LegalizedNodes map and have it just call RAUW
[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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   if (Subtarget->hasBMI()) {
383     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
384   } else {
385     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
387     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
388     if (Subtarget->is64Bit())
389       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
390   }
391
392   if (Subtarget->hasLZCNT()) {
393     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
394   } else {
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasPOPCNT()) {
403     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
404   } else {
405     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
407     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
410   }
411
412   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
413   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
414
415   // These should be promoted to a larger select which is supported.
416   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
417   // X86 wants to expand cmov itself.
418   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
423   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
430   if (Subtarget->is64Bit()) {
431     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
432     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
433   }
434   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
435
436   // Darwin ABI issue.
437   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
438   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
440   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
441   if (Subtarget->is64Bit())
442     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
444   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
447     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
448     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
449     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
450     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
451   }
452   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
455   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
459     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
460   }
461
462   if (Subtarget->hasXMM())
463     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
464
465   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
466   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
467
468   // On X86 and X86-64, atomic operations are lowered to locked instructions.
469   // Locked instructions, in turn, have implicit fence semantics (all memory
470   // operations are flushed before issuing the locked instruction, and they
471   // are not buffered), so we can fold away the common pattern of
472   // fence-atomic-fence.
473   setShouldFoldAtomicFences(true);
474
475   // Expand certain atomics
476   for (unsigned i = 0, e = 4; i != e; ++i) {
477     MVT VT = IntVTs[i];
478     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
481   }
482
483   if (!Subtarget->is64Bit()) {
484     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
492   }
493
494   if (Subtarget->hasCmpxchg16b()) {
495     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
496   }
497
498   // FIXME - use subtarget debug flags
499   if (!Subtarget->isTargetDarwin() &&
500       !Subtarget->isTargetELF() &&
501       !Subtarget->isTargetCygMing()) {
502     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
507   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
509   if (Subtarget->is64Bit()) {
510     setExceptionPointerRegister(X86::RAX);
511     setExceptionSelectorRegister(X86::RDX);
512   } else {
513     setExceptionPointerRegister(X86::EAX);
514     setExceptionSelectorRegister(X86::EDX);
515   }
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518
519   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521
522   setOperationAction(ISD::TRAP, MVT::Other, Legal);
523
524   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
526   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
529     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
530   } else {
531     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
532     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
533   }
534
535   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
536   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
537
538   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540                        MVT::i64 : MVT::i32, Custom);
541   else if (EnableSegmentedStacks)
542     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543                        MVT::i64 : MVT::i32, Custom);
544   else
545     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546                        MVT::i64 : MVT::i32, Expand);
547
548   if (!UseSoftFloat && X86ScalarSSEf64) {
549     // f32 and f64 use SSE.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553
554     // Use ANDPD to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f64, Custom);
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f64, Custom);
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     // Use ANDPD and ORPD to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // Lower this to FGETSIGNx86 plus an AND.
567     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569
570     // We don't support sin/cos/fmod
571     setOperationAction(ISD::FSIN , MVT::f64, Expand);
572     setOperationAction(ISD::FCOS , MVT::f64, Expand);
573     setOperationAction(ISD::FSIN , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS , MVT::f32, Expand);
575
576     // Expand FP immediates into loads from the stack, except for the special
577     // cases we handle.
578     addLegalFPImmediate(APFloat(+0.0)); // xorpd
579     addLegalFPImmediate(APFloat(+0.0f)); // xorps
580   } else if (!UseSoftFloat && X86ScalarSSEf32) {
581     // Use SSE for f32, x87 for f64.
582     // Set up the FP register classes.
583     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585
586     // Use ANDPS to simulate FABS.
587     setOperationAction(ISD::FABS , MVT::f32, Custom);
588
589     // Use XORP to simulate FNEG.
590     setOperationAction(ISD::FNEG , MVT::f32, Custom);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593
594     // Use ANDPS and ORPS to simulate FCOPYSIGN.
595     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597
598     // We don't support sin/cos/fmod
599     setOperationAction(ISD::FSIN , MVT::f32, Expand);
600     setOperationAction(ISD::FCOS , MVT::f32, Expand);
601
602     // Special cases we handle for FP constants.
603     addLegalFPImmediate(APFloat(+0.0f)); // xorps
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608
609     if (!UnsafeFPMath) {
610       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
611       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
612     }
613   } else if (!UseSoftFloat) {
614     // f32 and f64 in x87.
615     // Set up the FP register classes.
616     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618
619     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
620     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
623
624     if (!UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628     addLegalFPImmediate(APFloat(+0.0)); // FLD0
629     addLegalFPImmediate(APFloat(+1.0)); // FLD1
630     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
636   }
637
638   // We don't support FMA.
639   setOperationAction(ISD::FMA, MVT::f64, Expand);
640   setOperationAction(ISD::FMA, MVT::f32, Expand);
641
642   // Long double always uses X87.
643   if (!UseSoftFloat) {
644     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647     {
648       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649       addLegalFPImmediate(TmpFlt);  // FLD0
650       TmpFlt.changeSign();
651       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
652
653       bool ignored;
654       APFloat TmpFlt2(+1.0);
655       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656                       &ignored);
657       addLegalFPImmediate(TmpFlt2);  // FLD1
658       TmpFlt2.changeSign();
659       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
660     }
661
662     if (!UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
665     }
666
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680
681   // First set operation action for all vector types to either promote
682   // (for widening) or expand (for scalarization). Then we will selectively
683   // turn on ones that can be effectively codegen'd.
684   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
932     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
933     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
934     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
935     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
936
937     // i8 and i16 vectors are custom , because the source register and source
938     // source memory operand types are not the same width.  f32 vectors are
939     // custom since the immediate controlling the insert encodes additional
940     // information.
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
944     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
945
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950
951     if (Subtarget->is64Bit()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
953       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
954     }
955   }
956
957   if (Subtarget->hasXMMInt()) {
958     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
959     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
960     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
961     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
962
963     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
964     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
966
967     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
968     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
969   }
970
971   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
972     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
973
974   if (!UseSoftFloat && Subtarget->hasAVX()) {
975     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
976     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
977     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
978     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
979     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
980     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
981
982     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
983     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
984     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
985
986     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
988     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
989     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
990     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
991     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
992
993     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
995     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
996     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
997     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
998     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
999
1000     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1001     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1002     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1003
1004     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1005     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1006     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1007     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1008     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1009     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1013     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1015
1016     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1017     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1019     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1020
1021     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1022     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1023
1024     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1025     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1026     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1027     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1028
1029     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1030     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1031     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1034     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1035     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1036     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1037
1038     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1039     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1040     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1041     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1042
1043     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1044     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1045     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1046     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1047
1048     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1049     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1050     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1051     // Don't lower v32i8 because there is no 128-bit byte mul
1052
1053     // Custom lower several nodes for 256-bit types.
1054     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1055                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1056       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1057       EVT VT = SVT;
1058
1059       // Extract subvector is special because the value type
1060       // (result) is 128-bit but the source is 256-bit wide.
1061       if (VT.is128BitVector())
1062         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1063
1064       // Do not attempt to custom lower other non-256-bit vectors
1065       if (!VT.is256BitVector())
1066         continue;
1067
1068       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1069       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1070       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1071       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1072       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1073       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1074     }
1075
1076     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1077     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1078       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1079       EVT VT = SVT;
1080
1081       // Do not attempt to promote non-256-bit vectors
1082       if (!VT.is256BitVector())
1083         continue;
1084
1085       setOperationAction(ISD::AND,    SVT, Promote);
1086       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1087       setOperationAction(ISD::OR,     SVT, Promote);
1088       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1089       setOperationAction(ISD::XOR,    SVT, Promote);
1090       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1091       setOperationAction(ISD::LOAD,   SVT, Promote);
1092       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1093       setOperationAction(ISD::SELECT, SVT, Promote);
1094       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1095     }
1096   }
1097
1098   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1099   // of this type with custom code.
1100   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1101          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1102     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1103   }
1104
1105   // We want to custom lower some of our intrinsics.
1106   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1107
1108
1109   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1110   // handle type legalization for these operations here.
1111   //
1112   // FIXME: We really should do custom legalization for addition and
1113   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1114   // than generic legalization for 64-bit multiplication-with-overflow, though.
1115   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1116     // Add/Sub/Mul with overflow operations are custom lowered.
1117     MVT VT = IntVTs[i];
1118     setOperationAction(ISD::SADDO, VT, Custom);
1119     setOperationAction(ISD::UADDO, VT, Custom);
1120     setOperationAction(ISD::SSUBO, VT, Custom);
1121     setOperationAction(ISD::USUBO, VT, Custom);
1122     setOperationAction(ISD::SMULO, VT, Custom);
1123     setOperationAction(ISD::UMULO, VT, Custom);
1124   }
1125
1126   // There are no 8-bit 3-address imul/mul instructions
1127   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1128   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1129
1130   if (!Subtarget->is64Bit()) {
1131     // These libcalls are not available in 32-bit.
1132     setLibcallName(RTLIB::SHL_I128, 0);
1133     setLibcallName(RTLIB::SRL_I128, 0);
1134     setLibcallName(RTLIB::SRA_I128, 0);
1135   }
1136
1137   // We have target-specific dag combine patterns for the following nodes:
1138   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1139   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1140   setTargetDAGCombine(ISD::BUILD_VECTOR);
1141   setTargetDAGCombine(ISD::VSELECT);
1142   setTargetDAGCombine(ISD::SELECT);
1143   setTargetDAGCombine(ISD::SHL);
1144   setTargetDAGCombine(ISD::SRA);
1145   setTargetDAGCombine(ISD::SRL);
1146   setTargetDAGCombine(ISD::OR);
1147   setTargetDAGCombine(ISD::AND);
1148   setTargetDAGCombine(ISD::ADD);
1149   setTargetDAGCombine(ISD::FADD);
1150   setTargetDAGCombine(ISD::FSUB);
1151   setTargetDAGCombine(ISD::SUB);
1152   setTargetDAGCombine(ISD::LOAD);
1153   setTargetDAGCombine(ISD::STORE);
1154   setTargetDAGCombine(ISD::ZERO_EXTEND);
1155   setTargetDAGCombine(ISD::SINT_TO_FP);
1156   if (Subtarget->is64Bit())
1157     setTargetDAGCombine(ISD::MUL);
1158   if (Subtarget->hasBMI())
1159     setTargetDAGCombine(ISD::XOR);
1160
1161   computeRegisterProperties();
1162
1163   // On Darwin, -Os means optimize for size without hurting performance,
1164   // do not reduce the limit.
1165   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1166   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1167   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1168   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1169   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1170   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1171   setPrefLoopAlignment(16);
1172   benefitFromCodePlacementOpt = true;
1173
1174   setPrefFunctionAlignment(4);
1175 }
1176
1177
1178 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1179   if (!VT.isVector()) return MVT::i8;
1180   return VT.changeVectorElementTypeToInteger();
1181 }
1182
1183
1184 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1185 /// the desired ByVal argument alignment.
1186 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1187   if (MaxAlign == 16)
1188     return;
1189   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1190     if (VTy->getBitWidth() == 128)
1191       MaxAlign = 16;
1192   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1193     unsigned EltAlign = 0;
1194     getMaxByValAlign(ATy->getElementType(), EltAlign);
1195     if (EltAlign > MaxAlign)
1196       MaxAlign = EltAlign;
1197   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1198     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1199       unsigned EltAlign = 0;
1200       getMaxByValAlign(STy->getElementType(i), EltAlign);
1201       if (EltAlign > MaxAlign)
1202         MaxAlign = EltAlign;
1203       if (MaxAlign == 16)
1204         break;
1205     }
1206   }
1207   return;
1208 }
1209
1210 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1211 /// function arguments in the caller parameter area. For X86, aggregates
1212 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1213 /// are at 4-byte boundaries.
1214 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1215   if (Subtarget->is64Bit()) {
1216     // Max of 8 and alignment of type.
1217     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1218     if (TyAlign > 8)
1219       return TyAlign;
1220     return 8;
1221   }
1222
1223   unsigned Align = 4;
1224   if (Subtarget->hasXMM())
1225     getMaxByValAlign(Ty, Align);
1226   return Align;
1227 }
1228
1229 /// getOptimalMemOpType - Returns the target specific optimal type for load
1230 /// and store operations as a result of memset, memcpy, and memmove
1231 /// lowering. If DstAlign is zero that means it's safe to destination
1232 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1233 /// means there isn't a need to check it against alignment requirement,
1234 /// probably because the source does not need to be loaded. If
1235 /// 'IsZeroVal' is true, that means it's safe to return a
1236 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1237 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1238 /// constant so it does not need to be loaded.
1239 /// It returns EVT::Other if the type should be determined using generic
1240 /// target-independent logic.
1241 EVT
1242 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1243                                        unsigned DstAlign, unsigned SrcAlign,
1244                                        bool IsZeroVal,
1245                                        bool MemcpyStrSrc,
1246                                        MachineFunction &MF) const {
1247   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1248   // linux.  This is because the stack realignment code can't handle certain
1249   // cases like PR2962.  This should be removed when PR2962 is fixed.
1250   const Function *F = MF.getFunction();
1251   if (IsZeroVal &&
1252       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1253     if (Size >= 16 &&
1254         (Subtarget->isUnalignedMemAccessFast() ||
1255          ((DstAlign == 0 || DstAlign >= 16) &&
1256           (SrcAlign == 0 || SrcAlign >= 16))) &&
1257         Subtarget->getStackAlignment() >= 16) {
1258       if (Subtarget->hasAVX() &&
1259           Subtarget->getStackAlignment() >= 32)
1260         return MVT::v8f32;
1261       if (Subtarget->hasXMMInt())
1262         return MVT::v4i32;
1263       if (Subtarget->hasXMM())
1264         return MVT::v4f32;
1265     } else if (!MemcpyStrSrc && Size >= 8 &&
1266                !Subtarget->is64Bit() &&
1267                Subtarget->getStackAlignment() >= 8 &&
1268                Subtarget->hasXMMInt()) {
1269       // Do not use f64 to lower memcpy if source is string constant. It's
1270       // better to use i32 to avoid the loads.
1271       return MVT::f64;
1272     }
1273   }
1274   if (Subtarget->is64Bit() && Size >= 8)
1275     return MVT::i64;
1276   return MVT::i32;
1277 }
1278
1279 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1280 /// current function.  The returned value is a member of the
1281 /// MachineJumpTableInfo::JTEntryKind enum.
1282 unsigned X86TargetLowering::getJumpTableEncoding() const {
1283   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1284   // symbol.
1285   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1286       Subtarget->isPICStyleGOT())
1287     return MachineJumpTableInfo::EK_Custom32;
1288
1289   // Otherwise, use the normal jump table encoding heuristics.
1290   return TargetLowering::getJumpTableEncoding();
1291 }
1292
1293 const MCExpr *
1294 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1295                                              const MachineBasicBlock *MBB,
1296                                              unsigned uid,MCContext &Ctx) const{
1297   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1298          Subtarget->isPICStyleGOT());
1299   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1300   // entries.
1301   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1302                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1303 }
1304
1305 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1306 /// jumptable.
1307 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1308                                                     SelectionDAG &DAG) const {
1309   if (!Subtarget->is64Bit())
1310     // This doesn't have DebugLoc associated with it, but is not really the
1311     // same as a Register.
1312     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1313   return Table;
1314 }
1315
1316 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1317 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1318 /// MCExpr.
1319 const MCExpr *X86TargetLowering::
1320 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1321                              MCContext &Ctx) const {
1322   // X86-64 uses RIP relative addressing based on the jump table label.
1323   if (Subtarget->isPICStyleRIPRel())
1324     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1325
1326   // Otherwise, the reference is relative to the PIC base.
1327   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1328 }
1329
1330 // FIXME: Why this routine is here? Move to RegInfo!
1331 std::pair<const TargetRegisterClass*, uint8_t>
1332 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1333   const TargetRegisterClass *RRC = 0;
1334   uint8_t Cost = 1;
1335   switch (VT.getSimpleVT().SimpleTy) {
1336   default:
1337     return TargetLowering::findRepresentativeClass(VT);
1338   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1339     RRC = (Subtarget->is64Bit()
1340            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1341     break;
1342   case MVT::x86mmx:
1343     RRC = X86::VR64RegisterClass;
1344     break;
1345   case MVT::f32: case MVT::f64:
1346   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1347   case MVT::v4f32: case MVT::v2f64:
1348   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1349   case MVT::v4f64:
1350     RRC = X86::VR128RegisterClass;
1351     break;
1352   }
1353   return std::make_pair(RRC, Cost);
1354 }
1355
1356 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1357                                                unsigned &Offset) const {
1358   if (!Subtarget->isTargetLinux())
1359     return false;
1360
1361   if (Subtarget->is64Bit()) {
1362     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1363     Offset = 0x28;
1364     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1365       AddressSpace = 256;
1366     else
1367       AddressSpace = 257;
1368   } else {
1369     // %gs:0x14 on i386
1370     Offset = 0x14;
1371     AddressSpace = 256;
1372   }
1373   return true;
1374 }
1375
1376
1377 //===----------------------------------------------------------------------===//
1378 //               Return Value Calling Convention Implementation
1379 //===----------------------------------------------------------------------===//
1380
1381 #include "X86GenCallingConv.inc"
1382
1383 bool
1384 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1385                                   MachineFunction &MF, bool isVarArg,
1386                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1387                         LLVMContext &Context) const {
1388   SmallVector<CCValAssign, 16> RVLocs;
1389   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1390                  RVLocs, Context);
1391   return CCInfo.CheckReturn(Outs, RetCC_X86);
1392 }
1393
1394 SDValue
1395 X86TargetLowering::LowerReturn(SDValue Chain,
1396                                CallingConv::ID CallConv, bool isVarArg,
1397                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1398                                const SmallVectorImpl<SDValue> &OutVals,
1399                                DebugLoc dl, SelectionDAG &DAG) const {
1400   MachineFunction &MF = DAG.getMachineFunction();
1401   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1402
1403   SmallVector<CCValAssign, 16> RVLocs;
1404   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1405                  RVLocs, *DAG.getContext());
1406   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1407
1408   // Add the regs to the liveout set for the function.
1409   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1410   for (unsigned i = 0; i != RVLocs.size(); ++i)
1411     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1412       MRI.addLiveOut(RVLocs[i].getLocReg());
1413
1414   SDValue Flag;
1415
1416   SmallVector<SDValue, 6> RetOps;
1417   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1418   // Operand #1 = Bytes To Pop
1419   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1420                    MVT::i16));
1421
1422   // Copy the result values into the output registers.
1423   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1424     CCValAssign &VA = RVLocs[i];
1425     assert(VA.isRegLoc() && "Can only return in registers!");
1426     SDValue ValToCopy = OutVals[i];
1427     EVT ValVT = ValToCopy.getValueType();
1428
1429     // If this is x86-64, and we disabled SSE, we can't return FP values,
1430     // or SSE or MMX vectors.
1431     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1432          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1433           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1434       report_fatal_error("SSE register return with SSE disabled");
1435     }
1436     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1437     // llvm-gcc has never done it right and no one has noticed, so this
1438     // should be OK for now.
1439     if (ValVT == MVT::f64 &&
1440         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1441       report_fatal_error("SSE2 register return with SSE2 disabled");
1442
1443     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1444     // the RET instruction and handled by the FP Stackifier.
1445     if (VA.getLocReg() == X86::ST0 ||
1446         VA.getLocReg() == X86::ST1) {
1447       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1448       // change the value to the FP stack register class.
1449       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1450         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1451       RetOps.push_back(ValToCopy);
1452       // Don't emit a copytoreg.
1453       continue;
1454     }
1455
1456     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1457     // which is returned in RAX / RDX.
1458     if (Subtarget->is64Bit()) {
1459       if (ValVT == MVT::x86mmx) {
1460         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1461           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1462           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1463                                   ValToCopy);
1464           // If we don't have SSE2 available, convert to v4f32 so the generated
1465           // register is legal.
1466           if (!Subtarget->hasXMMInt())
1467             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1468         }
1469       }
1470     }
1471
1472     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1473     Flag = Chain.getValue(1);
1474   }
1475
1476   // The x86-64 ABI for returning structs by value requires that we copy
1477   // the sret argument into %rax for the return. We saved the argument into
1478   // a virtual register in the entry block, so now we copy the value out
1479   // and into %rax.
1480   if (Subtarget->is64Bit() &&
1481       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1482     MachineFunction &MF = DAG.getMachineFunction();
1483     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484     unsigned Reg = FuncInfo->getSRetReturnReg();
1485     assert(Reg &&
1486            "SRetReturnReg should have been set in LowerFormalArguments().");
1487     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1488
1489     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1490     Flag = Chain.getValue(1);
1491
1492     // RAX now acts like a return value.
1493     MRI.addLiveOut(X86::RAX);
1494   }
1495
1496   RetOps[0] = Chain;  // Update chain.
1497
1498   // Add the flag if we have it.
1499   if (Flag.getNode())
1500     RetOps.push_back(Flag);
1501
1502   return DAG.getNode(X86ISD::RET_FLAG, dl,
1503                      MVT::Other, &RetOps[0], RetOps.size());
1504 }
1505
1506 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1507   if (N->getNumValues() != 1)
1508     return false;
1509   if (!N->hasNUsesOfValue(1, 0))
1510     return false;
1511
1512   SDNode *Copy = *N->use_begin();
1513   if (Copy->getOpcode() != ISD::CopyToReg &&
1514       Copy->getOpcode() != ISD::FP_EXTEND)
1515     return false;
1516
1517   bool HasRet = false;
1518   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1519        UI != UE; ++UI) {
1520     if (UI->getOpcode() != X86ISD::RET_FLAG)
1521       return false;
1522     HasRet = true;
1523   }
1524
1525   return HasRet;
1526 }
1527
1528 EVT
1529 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1530                                             ISD::NodeType ExtendKind) const {
1531   MVT ReturnMVT;
1532   // TODO: Is this also valid on 32-bit?
1533   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1534     ReturnMVT = MVT::i8;
1535   else
1536     ReturnMVT = MVT::i32;
1537
1538   EVT MinVT = getRegisterType(Context, ReturnMVT);
1539   return VT.bitsLT(MinVT) ? MinVT : VT;
1540 }
1541
1542 /// LowerCallResult - Lower the result values of a call into the
1543 /// appropriate copies out of appropriate physical registers.
1544 ///
1545 SDValue
1546 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1547                                    CallingConv::ID CallConv, bool isVarArg,
1548                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1549                                    DebugLoc dl, SelectionDAG &DAG,
1550                                    SmallVectorImpl<SDValue> &InVals) const {
1551
1552   // Assign locations to each value returned by this call.
1553   SmallVector<CCValAssign, 16> RVLocs;
1554   bool Is64Bit = Subtarget->is64Bit();
1555   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1556                  getTargetMachine(), RVLocs, *DAG.getContext());
1557   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1558
1559   // Copy all of the result registers out of their specified physreg.
1560   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1561     CCValAssign &VA = RVLocs[i];
1562     EVT CopyVT = VA.getValVT();
1563
1564     // If this is x86-64, and we disabled SSE, we can't return FP values
1565     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1566         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1567       report_fatal_error("SSE register return with SSE disabled");
1568     }
1569
1570     SDValue Val;
1571
1572     // If this is a call to a function that returns an fp value on the floating
1573     // point stack, we must guarantee the the value is popped from the stack, so
1574     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1575     // if the return value is not used. We use the FpPOP_RETVAL instruction
1576     // instead.
1577     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1578       // If we prefer to use the value in xmm registers, copy it out as f80 and
1579       // use a truncate to move it from fp stack reg to xmm reg.
1580       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1581       SDValue Ops[] = { Chain, InFlag };
1582       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1583                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1584       Val = Chain.getValue(0);
1585
1586       // Round the f80 to the right size, which also moves it to the appropriate
1587       // xmm register.
1588       if (CopyVT != VA.getValVT())
1589         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1590                           // This truncation won't change the value.
1591                           DAG.getIntPtrConstant(1));
1592     } else {
1593       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1594                                  CopyVT, InFlag).getValue(1);
1595       Val = Chain.getValue(0);
1596     }
1597     InFlag = Chain.getValue(2);
1598     InVals.push_back(Val);
1599   }
1600
1601   return Chain;
1602 }
1603
1604
1605 //===----------------------------------------------------------------------===//
1606 //                C & StdCall & Fast Calling Convention implementation
1607 //===----------------------------------------------------------------------===//
1608 //  StdCall calling convention seems to be standard for many Windows' API
1609 //  routines and around. It differs from C calling convention just a little:
1610 //  callee should clean up the stack, not caller. Symbols should be also
1611 //  decorated in some fancy way :) It doesn't support any vector arguments.
1612 //  For info on fast calling convention see Fast Calling Convention (tail call)
1613 //  implementation LowerX86_32FastCCCallTo.
1614
1615 /// CallIsStructReturn - Determines whether a call uses struct return
1616 /// semantics.
1617 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1618   if (Outs.empty())
1619     return false;
1620
1621   return Outs[0].Flags.isSRet();
1622 }
1623
1624 /// ArgsAreStructReturn - Determines whether a function uses struct
1625 /// return semantics.
1626 static bool
1627 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1628   if (Ins.empty())
1629     return false;
1630
1631   return Ins[0].Flags.isSRet();
1632 }
1633
1634 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1635 /// by "Src" to address "Dst" with size and alignment information specified by
1636 /// the specific parameter attribute. The copy will be passed as a byval
1637 /// function parameter.
1638 static SDValue
1639 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1640                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1641                           DebugLoc dl) {
1642   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1643
1644   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1645                        /*isVolatile*/false, /*AlwaysInline=*/true,
1646                        MachinePointerInfo(), MachinePointerInfo());
1647 }
1648
1649 /// IsTailCallConvention - Return true if the calling convention is one that
1650 /// supports tail call optimization.
1651 static bool IsTailCallConvention(CallingConv::ID CC) {
1652   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1653 }
1654
1655 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1656   if (!CI->isTailCall())
1657     return false;
1658
1659   CallSite CS(CI);
1660   CallingConv::ID CalleeCC = CS.getCallingConv();
1661   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1662     return false;
1663
1664   return true;
1665 }
1666
1667 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1668 /// a tailcall target by changing its ABI.
1669 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1670   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1671 }
1672
1673 SDValue
1674 X86TargetLowering::LowerMemArgument(SDValue Chain,
1675                                     CallingConv::ID CallConv,
1676                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1677                                     DebugLoc dl, SelectionDAG &DAG,
1678                                     const CCValAssign &VA,
1679                                     MachineFrameInfo *MFI,
1680                                     unsigned i) const {
1681   // Create the nodes corresponding to a load from this parameter slot.
1682   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1683   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1684   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1685   EVT ValVT;
1686
1687   // If value is passed by pointer we have address passed instead of the value
1688   // itself.
1689   if (VA.getLocInfo() == CCValAssign::Indirect)
1690     ValVT = VA.getLocVT();
1691   else
1692     ValVT = VA.getValVT();
1693
1694   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1695   // changed with more analysis.
1696   // In case of tail call optimization mark all arguments mutable. Since they
1697   // could be overwritten by lowering of arguments in case of a tail call.
1698   if (Flags.isByVal()) {
1699     unsigned Bytes = Flags.getByValSize();
1700     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1701     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1702     return DAG.getFrameIndex(FI, getPointerTy());
1703   } else {
1704     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1705                                     VA.getLocMemOffset(), isImmutable);
1706     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1707     return DAG.getLoad(ValVT, dl, Chain, FIN,
1708                        MachinePointerInfo::getFixedStack(FI),
1709                        false, false, 0);
1710   }
1711 }
1712
1713 SDValue
1714 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1715                                         CallingConv::ID CallConv,
1716                                         bool isVarArg,
1717                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1718                                         DebugLoc dl,
1719                                         SelectionDAG &DAG,
1720                                         SmallVectorImpl<SDValue> &InVals)
1721                                           const {
1722   MachineFunction &MF = DAG.getMachineFunction();
1723   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1724
1725   const Function* Fn = MF.getFunction();
1726   if (Fn->hasExternalLinkage() &&
1727       Subtarget->isTargetCygMing() &&
1728       Fn->getName() == "main")
1729     FuncInfo->setForceFramePointer(true);
1730
1731   MachineFrameInfo *MFI = MF.getFrameInfo();
1732   bool Is64Bit = Subtarget->is64Bit();
1733   bool IsWin64 = Subtarget->isTargetWin64();
1734
1735   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1736          "Var args not supported with calling convention fastcc or ghc");
1737
1738   // Assign locations to all of the incoming arguments.
1739   SmallVector<CCValAssign, 16> ArgLocs;
1740   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1741                  ArgLocs, *DAG.getContext());
1742
1743   // Allocate shadow area for Win64
1744   if (IsWin64) {
1745     CCInfo.AllocateStack(32, 8);
1746   }
1747
1748   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1749
1750   unsigned LastVal = ~0U;
1751   SDValue ArgValue;
1752   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1753     CCValAssign &VA = ArgLocs[i];
1754     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1755     // places.
1756     assert(VA.getValNo() != LastVal &&
1757            "Don't support value assigned to multiple locs yet");
1758     (void)LastVal;
1759     LastVal = VA.getValNo();
1760
1761     if (VA.isRegLoc()) {
1762       EVT RegVT = VA.getLocVT();
1763       TargetRegisterClass *RC = NULL;
1764       if (RegVT == MVT::i32)
1765         RC = X86::GR32RegisterClass;
1766       else if (Is64Bit && RegVT == MVT::i64)
1767         RC = X86::GR64RegisterClass;
1768       else if (RegVT == MVT::f32)
1769         RC = X86::FR32RegisterClass;
1770       else if (RegVT == MVT::f64)
1771         RC = X86::FR64RegisterClass;
1772       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1773         RC = X86::VR256RegisterClass;
1774       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1775         RC = X86::VR128RegisterClass;
1776       else if (RegVT == MVT::x86mmx)
1777         RC = X86::VR64RegisterClass;
1778       else
1779         llvm_unreachable("Unknown argument type!");
1780
1781       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1782       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1783
1784       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1785       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1786       // right size.
1787       if (VA.getLocInfo() == CCValAssign::SExt)
1788         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1789                                DAG.getValueType(VA.getValVT()));
1790       else if (VA.getLocInfo() == CCValAssign::ZExt)
1791         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1792                                DAG.getValueType(VA.getValVT()));
1793       else if (VA.getLocInfo() == CCValAssign::BCvt)
1794         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1795
1796       if (VA.isExtInLoc()) {
1797         // Handle MMX values passed in XMM regs.
1798         if (RegVT.isVector()) {
1799           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1800                                  ArgValue);
1801         } else
1802           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1803       }
1804     } else {
1805       assert(VA.isMemLoc());
1806       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1807     }
1808
1809     // If value is passed via pointer - do a load.
1810     if (VA.getLocInfo() == CCValAssign::Indirect)
1811       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1812                              MachinePointerInfo(), false, false, 0);
1813
1814     InVals.push_back(ArgValue);
1815   }
1816
1817   // The x86-64 ABI for returning structs by value requires that we copy
1818   // the sret argument into %rax for the return. Save the argument into
1819   // a virtual register so that we can access it from the return points.
1820   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1821     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1822     unsigned Reg = FuncInfo->getSRetReturnReg();
1823     if (!Reg) {
1824       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1825       FuncInfo->setSRetReturnReg(Reg);
1826     }
1827     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1828     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1829   }
1830
1831   unsigned StackSize = CCInfo.getNextStackOffset();
1832   // Align stack specially for tail calls.
1833   if (FuncIsMadeTailCallSafe(CallConv))
1834     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1835
1836   // If the function takes variable number of arguments, make a frame index for
1837   // the start of the first vararg value... for expansion of llvm.va_start.
1838   if (isVarArg) {
1839     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1840                     CallConv != CallingConv::X86_ThisCall)) {
1841       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1842     }
1843     if (Is64Bit) {
1844       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1845
1846       // FIXME: We should really autogenerate these arrays
1847       static const unsigned GPR64ArgRegsWin64[] = {
1848         X86::RCX, X86::RDX, X86::R8,  X86::R9
1849       };
1850       static const unsigned GPR64ArgRegs64Bit[] = {
1851         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1852       };
1853       static const unsigned XMMArgRegs64Bit[] = {
1854         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1855         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1856       };
1857       const unsigned *GPR64ArgRegs;
1858       unsigned NumXMMRegs = 0;
1859
1860       if (IsWin64) {
1861         // The XMM registers which might contain var arg parameters are shadowed
1862         // in their paired GPR.  So we only need to save the GPR to their home
1863         // slots.
1864         TotalNumIntRegs = 4;
1865         GPR64ArgRegs = GPR64ArgRegsWin64;
1866       } else {
1867         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1868         GPR64ArgRegs = GPR64ArgRegs64Bit;
1869
1870         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1871       }
1872       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1873                                                        TotalNumIntRegs);
1874
1875       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1876       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1877              "SSE register cannot be used when SSE is disabled!");
1878       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1879              "SSE register cannot be used when SSE is disabled!");
1880       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1881         // Kernel mode asks for SSE to be disabled, so don't push them
1882         // on the stack.
1883         TotalNumXMMRegs = 0;
1884
1885       if (IsWin64) {
1886         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1887         // Get to the caller-allocated home save location.  Add 8 to account
1888         // for the return address.
1889         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1890         FuncInfo->setRegSaveFrameIndex(
1891           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1892         // Fixup to set vararg frame on shadow area (4 x i64).
1893         if (NumIntRegs < 4)
1894           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1895       } else {
1896         // For X86-64, if there are vararg parameters that are passed via
1897         // registers, then we must store them to their spots on the stack so they
1898         // may be loaded by deferencing the result of va_next.
1899         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1900         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1901         FuncInfo->setRegSaveFrameIndex(
1902           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1903                                false));
1904       }
1905
1906       // Store the integer parameter registers.
1907       SmallVector<SDValue, 8> MemOps;
1908       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1909                                         getPointerTy());
1910       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1911       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1912         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1913                                   DAG.getIntPtrConstant(Offset));
1914         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1915                                      X86::GR64RegisterClass);
1916         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1917         SDValue Store =
1918           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1919                        MachinePointerInfo::getFixedStack(
1920                          FuncInfo->getRegSaveFrameIndex(), Offset),
1921                        false, false, 0);
1922         MemOps.push_back(Store);
1923         Offset += 8;
1924       }
1925
1926       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1927         // Now store the XMM (fp + vector) parameter registers.
1928         SmallVector<SDValue, 11> SaveXMMOps;
1929         SaveXMMOps.push_back(Chain);
1930
1931         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1932         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1933         SaveXMMOps.push_back(ALVal);
1934
1935         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1936                                FuncInfo->getRegSaveFrameIndex()));
1937         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1938                                FuncInfo->getVarArgsFPOffset()));
1939
1940         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1941           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1942                                        X86::VR128RegisterClass);
1943           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1944           SaveXMMOps.push_back(Val);
1945         }
1946         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1947                                      MVT::Other,
1948                                      &SaveXMMOps[0], SaveXMMOps.size()));
1949       }
1950
1951       if (!MemOps.empty())
1952         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1953                             &MemOps[0], MemOps.size());
1954     }
1955   }
1956
1957   // Some CCs need callee pop.
1958   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1959     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1960   } else {
1961     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1962     // If this is an sret function, the return should pop the hidden pointer.
1963     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1964       FuncInfo->setBytesToPopOnReturn(4);
1965   }
1966
1967   if (!Is64Bit) {
1968     // RegSaveFrameIndex is X86-64 only.
1969     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1970     if (CallConv == CallingConv::X86_FastCall ||
1971         CallConv == CallingConv::X86_ThisCall)
1972       // fastcc functions can't have varargs.
1973       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1974   }
1975
1976   FuncInfo->setArgumentStackSize(StackSize);
1977
1978   return Chain;
1979 }
1980
1981 SDValue
1982 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1983                                     SDValue StackPtr, SDValue Arg,
1984                                     DebugLoc dl, SelectionDAG &DAG,
1985                                     const CCValAssign &VA,
1986                                     ISD::ArgFlagsTy Flags) const {
1987   unsigned LocMemOffset = VA.getLocMemOffset();
1988   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1989   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1990   if (Flags.isByVal())
1991     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1992
1993   return DAG.getStore(Chain, dl, Arg, PtrOff,
1994                       MachinePointerInfo::getStack(LocMemOffset),
1995                       false, false, 0);
1996 }
1997
1998 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1999 /// optimization is performed and it is required.
2000 SDValue
2001 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2002                                            SDValue &OutRetAddr, SDValue Chain,
2003                                            bool IsTailCall, bool Is64Bit,
2004                                            int FPDiff, DebugLoc dl) const {
2005   // Adjust the Return address stack slot.
2006   EVT VT = getPointerTy();
2007   OutRetAddr = getReturnAddressFrameIndex(DAG);
2008
2009   // Load the "old" Return address.
2010   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2011                            false, false, 0);
2012   return SDValue(OutRetAddr.getNode(), 1);
2013 }
2014
2015 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2016 /// optimization is performed and it is required (FPDiff!=0).
2017 static SDValue
2018 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2019                          SDValue Chain, SDValue RetAddrFrIdx,
2020                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2021   // Store the return address to the appropriate stack slot.
2022   if (!FPDiff) return Chain;
2023   // Calculate the new stack slot for the return address.
2024   int SlotSize = Is64Bit ? 8 : 4;
2025   int NewReturnAddrFI =
2026     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2027   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2028   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2029   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2030                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2031                        false, false, 0);
2032   return Chain;
2033 }
2034
2035 SDValue
2036 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2037                              CallingConv::ID CallConv, bool isVarArg,
2038                              bool &isTailCall,
2039                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2040                              const SmallVectorImpl<SDValue> &OutVals,
2041                              const SmallVectorImpl<ISD::InputArg> &Ins,
2042                              DebugLoc dl, SelectionDAG &DAG,
2043                              SmallVectorImpl<SDValue> &InVals) const {
2044   MachineFunction &MF = DAG.getMachineFunction();
2045   bool Is64Bit        = Subtarget->is64Bit();
2046   bool IsWin64        = Subtarget->isTargetWin64();
2047   bool IsStructRet    = CallIsStructReturn(Outs);
2048   bool IsSibcall      = false;
2049
2050   if (isTailCall) {
2051     // Check if it's really possible to do a tail call.
2052     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2053                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2054                                                    Outs, OutVals, Ins, DAG);
2055
2056     // Sibcalls are automatically detected tailcalls which do not require
2057     // ABI changes.
2058     if (!GuaranteedTailCallOpt && isTailCall)
2059       IsSibcall = true;
2060
2061     if (isTailCall)
2062       ++NumTailCalls;
2063   }
2064
2065   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2066          "Var args not supported with calling convention fastcc or ghc");
2067
2068   // Analyze operands of the call, assigning locations to each operand.
2069   SmallVector<CCValAssign, 16> ArgLocs;
2070   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2071                  ArgLocs, *DAG.getContext());
2072
2073   // Allocate shadow area for Win64
2074   if (IsWin64) {
2075     CCInfo.AllocateStack(32, 8);
2076   }
2077
2078   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2079
2080   // Get a count of how many bytes are to be pushed on the stack.
2081   unsigned NumBytes = CCInfo.getNextStackOffset();
2082   if (IsSibcall)
2083     // This is a sibcall. The memory operands are available in caller's
2084     // own caller's stack.
2085     NumBytes = 0;
2086   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2087     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2088
2089   int FPDiff = 0;
2090   if (isTailCall && !IsSibcall) {
2091     // Lower arguments at fp - stackoffset + fpdiff.
2092     unsigned NumBytesCallerPushed =
2093       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2094     FPDiff = NumBytesCallerPushed - NumBytes;
2095
2096     // Set the delta of movement of the returnaddr stackslot.
2097     // But only set if delta is greater than previous delta.
2098     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2099       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2100   }
2101
2102   if (!IsSibcall)
2103     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2104
2105   SDValue RetAddrFrIdx;
2106   // Load return address for tail calls.
2107   if (isTailCall && FPDiff)
2108     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2109                                     Is64Bit, FPDiff, dl);
2110
2111   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2112   SmallVector<SDValue, 8> MemOpChains;
2113   SDValue StackPtr;
2114
2115   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2116   // of tail call optimization arguments are handle later.
2117   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2118     CCValAssign &VA = ArgLocs[i];
2119     EVT RegVT = VA.getLocVT();
2120     SDValue Arg = OutVals[i];
2121     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2122     bool isByVal = Flags.isByVal();
2123
2124     // Promote the value if needed.
2125     switch (VA.getLocInfo()) {
2126     default: llvm_unreachable("Unknown loc info!");
2127     case CCValAssign::Full: break;
2128     case CCValAssign::SExt:
2129       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2130       break;
2131     case CCValAssign::ZExt:
2132       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2133       break;
2134     case CCValAssign::AExt:
2135       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2136         // Special case: passing MMX values in XMM registers.
2137         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2138         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2139         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2140       } else
2141         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2142       break;
2143     case CCValAssign::BCvt:
2144       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2145       break;
2146     case CCValAssign::Indirect: {
2147       // Store the argument.
2148       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2149       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2150       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2151                            MachinePointerInfo::getFixedStack(FI),
2152                            false, false, 0);
2153       Arg = SpillSlot;
2154       break;
2155     }
2156     }
2157
2158     if (VA.isRegLoc()) {
2159       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2160       if (isVarArg && IsWin64) {
2161         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2162         // shadow reg if callee is a varargs function.
2163         unsigned ShadowReg = 0;
2164         switch (VA.getLocReg()) {
2165         case X86::XMM0: ShadowReg = X86::RCX; break;
2166         case X86::XMM1: ShadowReg = X86::RDX; break;
2167         case X86::XMM2: ShadowReg = X86::R8; break;
2168         case X86::XMM3: ShadowReg = X86::R9; break;
2169         }
2170         if (ShadowReg)
2171           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2172       }
2173     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2174       assert(VA.isMemLoc());
2175       if (StackPtr.getNode() == 0)
2176         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2177       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2178                                              dl, DAG, VA, Flags));
2179     }
2180   }
2181
2182   if (!MemOpChains.empty())
2183     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2184                         &MemOpChains[0], MemOpChains.size());
2185
2186   // Build a sequence of copy-to-reg nodes chained together with token chain
2187   // and flag operands which copy the outgoing args into registers.
2188   SDValue InFlag;
2189   // Tail call byval lowering might overwrite argument registers so in case of
2190   // tail call optimization the copies to registers are lowered later.
2191   if (!isTailCall)
2192     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2193       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2194                                RegsToPass[i].second, InFlag);
2195       InFlag = Chain.getValue(1);
2196     }
2197
2198   if (Subtarget->isPICStyleGOT()) {
2199     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2200     // GOT pointer.
2201     if (!isTailCall) {
2202       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2203                                DAG.getNode(X86ISD::GlobalBaseReg,
2204                                            DebugLoc(), getPointerTy()),
2205                                InFlag);
2206       InFlag = Chain.getValue(1);
2207     } else {
2208       // If we are tail calling and generating PIC/GOT style code load the
2209       // address of the callee into ECX. The value in ecx is used as target of
2210       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2211       // for tail calls on PIC/GOT architectures. Normally we would just put the
2212       // address of GOT into ebx and then call target@PLT. But for tail calls
2213       // ebx would be restored (since ebx is callee saved) before jumping to the
2214       // target@PLT.
2215
2216       // Note: The actual moving to ECX is done further down.
2217       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2218       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2219           !G->getGlobal()->hasProtectedVisibility())
2220         Callee = LowerGlobalAddress(Callee, DAG);
2221       else if (isa<ExternalSymbolSDNode>(Callee))
2222         Callee = LowerExternalSymbol(Callee, DAG);
2223     }
2224   }
2225
2226   if (Is64Bit && isVarArg && !IsWin64) {
2227     // From AMD64 ABI document:
2228     // For calls that may call functions that use varargs or stdargs
2229     // (prototype-less calls or calls to functions containing ellipsis (...) in
2230     // the declaration) %al is used as hidden argument to specify the number
2231     // of SSE registers used. The contents of %al do not need to match exactly
2232     // the number of registers, but must be an ubound on the number of SSE
2233     // registers used and is in the range 0 - 8 inclusive.
2234
2235     // Count the number of XMM registers allocated.
2236     static const unsigned XMMArgRegs[] = {
2237       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2238       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2239     };
2240     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2241     assert((Subtarget->hasXMM() || !NumXMMRegs)
2242            && "SSE registers cannot be used when SSE is disabled");
2243
2244     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2245                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2246     InFlag = Chain.getValue(1);
2247   }
2248
2249
2250   // For tail calls lower the arguments to the 'real' stack slot.
2251   if (isTailCall) {
2252     // Force all the incoming stack arguments to be loaded from the stack
2253     // before any new outgoing arguments are stored to the stack, because the
2254     // outgoing stack slots may alias the incoming argument stack slots, and
2255     // the alias isn't otherwise explicit. This is slightly more conservative
2256     // than necessary, because it means that each store effectively depends
2257     // on every argument instead of just those arguments it would clobber.
2258     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2259
2260     SmallVector<SDValue, 8> MemOpChains2;
2261     SDValue FIN;
2262     int FI = 0;
2263     // Do not flag preceding copytoreg stuff together with the following stuff.
2264     InFlag = SDValue();
2265     if (GuaranteedTailCallOpt) {
2266       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2267         CCValAssign &VA = ArgLocs[i];
2268         if (VA.isRegLoc())
2269           continue;
2270         assert(VA.isMemLoc());
2271         SDValue Arg = OutVals[i];
2272         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2273         // Create frame index.
2274         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2275         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2276         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2277         FIN = DAG.getFrameIndex(FI, getPointerTy());
2278
2279         if (Flags.isByVal()) {
2280           // Copy relative to framepointer.
2281           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2282           if (StackPtr.getNode() == 0)
2283             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2284                                           getPointerTy());
2285           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2286
2287           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2288                                                            ArgChain,
2289                                                            Flags, DAG, dl));
2290         } else {
2291           // Store relative to framepointer.
2292           MemOpChains2.push_back(
2293             DAG.getStore(ArgChain, dl, Arg, FIN,
2294                          MachinePointerInfo::getFixedStack(FI),
2295                          false, false, 0));
2296         }
2297       }
2298     }
2299
2300     if (!MemOpChains2.empty())
2301       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2302                           &MemOpChains2[0], MemOpChains2.size());
2303
2304     // Copy arguments to their registers.
2305     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2306       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2307                                RegsToPass[i].second, InFlag);
2308       InFlag = Chain.getValue(1);
2309     }
2310     InFlag =SDValue();
2311
2312     // Store the return address to the appropriate stack slot.
2313     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2314                                      FPDiff, dl);
2315   }
2316
2317   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2318     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2319     // In the 64-bit large code model, we have to make all calls
2320     // through a register, since the call instruction's 32-bit
2321     // pc-relative offset may not be large enough to hold the whole
2322     // address.
2323   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2324     // If the callee is a GlobalAddress node (quite common, every direct call
2325     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2326     // it.
2327
2328     // We should use extra load for direct calls to dllimported functions in
2329     // non-JIT mode.
2330     const GlobalValue *GV = G->getGlobal();
2331     if (!GV->hasDLLImportLinkage()) {
2332       unsigned char OpFlags = 0;
2333       bool ExtraLoad = false;
2334       unsigned WrapperKind = ISD::DELETED_NODE;
2335
2336       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2337       // external symbols most go through the PLT in PIC mode.  If the symbol
2338       // has hidden or protected visibility, or if it is static or local, then
2339       // we don't need to use the PLT - we can directly call it.
2340       if (Subtarget->isTargetELF() &&
2341           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2342           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2343         OpFlags = X86II::MO_PLT;
2344       } else if (Subtarget->isPICStyleStubAny() &&
2345                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2346                  (!Subtarget->getTargetTriple().isMacOSX() ||
2347                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2348         // PC-relative references to external symbols should go through $stub,
2349         // unless we're building with the leopard linker or later, which
2350         // automatically synthesizes these stubs.
2351         OpFlags = X86II::MO_DARWIN_STUB;
2352       } else if (Subtarget->isPICStyleRIPRel() &&
2353                  isa<Function>(GV) &&
2354                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2355         // If the function is marked as non-lazy, generate an indirect call
2356         // which loads from the GOT directly. This avoids runtime overhead
2357         // at the cost of eager binding (and one extra byte of encoding).
2358         OpFlags = X86II::MO_GOTPCREL;
2359         WrapperKind = X86ISD::WrapperRIP;
2360         ExtraLoad = true;
2361       }
2362
2363       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2364                                           G->getOffset(), OpFlags);
2365
2366       // Add a wrapper if needed.
2367       if (WrapperKind != ISD::DELETED_NODE)
2368         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2369       // Add extra indirection if needed.
2370       if (ExtraLoad)
2371         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2372                              MachinePointerInfo::getGOT(),
2373                              false, false, 0);
2374     }
2375   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2376     unsigned char OpFlags = 0;
2377
2378     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2379     // external symbols should go through the PLT.
2380     if (Subtarget->isTargetELF() &&
2381         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2382       OpFlags = X86II::MO_PLT;
2383     } else if (Subtarget->isPICStyleStubAny() &&
2384                (!Subtarget->getTargetTriple().isMacOSX() ||
2385                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2386       // PC-relative references to external symbols should go through $stub,
2387       // unless we're building with the leopard linker or later, which
2388       // automatically synthesizes these stubs.
2389       OpFlags = X86II::MO_DARWIN_STUB;
2390     }
2391
2392     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2393                                          OpFlags);
2394   }
2395
2396   // Returns a chain & a flag for retval copy to use.
2397   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2398   SmallVector<SDValue, 8> Ops;
2399
2400   if (!IsSibcall && isTailCall) {
2401     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2402                            DAG.getIntPtrConstant(0, true), InFlag);
2403     InFlag = Chain.getValue(1);
2404   }
2405
2406   Ops.push_back(Chain);
2407   Ops.push_back(Callee);
2408
2409   if (isTailCall)
2410     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2411
2412   // Add argument registers to the end of the list so that they are known live
2413   // into the call.
2414   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2415     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2416                                   RegsToPass[i].second.getValueType()));
2417
2418   // Add an implicit use GOT pointer in EBX.
2419   if (!isTailCall && Subtarget->isPICStyleGOT())
2420     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2421
2422   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2423   if (Is64Bit && isVarArg && !IsWin64)
2424     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2425
2426   if (InFlag.getNode())
2427     Ops.push_back(InFlag);
2428
2429   if (isTailCall) {
2430     // We used to do:
2431     //// If this is the first return lowered for this function, add the regs
2432     //// to the liveout set for the function.
2433     // This isn't right, although it's probably harmless on x86; liveouts
2434     // should be computed from returns not tail calls.  Consider a void
2435     // function making a tail call to a function returning int.
2436     return DAG.getNode(X86ISD::TC_RETURN, dl,
2437                        NodeTys, &Ops[0], Ops.size());
2438   }
2439
2440   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2441   InFlag = Chain.getValue(1);
2442
2443   // Create the CALLSEQ_END node.
2444   unsigned NumBytesForCalleeToPush;
2445   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2446     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2447   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2448     // If this is a call to a struct-return function, the callee
2449     // pops the hidden struct pointer, so we have to push it back.
2450     // This is common for Darwin/X86, Linux & Mingw32 targets.
2451     NumBytesForCalleeToPush = 4;
2452   else
2453     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2454
2455   // Returns a flag for retval copy to use.
2456   if (!IsSibcall) {
2457     Chain = DAG.getCALLSEQ_END(Chain,
2458                                DAG.getIntPtrConstant(NumBytes, true),
2459                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2460                                                      true),
2461                                InFlag);
2462     InFlag = Chain.getValue(1);
2463   }
2464
2465   // Handle result values, copying them out of physregs into vregs that we
2466   // return.
2467   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2468                          Ins, dl, DAG, InVals);
2469 }
2470
2471
2472 //===----------------------------------------------------------------------===//
2473 //                Fast Calling Convention (tail call) implementation
2474 //===----------------------------------------------------------------------===//
2475
2476 //  Like std call, callee cleans arguments, convention except that ECX is
2477 //  reserved for storing the tail called function address. Only 2 registers are
2478 //  free for argument passing (inreg). Tail call optimization is performed
2479 //  provided:
2480 //                * tailcallopt is enabled
2481 //                * caller/callee are fastcc
2482 //  On X86_64 architecture with GOT-style position independent code only local
2483 //  (within module) calls are supported at the moment.
2484 //  To keep the stack aligned according to platform abi the function
2485 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2486 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2487 //  If a tail called function callee has more arguments than the caller the
2488 //  caller needs to make sure that there is room to move the RETADDR to. This is
2489 //  achieved by reserving an area the size of the argument delta right after the
2490 //  original REtADDR, but before the saved framepointer or the spilled registers
2491 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2492 //  stack layout:
2493 //    arg1
2494 //    arg2
2495 //    RETADDR
2496 //    [ new RETADDR
2497 //      move area ]
2498 //    (possible EBP)
2499 //    ESI
2500 //    EDI
2501 //    local1 ..
2502
2503 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2504 /// for a 16 byte align requirement.
2505 unsigned
2506 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2507                                                SelectionDAG& DAG) const {
2508   MachineFunction &MF = DAG.getMachineFunction();
2509   const TargetMachine &TM = MF.getTarget();
2510   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2511   unsigned StackAlignment = TFI.getStackAlignment();
2512   uint64_t AlignMask = StackAlignment - 1;
2513   int64_t Offset = StackSize;
2514   uint64_t SlotSize = TD->getPointerSize();
2515   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2516     // Number smaller than 12 so just add the difference.
2517     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2518   } else {
2519     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2520     Offset = ((~AlignMask) & Offset) + StackAlignment +
2521       (StackAlignment-SlotSize);
2522   }
2523   return Offset;
2524 }
2525
2526 /// MatchingStackOffset - Return true if the given stack call argument is
2527 /// already available in the same position (relatively) of the caller's
2528 /// incoming argument stack.
2529 static
2530 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2531                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2532                          const X86InstrInfo *TII) {
2533   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2534   int FI = INT_MAX;
2535   if (Arg.getOpcode() == ISD::CopyFromReg) {
2536     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2537     if (!TargetRegisterInfo::isVirtualRegister(VR))
2538       return false;
2539     MachineInstr *Def = MRI->getVRegDef(VR);
2540     if (!Def)
2541       return false;
2542     if (!Flags.isByVal()) {
2543       if (!TII->isLoadFromStackSlot(Def, FI))
2544         return false;
2545     } else {
2546       unsigned Opcode = Def->getOpcode();
2547       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2548           Def->getOperand(1).isFI()) {
2549         FI = Def->getOperand(1).getIndex();
2550         Bytes = Flags.getByValSize();
2551       } else
2552         return false;
2553     }
2554   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2555     if (Flags.isByVal())
2556       // ByVal argument is passed in as a pointer but it's now being
2557       // dereferenced. e.g.
2558       // define @foo(%struct.X* %A) {
2559       //   tail call @bar(%struct.X* byval %A)
2560       // }
2561       return false;
2562     SDValue Ptr = Ld->getBasePtr();
2563     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2564     if (!FINode)
2565       return false;
2566     FI = FINode->getIndex();
2567   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2568     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2569     FI = FINode->getIndex();
2570     Bytes = Flags.getByValSize();
2571   } else
2572     return false;
2573
2574   assert(FI != INT_MAX);
2575   if (!MFI->isFixedObjectIndex(FI))
2576     return false;
2577   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2578 }
2579
2580 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2581 /// for tail call optimization. Targets which want to do tail call
2582 /// optimization should implement this function.
2583 bool
2584 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2585                                                      CallingConv::ID CalleeCC,
2586                                                      bool isVarArg,
2587                                                      bool isCalleeStructRet,
2588                                                      bool isCallerStructRet,
2589                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2590                                     const SmallVectorImpl<SDValue> &OutVals,
2591                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2592                                                      SelectionDAG& DAG) const {
2593   if (!IsTailCallConvention(CalleeCC) &&
2594       CalleeCC != CallingConv::C)
2595     return false;
2596
2597   // If -tailcallopt is specified, make fastcc functions tail-callable.
2598   const MachineFunction &MF = DAG.getMachineFunction();
2599   const Function *CallerF = DAG.getMachineFunction().getFunction();
2600   CallingConv::ID CallerCC = CallerF->getCallingConv();
2601   bool CCMatch = CallerCC == CalleeCC;
2602
2603   if (GuaranteedTailCallOpt) {
2604     if (IsTailCallConvention(CalleeCC) && CCMatch)
2605       return true;
2606     return false;
2607   }
2608
2609   // Look for obvious safe cases to perform tail call optimization that do not
2610   // require ABI changes. This is what gcc calls sibcall.
2611
2612   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2613   // emit a special epilogue.
2614   if (RegInfo->needsStackRealignment(MF))
2615     return false;
2616
2617   // Also avoid sibcall optimization if either caller or callee uses struct
2618   // return semantics.
2619   if (isCalleeStructRet || isCallerStructRet)
2620     return false;
2621
2622   // An stdcall caller is expected to clean up its arguments; the callee
2623   // isn't going to do that.
2624   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2625     return false;
2626
2627   // Do not sibcall optimize vararg calls unless all arguments are passed via
2628   // registers.
2629   if (isVarArg && !Outs.empty()) {
2630
2631     // Optimizing for varargs on Win64 is unlikely to be safe without
2632     // additional testing.
2633     if (Subtarget->isTargetWin64())
2634       return false;
2635
2636     SmallVector<CCValAssign, 16> ArgLocs;
2637     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2638                    getTargetMachine(), ArgLocs, *DAG.getContext());
2639
2640     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2641     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2642       if (!ArgLocs[i].isRegLoc())
2643         return false;
2644   }
2645
2646   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2647   // Therefore if it's not used by the call it is not safe to optimize this into
2648   // a sibcall.
2649   bool Unused = false;
2650   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2651     if (!Ins[i].Used) {
2652       Unused = true;
2653       break;
2654     }
2655   }
2656   if (Unused) {
2657     SmallVector<CCValAssign, 16> RVLocs;
2658     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2659                    getTargetMachine(), RVLocs, *DAG.getContext());
2660     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2661     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2662       CCValAssign &VA = RVLocs[i];
2663       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2664         return false;
2665     }
2666   }
2667
2668   // If the calling conventions do not match, then we'd better make sure the
2669   // results are returned in the same way as what the caller expects.
2670   if (!CCMatch) {
2671     SmallVector<CCValAssign, 16> RVLocs1;
2672     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2673                     getTargetMachine(), RVLocs1, *DAG.getContext());
2674     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2675
2676     SmallVector<CCValAssign, 16> RVLocs2;
2677     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2678                     getTargetMachine(), RVLocs2, *DAG.getContext());
2679     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2680
2681     if (RVLocs1.size() != RVLocs2.size())
2682       return false;
2683     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2684       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2685         return false;
2686       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2687         return false;
2688       if (RVLocs1[i].isRegLoc()) {
2689         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2690           return false;
2691       } else {
2692         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2693           return false;
2694       }
2695     }
2696   }
2697
2698   // If the callee takes no arguments then go on to check the results of the
2699   // call.
2700   if (!Outs.empty()) {
2701     // Check if stack adjustment is needed. For now, do not do this if any
2702     // argument is passed on the stack.
2703     SmallVector<CCValAssign, 16> ArgLocs;
2704     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2705                    getTargetMachine(), ArgLocs, *DAG.getContext());
2706
2707     // Allocate shadow area for Win64
2708     if (Subtarget->isTargetWin64()) {
2709       CCInfo.AllocateStack(32, 8);
2710     }
2711
2712     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2713     if (CCInfo.getNextStackOffset()) {
2714       MachineFunction &MF = DAG.getMachineFunction();
2715       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2716         return false;
2717
2718       // Check if the arguments are already laid out in the right way as
2719       // the caller's fixed stack objects.
2720       MachineFrameInfo *MFI = MF.getFrameInfo();
2721       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2722       const X86InstrInfo *TII =
2723         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2724       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725         CCValAssign &VA = ArgLocs[i];
2726         SDValue Arg = OutVals[i];
2727         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2728         if (VA.getLocInfo() == CCValAssign::Indirect)
2729           return false;
2730         if (!VA.isRegLoc()) {
2731           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2732                                    MFI, MRI, TII))
2733             return false;
2734         }
2735       }
2736     }
2737
2738     // If the tailcall address may be in a register, then make sure it's
2739     // possible to register allocate for it. In 32-bit, the call address can
2740     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2741     // callee-saved registers are restored. These happen to be the same
2742     // registers used to pass 'inreg' arguments so watch out for those.
2743     if (!Subtarget->is64Bit() &&
2744         !isa<GlobalAddressSDNode>(Callee) &&
2745         !isa<ExternalSymbolSDNode>(Callee)) {
2746       unsigned NumInRegs = 0;
2747       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2748         CCValAssign &VA = ArgLocs[i];
2749         if (!VA.isRegLoc())
2750           continue;
2751         unsigned Reg = VA.getLocReg();
2752         switch (Reg) {
2753         default: break;
2754         case X86::EAX: case X86::EDX: case X86::ECX:
2755           if (++NumInRegs == 3)
2756             return false;
2757           break;
2758         }
2759       }
2760     }
2761   }
2762
2763   return true;
2764 }
2765
2766 FastISel *
2767 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2768   return X86::createFastISel(funcInfo);
2769 }
2770
2771
2772 //===----------------------------------------------------------------------===//
2773 //                           Other Lowering Hooks
2774 //===----------------------------------------------------------------------===//
2775
2776 static bool MayFoldLoad(SDValue Op) {
2777   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2778 }
2779
2780 static bool MayFoldIntoStore(SDValue Op) {
2781   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2782 }
2783
2784 static bool isTargetShuffle(unsigned Opcode) {
2785   switch(Opcode) {
2786   default: return false;
2787   case X86ISD::PSHUFD:
2788   case X86ISD::PSHUFHW:
2789   case X86ISD::PSHUFLW:
2790   case X86ISD::SHUFPD:
2791   case X86ISD::PALIGN:
2792   case X86ISD::SHUFPS:
2793   case X86ISD::MOVLHPS:
2794   case X86ISD::MOVLHPD:
2795   case X86ISD::MOVHLPS:
2796   case X86ISD::MOVLPS:
2797   case X86ISD::MOVLPD:
2798   case X86ISD::MOVSHDUP:
2799   case X86ISD::MOVSLDUP:
2800   case X86ISD::MOVDDUP:
2801   case X86ISD::MOVSS:
2802   case X86ISD::MOVSD:
2803   case X86ISD::UNPCKLPS:
2804   case X86ISD::UNPCKLPD:
2805   case X86ISD::VUNPCKLPSY:
2806   case X86ISD::VUNPCKLPDY:
2807   case X86ISD::PUNPCKLWD:
2808   case X86ISD::PUNPCKLBW:
2809   case X86ISD::PUNPCKLDQ:
2810   case X86ISD::PUNPCKLQDQ:
2811   case X86ISD::UNPCKHPS:
2812   case X86ISD::UNPCKHPD:
2813   case X86ISD::VUNPCKHPSY:
2814   case X86ISD::VUNPCKHPDY:
2815   case X86ISD::PUNPCKHWD:
2816   case X86ISD::PUNPCKHBW:
2817   case X86ISD::PUNPCKHDQ:
2818   case X86ISD::PUNPCKHQDQ:
2819   case X86ISD::VPERMILPS:
2820   case X86ISD::VPERMILPSY:
2821   case X86ISD::VPERMILPD:
2822   case X86ISD::VPERMILPDY:
2823   case X86ISD::VPERM2F128:
2824     return true;
2825   }
2826   return false;
2827 }
2828
2829 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2830                                                SDValue V1, SelectionDAG &DAG) {
2831   switch(Opc) {
2832   default: llvm_unreachable("Unknown x86 shuffle node");
2833   case X86ISD::MOVSHDUP:
2834   case X86ISD::MOVSLDUP:
2835   case X86ISD::MOVDDUP:
2836     return DAG.getNode(Opc, dl, VT, V1);
2837   }
2838
2839   return SDValue();
2840 }
2841
2842 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2843                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2844   switch(Opc) {
2845   default: llvm_unreachable("Unknown x86 shuffle node");
2846   case X86ISD::PSHUFD:
2847   case X86ISD::PSHUFHW:
2848   case X86ISD::PSHUFLW:
2849   case X86ISD::VPERMILPS:
2850   case X86ISD::VPERMILPSY:
2851   case X86ISD::VPERMILPD:
2852   case X86ISD::VPERMILPDY:
2853     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2854   }
2855
2856   return SDValue();
2857 }
2858
2859 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2860                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2861   switch(Opc) {
2862   default: llvm_unreachable("Unknown x86 shuffle node");
2863   case X86ISD::PALIGN:
2864   case X86ISD::SHUFPD:
2865   case X86ISD::SHUFPS:
2866   case X86ISD::VPERM2F128:
2867     return DAG.getNode(Opc, dl, VT, V1, V2,
2868                        DAG.getConstant(TargetMask, MVT::i8));
2869   }
2870   return SDValue();
2871 }
2872
2873 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2874                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2875   switch(Opc) {
2876   default: llvm_unreachable("Unknown x86 shuffle node");
2877   case X86ISD::MOVLHPS:
2878   case X86ISD::MOVLHPD:
2879   case X86ISD::MOVHLPS:
2880   case X86ISD::MOVLPS:
2881   case X86ISD::MOVLPD:
2882   case X86ISD::MOVSS:
2883   case X86ISD::MOVSD:
2884   case X86ISD::UNPCKLPS:
2885   case X86ISD::UNPCKLPD:
2886   case X86ISD::VUNPCKLPSY:
2887   case X86ISD::VUNPCKLPDY:
2888   case X86ISD::PUNPCKLWD:
2889   case X86ISD::PUNPCKLBW:
2890   case X86ISD::PUNPCKLDQ:
2891   case X86ISD::PUNPCKLQDQ:
2892   case X86ISD::UNPCKHPS:
2893   case X86ISD::UNPCKHPD:
2894   case X86ISD::VUNPCKHPSY:
2895   case X86ISD::VUNPCKHPDY:
2896   case X86ISD::PUNPCKHWD:
2897   case X86ISD::PUNPCKHBW:
2898   case X86ISD::PUNPCKHDQ:
2899   case X86ISD::PUNPCKHQDQ:
2900     return DAG.getNode(Opc, dl, VT, V1, V2);
2901   }
2902   return SDValue();
2903 }
2904
2905 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2908   int ReturnAddrIndex = FuncInfo->getRAIndex();
2909
2910   if (ReturnAddrIndex == 0) {
2911     // Set up a frame object for the return address.
2912     uint64_t SlotSize = TD->getPointerSize();
2913     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2914                                                            false);
2915     FuncInfo->setRAIndex(ReturnAddrIndex);
2916   }
2917
2918   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2919 }
2920
2921
2922 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2923                                        bool hasSymbolicDisplacement) {
2924   // Offset should fit into 32 bit immediate field.
2925   if (!isInt<32>(Offset))
2926     return false;
2927
2928   // If we don't have a symbolic displacement - we don't have any extra
2929   // restrictions.
2930   if (!hasSymbolicDisplacement)
2931     return true;
2932
2933   // FIXME: Some tweaks might be needed for medium code model.
2934   if (M != CodeModel::Small && M != CodeModel::Kernel)
2935     return false;
2936
2937   // For small code model we assume that latest object is 16MB before end of 31
2938   // bits boundary. We may also accept pretty large negative constants knowing
2939   // that all objects are in the positive half of address space.
2940   if (M == CodeModel::Small && Offset < 16*1024*1024)
2941     return true;
2942
2943   // For kernel code model we know that all object resist in the negative half
2944   // of 32bits address space. We may not accept negative offsets, since they may
2945   // be just off and we may accept pretty large positive ones.
2946   if (M == CodeModel::Kernel && Offset > 0)
2947     return true;
2948
2949   return false;
2950 }
2951
2952 /// isCalleePop - Determines whether the callee is required to pop its
2953 /// own arguments. Callee pop is necessary to support tail calls.
2954 bool X86::isCalleePop(CallingConv::ID CallingConv,
2955                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2956   if (IsVarArg)
2957     return false;
2958
2959   switch (CallingConv) {
2960   default:
2961     return false;
2962   case CallingConv::X86_StdCall:
2963     return !is64Bit;
2964   case CallingConv::X86_FastCall:
2965     return !is64Bit;
2966   case CallingConv::X86_ThisCall:
2967     return !is64Bit;
2968   case CallingConv::Fast:
2969     return TailCallOpt;
2970   case CallingConv::GHC:
2971     return TailCallOpt;
2972   }
2973 }
2974
2975 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2976 /// specific condition code, returning the condition code and the LHS/RHS of the
2977 /// comparison to make.
2978 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2979                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2980   if (!isFP) {
2981     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2982       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2983         // X > -1   -> X == 0, jump !sign.
2984         RHS = DAG.getConstant(0, RHS.getValueType());
2985         return X86::COND_NS;
2986       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2987         // X < 0   -> X == 0, jump on sign.
2988         return X86::COND_S;
2989       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2990         // X < 1   -> X <= 0
2991         RHS = DAG.getConstant(0, RHS.getValueType());
2992         return X86::COND_LE;
2993       }
2994     }
2995
2996     switch (SetCCOpcode) {
2997     default: llvm_unreachable("Invalid integer condition!");
2998     case ISD::SETEQ:  return X86::COND_E;
2999     case ISD::SETGT:  return X86::COND_G;
3000     case ISD::SETGE:  return X86::COND_GE;
3001     case ISD::SETLT:  return X86::COND_L;
3002     case ISD::SETLE:  return X86::COND_LE;
3003     case ISD::SETNE:  return X86::COND_NE;
3004     case ISD::SETULT: return X86::COND_B;
3005     case ISD::SETUGT: return X86::COND_A;
3006     case ISD::SETULE: return X86::COND_BE;
3007     case ISD::SETUGE: return X86::COND_AE;
3008     }
3009   }
3010
3011   // First determine if it is required or is profitable to flip the operands.
3012
3013   // If LHS is a foldable load, but RHS is not, flip the condition.
3014   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3015       !ISD::isNON_EXTLoad(RHS.getNode())) {
3016     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3017     std::swap(LHS, RHS);
3018   }
3019
3020   switch (SetCCOpcode) {
3021   default: break;
3022   case ISD::SETOLT:
3023   case ISD::SETOLE:
3024   case ISD::SETUGT:
3025   case ISD::SETUGE:
3026     std::swap(LHS, RHS);
3027     break;
3028   }
3029
3030   // On a floating point condition, the flags are set as follows:
3031   // ZF  PF  CF   op
3032   //  0 | 0 | 0 | X > Y
3033   //  0 | 0 | 1 | X < Y
3034   //  1 | 0 | 0 | X == Y
3035   //  1 | 1 | 1 | unordered
3036   switch (SetCCOpcode) {
3037   default: llvm_unreachable("Condcode should be pre-legalized away");
3038   case ISD::SETUEQ:
3039   case ISD::SETEQ:   return X86::COND_E;
3040   case ISD::SETOLT:              // flipped
3041   case ISD::SETOGT:
3042   case ISD::SETGT:   return X86::COND_A;
3043   case ISD::SETOLE:              // flipped
3044   case ISD::SETOGE:
3045   case ISD::SETGE:   return X86::COND_AE;
3046   case ISD::SETUGT:              // flipped
3047   case ISD::SETULT:
3048   case ISD::SETLT:   return X86::COND_B;
3049   case ISD::SETUGE:              // flipped
3050   case ISD::SETULE:
3051   case ISD::SETLE:   return X86::COND_BE;
3052   case ISD::SETONE:
3053   case ISD::SETNE:   return X86::COND_NE;
3054   case ISD::SETUO:   return X86::COND_P;
3055   case ISD::SETO:    return X86::COND_NP;
3056   case ISD::SETOEQ:
3057   case ISD::SETUNE:  return X86::COND_INVALID;
3058   }
3059 }
3060
3061 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3062 /// code. Current x86 isa includes the following FP cmov instructions:
3063 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3064 static bool hasFPCMov(unsigned X86CC) {
3065   switch (X86CC) {
3066   default:
3067     return false;
3068   case X86::COND_B:
3069   case X86::COND_BE:
3070   case X86::COND_E:
3071   case X86::COND_P:
3072   case X86::COND_A:
3073   case X86::COND_AE:
3074   case X86::COND_NE:
3075   case X86::COND_NP:
3076     return true;
3077   }
3078 }
3079
3080 /// isFPImmLegal - Returns true if the target can instruction select the
3081 /// specified FP immediate natively. If false, the legalizer will
3082 /// materialize the FP immediate as a load from a constant pool.
3083 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3084   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3085     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3086       return true;
3087   }
3088   return false;
3089 }
3090
3091 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3092 /// the specified range (L, H].
3093 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3094   return (Val < 0) || (Val >= Low && Val < Hi);
3095 }
3096
3097 /// isUndefOrInRange - Return true if every element in Mask, begining
3098 /// from position Pos and ending in Pos+Size, falls within the specified
3099 /// range (L, L+Pos]. or is undef.
3100 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3101                              int Pos, int Size, int Low, int Hi) {
3102   for (int i = Pos, e = Pos+Size; i != e; ++i)
3103     if (!isUndefOrInRange(Mask[i], Low, Hi))
3104       return false;
3105   return true;
3106 }
3107
3108 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3109 /// specified value.
3110 static bool isUndefOrEqual(int Val, int CmpVal) {
3111   if (Val < 0 || Val == CmpVal)
3112     return true;
3113   return false;
3114 }
3115
3116 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3117 /// from position Pos and ending in Pos+Size, falls within the specified
3118 /// sequential range (L, L+Pos]. or is undef.
3119 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3120                                        int Pos, int Size, int Low) {
3121   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3122     if (!isUndefOrEqual(Mask[i], Low))
3123       return false;
3124   return true;
3125 }
3126
3127 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3128 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3129 /// the second operand.
3130 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3131   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3132     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3133   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3134     return (Mask[0] < 2 && Mask[1] < 2);
3135   return false;
3136 }
3137
3138 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3139   SmallVector<int, 8> M;
3140   N->getMask(M);
3141   return ::isPSHUFDMask(M, N->getValueType(0));
3142 }
3143
3144 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3145 /// is suitable for input to PSHUFHW.
3146 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3147   if (VT != MVT::v8i16)
3148     return false;
3149
3150   // Lower quadword copied in order or undef.
3151   for (int i = 0; i != 4; ++i)
3152     if (Mask[i] >= 0 && Mask[i] != i)
3153       return false;
3154
3155   // Upper quadword shuffled.
3156   for (int i = 4; i != 8; ++i)
3157     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3158       return false;
3159
3160   return true;
3161 }
3162
3163 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3164   SmallVector<int, 8> M;
3165   N->getMask(M);
3166   return ::isPSHUFHWMask(M, N->getValueType(0));
3167 }
3168
3169 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3170 /// is suitable for input to PSHUFLW.
3171 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172   if (VT != MVT::v8i16)
3173     return false;
3174
3175   // Upper quadword copied in order.
3176   for (int i = 4; i != 8; ++i)
3177     if (Mask[i] >= 0 && Mask[i] != i)
3178       return false;
3179
3180   // Lower quadword shuffled.
3181   for (int i = 0; i != 4; ++i)
3182     if (Mask[i] >= 4)
3183       return false;
3184
3185   return true;
3186 }
3187
3188 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3189   SmallVector<int, 8> M;
3190   N->getMask(M);
3191   return ::isPSHUFLWMask(M, N->getValueType(0));
3192 }
3193
3194 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3195 /// is suitable for input to PALIGNR.
3196 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3197                           bool hasSSSE3OrAVX) {
3198   int i, e = VT.getVectorNumElements();
3199   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3200     return false;
3201
3202   // Do not handle v2i64 / v2f64 shuffles with palignr.
3203   if (e < 4 || !hasSSSE3OrAVX)
3204     return false;
3205
3206   for (i = 0; i != e; ++i)
3207     if (Mask[i] >= 0)
3208       break;
3209
3210   // All undef, not a palignr.
3211   if (i == e)
3212     return false;
3213
3214   // Make sure we're shifting in the right direction.
3215   if (Mask[i] <= i)
3216     return false;
3217
3218   int s = Mask[i] - i;
3219
3220   // Check the rest of the elements to see if they are consecutive.
3221   for (++i; i != e; ++i) {
3222     int m = Mask[i];
3223     if (m >= 0 && m != s+i)
3224       return false;
3225   }
3226   return true;
3227 }
3228
3229 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3230 /// specifies a shuffle of elements that is suitable for input to 256-bit
3231 /// VSHUFPSY.
3232 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3233                           const X86Subtarget *Subtarget) {
3234   int NumElems = VT.getVectorNumElements();
3235
3236   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3237     return false;
3238
3239   if (NumElems != 8)
3240     return false;
3241
3242   // VSHUFPSY divides the resulting vector into 4 chunks.
3243   // The sources are also splitted into 4 chunks, and each destination
3244   // chunk must come from a different source chunk.
3245   //
3246   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3247   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3248   //
3249   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3250   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3251   //
3252   int QuarterSize = NumElems/4;
3253   int HalfSize = QuarterSize*2;
3254   for (int i = 0; i < QuarterSize; ++i)
3255     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3256       return false;
3257   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3258     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3259       return false;
3260
3261   // The mask of the second half must be the same as the first but with
3262   // the appropriate offsets. This works in the same way as VPERMILPS
3263   // works with masks.
3264   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3265     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3266       return false;
3267     int FstHalfIdx = i-HalfSize;
3268     if (Mask[FstHalfIdx] < 0)
3269       continue;
3270     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3271       return false;
3272   }
3273   for (int i = QuarterSize*3; i < NumElems; ++i) {
3274     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3275       return false;
3276     int FstHalfIdx = i-HalfSize;
3277     if (Mask[FstHalfIdx] < 0)
3278       continue;
3279     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3280       return false;
3281
3282   }
3283
3284   return true;
3285 }
3286
3287 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3288 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3289 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3291   EVT VT = SVOp->getValueType(0);
3292   int NumElems = VT.getVectorNumElements();
3293
3294   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3295          "Only supports v8i32 and v8f32 types");
3296
3297   int HalfSize = NumElems/2;
3298   unsigned Mask = 0;
3299   for (int i = 0; i != NumElems ; ++i) {
3300     if (SVOp->getMaskElt(i) < 0)
3301       continue;
3302     // The mask of the first half must be equal to the second one.
3303     unsigned Shamt = (i%HalfSize)*2;
3304     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3305     Mask |= Elt << Shamt;
3306   }
3307
3308   return Mask;
3309 }
3310
3311 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3312 /// specifies a shuffle of elements that is suitable for input to 256-bit
3313 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3314 /// version and the mask of the second half isn't binded with the first
3315 /// one.
3316 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3317                            const X86Subtarget *Subtarget) {
3318   int NumElems = VT.getVectorNumElements();
3319
3320   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3321     return false;
3322
3323   if (NumElems != 4)
3324     return false;
3325
3326   // VSHUFPSY divides the resulting vector into 4 chunks.
3327   // The sources are also splitted into 4 chunks, and each destination
3328   // chunk must come from a different source chunk.
3329   //
3330   //  SRC1 =>      X3       X2       X1       X0
3331   //  SRC2 =>      Y3       Y2       Y1       Y0
3332   //
3333   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3334   //
3335   int QuarterSize = NumElems/4;
3336   int HalfSize = QuarterSize*2;
3337   for (int i = 0; i < QuarterSize; ++i)
3338     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3339       return false;
3340   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3341     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3342       return false;
3343   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3344     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3345       return false;
3346   for (int i = QuarterSize*3; i < NumElems; ++i)
3347     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3348       return false;
3349
3350   return true;
3351 }
3352
3353 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3354 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3355 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3357   EVT VT = SVOp->getValueType(0);
3358   int NumElems = VT.getVectorNumElements();
3359
3360   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3361          "Only supports v4i64 and v4f64 types");
3362
3363   int HalfSize = NumElems/2;
3364   unsigned Mask = 0;
3365   for (int i = 0; i != NumElems ; ++i) {
3366     if (SVOp->getMaskElt(i) < 0)
3367       continue;
3368     int Elt = SVOp->getMaskElt(i) % HalfSize;
3369     Mask |= Elt << i;
3370   }
3371
3372   return Mask;
3373 }
3374
3375 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3376 /// specifies a shuffle of elements that is suitable for input to 128-bit
3377 /// SHUFPS and SHUFPD.
3378 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3379   int NumElems = VT.getVectorNumElements();
3380
3381   if (VT.getSizeInBits() != 128)
3382     return false;
3383
3384   if (NumElems != 2 && NumElems != 4)
3385     return false;
3386
3387   int Half = NumElems / 2;
3388   for (int i = 0; i < Half; ++i)
3389     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3390       return false;
3391   for (int i = Half; i < NumElems; ++i)
3392     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3393       return false;
3394
3395   return true;
3396 }
3397
3398 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3399   SmallVector<int, 8> M;
3400   N->getMask(M);
3401   return ::isSHUFPMask(M, N->getValueType(0));
3402 }
3403
3404 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3405 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3406 /// half elements to come from vector 1 (which would equal the dest.) and
3407 /// the upper half to come from vector 2.
3408 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3409   int NumElems = VT.getVectorNumElements();
3410
3411   if (NumElems != 2 && NumElems != 4)
3412     return false;
3413
3414   int Half = NumElems / 2;
3415   for (int i = 0; i < Half; ++i)
3416     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3417       return false;
3418   for (int i = Half; i < NumElems; ++i)
3419     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3420       return false;
3421   return true;
3422 }
3423
3424 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3425   SmallVector<int, 8> M;
3426   N->getMask(M);
3427   return isCommutedSHUFPMask(M, N->getValueType(0));
3428 }
3429
3430 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3431 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3432 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3433   EVT VT = N->getValueType(0);
3434   unsigned NumElems = VT.getVectorNumElements();
3435
3436   if (VT.getSizeInBits() != 128)
3437     return false;
3438
3439   if (NumElems != 4)
3440     return false;
3441
3442   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3443   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3444          isUndefOrEqual(N->getMaskElt(1), 7) &&
3445          isUndefOrEqual(N->getMaskElt(2), 2) &&
3446          isUndefOrEqual(N->getMaskElt(3), 3);
3447 }
3448
3449 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3450 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3451 /// <2, 3, 2, 3>
3452 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3453   EVT VT = N->getValueType(0);
3454   unsigned NumElems = VT.getVectorNumElements();
3455
3456   if (VT.getSizeInBits() != 128)
3457     return false;
3458
3459   if (NumElems != 4)
3460     return false;
3461
3462   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3463          isUndefOrEqual(N->getMaskElt(1), 3) &&
3464          isUndefOrEqual(N->getMaskElt(2), 2) &&
3465          isUndefOrEqual(N->getMaskElt(3), 3);
3466 }
3467
3468 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3469 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3470 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3471   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3472
3473   if (NumElems != 2 && NumElems != 4)
3474     return false;
3475
3476   for (unsigned i = 0; i < NumElems/2; ++i)
3477     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3478       return false;
3479
3480   for (unsigned i = NumElems/2; i < NumElems; ++i)
3481     if (!isUndefOrEqual(N->getMaskElt(i), i))
3482       return false;
3483
3484   return true;
3485 }
3486
3487 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3488 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3489 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3490   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3491
3492   if ((NumElems != 2 && NumElems != 4)
3493       || N->getValueType(0).getSizeInBits() > 128)
3494     return false;
3495
3496   for (unsigned i = 0; i < NumElems/2; ++i)
3497     if (!isUndefOrEqual(N->getMaskElt(i), i))
3498       return false;
3499
3500   for (unsigned i = 0; i < NumElems/2; ++i)
3501     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3502       return false;
3503
3504   return true;
3505 }
3506
3507 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3509 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3510                          bool V2IsSplat = false) {
3511   int NumElts = VT.getVectorNumElements();
3512
3513   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3514          "Unsupported vector type for unpckh");
3515
3516   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3517     return false;
3518
3519   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3520   // independently on 128-bit lanes.
3521   unsigned NumLanes = VT.getSizeInBits()/128;
3522   unsigned NumLaneElts = NumElts/NumLanes;
3523
3524   unsigned Start = 0;
3525   unsigned End = NumLaneElts;
3526   for (unsigned s = 0; s < NumLanes; ++s) {
3527     for (unsigned i = Start, j = s * NumLaneElts;
3528          i != End;
3529          i += 2, ++j) {
3530       int BitI  = Mask[i];
3531       int BitI1 = Mask[i+1];
3532       if (!isUndefOrEqual(BitI, j))
3533         return false;
3534       if (V2IsSplat) {
3535         if (!isUndefOrEqual(BitI1, NumElts))
3536           return false;
3537       } else {
3538         if (!isUndefOrEqual(BitI1, j + NumElts))
3539           return false;
3540       }
3541     }
3542     // Process the next 128 bits.
3543     Start += NumLaneElts;
3544     End += NumLaneElts;
3545   }
3546
3547   return true;
3548 }
3549
3550 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3551   SmallVector<int, 8> M;
3552   N->getMask(M);
3553   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3554 }
3555
3556 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3557 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3558 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3559                          bool V2IsSplat = false) {
3560   int NumElts = VT.getVectorNumElements();
3561
3562   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3563          "Unsupported vector type for unpckh");
3564
3565   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3566     return false;
3567
3568   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3569   // independently on 128-bit lanes.
3570   unsigned NumLanes = VT.getSizeInBits()/128;
3571   unsigned NumLaneElts = NumElts/NumLanes;
3572
3573   unsigned Start = 0;
3574   unsigned End = NumLaneElts;
3575   for (unsigned l = 0; l != NumLanes; ++l) {
3576     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3577                              i != End; i += 2, ++j) {
3578       int BitI  = Mask[i];
3579       int BitI1 = Mask[i+1];
3580       if (!isUndefOrEqual(BitI, j))
3581         return false;
3582       if (V2IsSplat) {
3583         if (isUndefOrEqual(BitI1, NumElts))
3584           return false;
3585       } else {
3586         if (!isUndefOrEqual(BitI1, j+NumElts))
3587           return false;
3588       }
3589     }
3590     // Process the next 128 bits.
3591     Start += NumLaneElts;
3592     End += NumLaneElts;
3593   }
3594   return true;
3595 }
3596
3597 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3598   SmallVector<int, 8> M;
3599   N->getMask(M);
3600   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3601 }
3602
3603 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3604 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3605 /// <0, 0, 1, 1>
3606 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3607   int NumElems = VT.getVectorNumElements();
3608   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3609     return false;
3610
3611   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3612   // FIXME: Need a better way to get rid of this, there's no latency difference
3613   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3614   // the former later. We should also remove the "_undef" special mask.
3615   if (NumElems == 4 && VT.getSizeInBits() == 256)
3616     return false;
3617
3618   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3619   // independently on 128-bit lanes.
3620   unsigned NumLanes = VT.getSizeInBits() / 128;
3621   unsigned NumLaneElts = NumElems / NumLanes;
3622
3623   for (unsigned s = 0; s < NumLanes; ++s) {
3624     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3625          i != NumLaneElts * (s + 1);
3626          i += 2, ++j) {
3627       int BitI  = Mask[i];
3628       int BitI1 = Mask[i+1];
3629
3630       if (!isUndefOrEqual(BitI, j))
3631         return false;
3632       if (!isUndefOrEqual(BitI1, j))
3633         return false;
3634     }
3635   }
3636
3637   return true;
3638 }
3639
3640 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3641   SmallVector<int, 8> M;
3642   N->getMask(M);
3643   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3644 }
3645
3646 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3647 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3648 /// <2, 2, 3, 3>
3649 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3650   int NumElems = VT.getVectorNumElements();
3651   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3652     return false;
3653
3654   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3655     int BitI  = Mask[i];
3656     int BitI1 = Mask[i+1];
3657     if (!isUndefOrEqual(BitI, j))
3658       return false;
3659     if (!isUndefOrEqual(BitI1, j))
3660       return false;
3661   }
3662   return true;
3663 }
3664
3665 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3666   SmallVector<int, 8> M;
3667   N->getMask(M);
3668   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3669 }
3670
3671 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3672 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3673 /// MOVSD, and MOVD, i.e. setting the lowest element.
3674 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3675   if (VT.getVectorElementType().getSizeInBits() < 32)
3676     return false;
3677
3678   int NumElts = VT.getVectorNumElements();
3679
3680   if (!isUndefOrEqual(Mask[0], NumElts))
3681     return false;
3682
3683   for (int i = 1; i < NumElts; ++i)
3684     if (!isUndefOrEqual(Mask[i], i))
3685       return false;
3686
3687   return true;
3688 }
3689
3690 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3691   SmallVector<int, 8> M;
3692   N->getMask(M);
3693   return ::isMOVLMask(M, N->getValueType(0));
3694 }
3695
3696 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3697 /// as permutations between 128-bit chunks or halves. As an example: this
3698 /// shuffle bellow:
3699 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3700 /// The first half comes from the second half of V1 and the second half from the
3701 /// the second half of V2.
3702 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3703                              const X86Subtarget *Subtarget) {
3704   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3705     return false;
3706
3707   // The shuffle result is divided into half A and half B. In total the two
3708   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3709   // B must come from C, D, E or F.
3710   int HalfSize = VT.getVectorNumElements()/2;
3711   bool MatchA = false, MatchB = false;
3712
3713   // Check if A comes from one of C, D, E, F.
3714   for (int Half = 0; Half < 4; ++Half) {
3715     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3716       MatchA = true;
3717       break;
3718     }
3719   }
3720
3721   // Check if B comes from one of C, D, E, F.
3722   for (int Half = 0; Half < 4; ++Half) {
3723     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3724       MatchB = true;
3725       break;
3726     }
3727   }
3728
3729   return MatchA && MatchB;
3730 }
3731
3732 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3733 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3734 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3736   EVT VT = SVOp->getValueType(0);
3737
3738   int HalfSize = VT.getVectorNumElements()/2;
3739
3740   int FstHalf = 0, SndHalf = 0;
3741   for (int i = 0; i < HalfSize; ++i) {
3742     if (SVOp->getMaskElt(i) > 0) {
3743       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3744       break;
3745     }
3746   }
3747   for (int i = HalfSize; i < HalfSize*2; ++i) {
3748     if (SVOp->getMaskElt(i) > 0) {
3749       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3750       break;
3751     }
3752   }
3753
3754   return (FstHalf | (SndHalf << 4));
3755 }
3756
3757 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3758 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3759 /// Note that VPERMIL mask matching is different depending whether theunderlying
3760 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3761 /// to the same elements of the low, but to the higher half of the source.
3762 /// In VPERMILPD the two lanes could be shuffled independently of each other
3763 /// with the same restriction that lanes can't be crossed.
3764 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3765                             const X86Subtarget *Subtarget) {
3766   int NumElts = VT.getVectorNumElements();
3767   int NumLanes = VT.getSizeInBits()/128;
3768
3769   if (!Subtarget->hasAVX())
3770     return false;
3771
3772   // Only match 256-bit with 64-bit types
3773   if (VT.getSizeInBits() != 256 || NumElts != 4)
3774     return false;
3775
3776   // The mask on the high lane is independent of the low. Both can match
3777   // any element in inside its own lane, but can't cross.
3778   int LaneSize = NumElts/NumLanes;
3779   for (int l = 0; l < NumLanes; ++l)
3780     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3781       int LaneStart = l*LaneSize;
3782       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3783         return false;
3784     }
3785
3786   return true;
3787 }
3788
3789 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3791 /// Note that VPERMIL mask matching is different depending whether theunderlying
3792 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3793 /// to the same elements of the low, but to the higher half of the source.
3794 /// In VPERMILPD the two lanes could be shuffled independently of each other
3795 /// with the same restriction that lanes can't be crossed.
3796 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3797                             const X86Subtarget *Subtarget) {
3798   unsigned NumElts = VT.getVectorNumElements();
3799   unsigned NumLanes = VT.getSizeInBits()/128;
3800
3801   if (!Subtarget->hasAVX())
3802     return false;
3803
3804   // Only match 256-bit with 32-bit types
3805   if (VT.getSizeInBits() != 256 || NumElts != 8)
3806     return false;
3807
3808   // The mask on the high lane should be the same as the low. Actually,
3809   // they can differ if any of the corresponding index in a lane is undef
3810   // and the other stays in range.
3811   int LaneSize = NumElts/NumLanes;
3812   for (int i = 0; i < LaneSize; ++i) {
3813     int HighElt = i+LaneSize;
3814     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3815     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3816
3817     if (!HighValid || !LowValid)
3818       return false;
3819     if (Mask[i] < 0 || Mask[HighElt] < 0)
3820       continue;
3821     if (Mask[HighElt]-Mask[i] != LaneSize)
3822       return false;
3823   }
3824
3825   return true;
3826 }
3827
3828 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3829 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3830 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3831   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3832   EVT VT = SVOp->getValueType(0);
3833
3834   int NumElts = VT.getVectorNumElements();
3835   int NumLanes = VT.getSizeInBits()/128;
3836   int LaneSize = NumElts/NumLanes;
3837
3838   // Although the mask is equal for both lanes do it twice to get the cases
3839   // where a mask will match because the same mask element is undef on the
3840   // first half but valid on the second. This would get pathological cases
3841   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3842   unsigned Mask = 0;
3843   for (int l = 0; l < NumLanes; ++l) {
3844     for (int i = 0; i < LaneSize; ++i) {
3845       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3846       if (MaskElt < 0)
3847         continue;
3848       if (MaskElt >= LaneSize)
3849         MaskElt -= LaneSize;
3850       Mask |= MaskElt << (i*2);
3851     }
3852   }
3853
3854   return Mask;
3855 }
3856
3857 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3859 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3861   EVT VT = SVOp->getValueType(0);
3862
3863   int NumElts = VT.getVectorNumElements();
3864   int NumLanes = VT.getSizeInBits()/128;
3865
3866   unsigned Mask = 0;
3867   int LaneSize = NumElts/NumLanes;
3868   for (int l = 0; l < NumLanes; ++l)
3869     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3870       int MaskElt = SVOp->getMaskElt(i);
3871       if (MaskElt < 0)
3872         continue;
3873       Mask |= (MaskElt-l*LaneSize) << i;
3874     }
3875
3876   return Mask;
3877 }
3878
3879 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3880 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3881 /// element of vector 2 and the other elements to come from vector 1 in order.
3882 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3883                                bool V2IsSplat = false, bool V2IsUndef = false) {
3884   int NumOps = VT.getVectorNumElements();
3885   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3886     return false;
3887
3888   if (!isUndefOrEqual(Mask[0], 0))
3889     return false;
3890
3891   for (int i = 1; i < NumOps; ++i)
3892     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3893           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3894           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3895       return false;
3896
3897   return true;
3898 }
3899
3900 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3901                            bool V2IsUndef = false) {
3902   SmallVector<int, 8> M;
3903   N->getMask(M);
3904   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3905 }
3906
3907 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3909 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3910 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3911                          const X86Subtarget *Subtarget) {
3912   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3913     return false;
3914
3915   // The second vector must be undef
3916   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3917     return false;
3918
3919   EVT VT = N->getValueType(0);
3920   unsigned NumElems = VT.getVectorNumElements();
3921
3922   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3923       (VT.getSizeInBits() == 256 && NumElems != 8))
3924     return false;
3925
3926   // "i+1" is the value the indexed mask element must have
3927   for (unsigned i = 0; i < NumElems; i += 2)
3928     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3929         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3930       return false;
3931
3932   return true;
3933 }
3934
3935 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3937 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3938 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3939                          const X86Subtarget *Subtarget) {
3940   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3941     return false;
3942
3943   // The second vector must be undef
3944   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3945     return false;
3946
3947   EVT VT = N->getValueType(0);
3948   unsigned NumElems = VT.getVectorNumElements();
3949
3950   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3951       (VT.getSizeInBits() == 256 && NumElems != 8))
3952     return false;
3953
3954   // "i" is the value the indexed mask element must have
3955   for (unsigned i = 0; i < NumElems; i += 2)
3956     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3957         !isUndefOrEqual(N->getMaskElt(i+1), i))
3958       return false;
3959
3960   return true;
3961 }
3962
3963 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3964 /// specifies a shuffle of elements that is suitable for input to 256-bit
3965 /// version of MOVDDUP.
3966 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3967                            const X86Subtarget *Subtarget) {
3968   EVT VT = N->getValueType(0);
3969   int NumElts = VT.getVectorNumElements();
3970   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3971
3972   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3973       !V2IsUndef || NumElts != 4)
3974     return false;
3975
3976   for (int i = 0; i != NumElts/2; ++i)
3977     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3978       return false;
3979   for (int i = NumElts/2; i != NumElts; ++i)
3980     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3981       return false;
3982   return true;
3983 }
3984
3985 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3986 /// specifies a shuffle of elements that is suitable for input to 128-bit
3987 /// version of MOVDDUP.
3988 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3989   EVT VT = N->getValueType(0);
3990
3991   if (VT.getSizeInBits() != 128)
3992     return false;
3993
3994   int e = VT.getVectorNumElements() / 2;
3995   for (int i = 0; i < e; ++i)
3996     if (!isUndefOrEqual(N->getMaskElt(i), i))
3997       return false;
3998   for (int i = 0; i < e; ++i)
3999     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4000       return false;
4001   return true;
4002 }
4003
4004 /// isVEXTRACTF128Index - Return true if the specified
4005 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4006 /// suitable for input to VEXTRACTF128.
4007 bool X86::isVEXTRACTF128Index(SDNode *N) {
4008   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4009     return false;
4010
4011   // The index should be aligned on a 128-bit boundary.
4012   uint64_t Index =
4013     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4014
4015   unsigned VL = N->getValueType(0).getVectorNumElements();
4016   unsigned VBits = N->getValueType(0).getSizeInBits();
4017   unsigned ElSize = VBits / VL;
4018   bool Result = (Index * ElSize) % 128 == 0;
4019
4020   return Result;
4021 }
4022
4023 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4024 /// operand specifies a subvector insert that is suitable for input to
4025 /// VINSERTF128.
4026 bool X86::isVINSERTF128Index(SDNode *N) {
4027   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4028     return false;
4029
4030   // The index should be aligned on a 128-bit boundary.
4031   uint64_t Index =
4032     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4033
4034   unsigned VL = N->getValueType(0).getVectorNumElements();
4035   unsigned VBits = N->getValueType(0).getSizeInBits();
4036   unsigned ElSize = VBits / VL;
4037   bool Result = (Index * ElSize) % 128 == 0;
4038
4039   return Result;
4040 }
4041
4042 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4044 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4046   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4047
4048   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4049   unsigned Mask = 0;
4050   for (int i = 0; i < NumOperands; ++i) {
4051     int Val = SVOp->getMaskElt(NumOperands-i-1);
4052     if (Val < 0) Val = 0;
4053     if (Val >= NumOperands) Val -= NumOperands;
4054     Mask |= Val;
4055     if (i != NumOperands - 1)
4056       Mask <<= Shift;
4057   }
4058   return Mask;
4059 }
4060
4061 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4062 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4063 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4064   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4065   unsigned Mask = 0;
4066   // 8 nodes, but we only care about the last 4.
4067   for (unsigned i = 7; i >= 4; --i) {
4068     int Val = SVOp->getMaskElt(i);
4069     if (Val >= 0)
4070       Mask |= (Val - 4);
4071     if (i != 4)
4072       Mask <<= 2;
4073   }
4074   return Mask;
4075 }
4076
4077 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4078 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4079 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4080   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4081   unsigned Mask = 0;
4082   // 8 nodes, but we only care about the first 4.
4083   for (int i = 3; i >= 0; --i) {
4084     int Val = SVOp->getMaskElt(i);
4085     if (Val >= 0)
4086       Mask |= Val;
4087     if (i != 0)
4088       Mask <<= 2;
4089   }
4090   return Mask;
4091 }
4092
4093 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4094 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4095 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4097   EVT VVT = N->getValueType(0);
4098   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4099   int Val = 0;
4100
4101   unsigned i, e;
4102   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4103     Val = SVOp->getMaskElt(i);
4104     if (Val >= 0)
4105       break;
4106   }
4107   assert(Val - i > 0 && "PALIGNR imm should be positive");
4108   return (Val - i) * EltSize;
4109 }
4110
4111 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4112 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4113 /// instructions.
4114 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4115   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4116     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4117
4118   uint64_t Index =
4119     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4120
4121   EVT VecVT = N->getOperand(0).getValueType();
4122   EVT ElVT = VecVT.getVectorElementType();
4123
4124   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4125   return Index / NumElemsPerChunk;
4126 }
4127
4128 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4129 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4130 /// instructions.
4131 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4132   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4133     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4134
4135   uint64_t Index =
4136     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4137
4138   EVT VecVT = N->getValueType(0);
4139   EVT ElVT = VecVT.getVectorElementType();
4140
4141   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4142   return Index / NumElemsPerChunk;
4143 }
4144
4145 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4146 /// constant +0.0.
4147 bool X86::isZeroNode(SDValue Elt) {
4148   return ((isa<ConstantSDNode>(Elt) &&
4149            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4150           (isa<ConstantFPSDNode>(Elt) &&
4151            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4152 }
4153
4154 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4155 /// their permute mask.
4156 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4157                                     SelectionDAG &DAG) {
4158   EVT VT = SVOp->getValueType(0);
4159   unsigned NumElems = VT.getVectorNumElements();
4160   SmallVector<int, 8> MaskVec;
4161
4162   for (unsigned i = 0; i != NumElems; ++i) {
4163     int idx = SVOp->getMaskElt(i);
4164     if (idx < 0)
4165       MaskVec.push_back(idx);
4166     else if (idx < (int)NumElems)
4167       MaskVec.push_back(idx + NumElems);
4168     else
4169       MaskVec.push_back(idx - NumElems);
4170   }
4171   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4172                               SVOp->getOperand(0), &MaskVec[0]);
4173 }
4174
4175 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4176 /// the two vector operands have swapped position.
4177 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4178   unsigned NumElems = VT.getVectorNumElements();
4179   for (unsigned i = 0; i != NumElems; ++i) {
4180     int idx = Mask[i];
4181     if (idx < 0)
4182       continue;
4183     else if (idx < (int)NumElems)
4184       Mask[i] = idx + NumElems;
4185     else
4186       Mask[i] = idx - NumElems;
4187   }
4188 }
4189
4190 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4191 /// match movhlps. The lower half elements should come from upper half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order).
4194 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4195   EVT VT = Op->getValueType(0);
4196   if (VT.getSizeInBits() != 128)
4197     return false;
4198   if (VT.getVectorNumElements() != 4)
4199     return false;
4200   for (unsigned i = 0, e = 2; i != e; ++i)
4201     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4202       return false;
4203   for (unsigned i = 2; i != 4; ++i)
4204     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4205       return false;
4206   return true;
4207 }
4208
4209 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4210 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4211 /// required.
4212 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4213   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4214     return false;
4215   N = N->getOperand(0).getNode();
4216   if (!ISD::isNON_EXTLoad(N))
4217     return false;
4218   if (LD)
4219     *LD = cast<LoadSDNode>(N);
4220   return true;
4221 }
4222
4223 // Test whether the given value is a vector value which will be legalized
4224 // into a load.
4225 static bool WillBeConstantPoolLoad(SDNode *N) {
4226   if (N->getOpcode() != ISD::BUILD_VECTOR)
4227     return false;
4228
4229   // Check for any non-constant elements.
4230   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4231     switch (N->getOperand(i).getNode()->getOpcode()) {
4232     case ISD::UNDEF:
4233     case ISD::ConstantFP:
4234     case ISD::Constant:
4235       break;
4236     default:
4237       return false;
4238     }
4239
4240   // Vectors of all-zeros and all-ones are materialized with special
4241   // instructions rather than being loaded.
4242   return !ISD::isBuildVectorAllZeros(N) &&
4243          !ISD::isBuildVectorAllOnes(N);
4244 }
4245
4246 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4247 /// match movlp{s|d}. The lower half elements should come from lower half of
4248 /// V1 (and in order), and the upper half elements should come from the upper
4249 /// half of V2 (and in order). And since V1 will become the source of the
4250 /// MOVLP, it must be either a vector load or a scalar load to vector.
4251 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4252                                ShuffleVectorSDNode *Op) {
4253   EVT VT = Op->getValueType(0);
4254   if (VT.getSizeInBits() != 128)
4255     return false;
4256
4257   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4258     return false;
4259   // Is V2 is a vector load, don't do this transformation. We will try to use
4260   // load folding shufps op.
4261   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4262     return false;
4263
4264   unsigned NumElems = VT.getVectorNumElements();
4265
4266   if (NumElems != 2 && NumElems != 4)
4267     return false;
4268   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4269     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4270       return false;
4271   for (unsigned i = NumElems/2; i != NumElems; ++i)
4272     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4273       return false;
4274   return true;
4275 }
4276
4277 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4278 /// all the same.
4279 static bool isSplatVector(SDNode *N) {
4280   if (N->getOpcode() != ISD::BUILD_VECTOR)
4281     return false;
4282
4283   SDValue SplatValue = N->getOperand(0);
4284   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4285     if (N->getOperand(i) != SplatValue)
4286       return false;
4287   return true;
4288 }
4289
4290 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4291 /// to an zero vector.
4292 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4293 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4294   SDValue V1 = N->getOperand(0);
4295   SDValue V2 = N->getOperand(1);
4296   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4297   for (unsigned i = 0; i != NumElems; ++i) {
4298     int Idx = N->getMaskElt(i);
4299     if (Idx >= (int)NumElems) {
4300       unsigned Opc = V2.getOpcode();
4301       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4302         continue;
4303       if (Opc != ISD::BUILD_VECTOR ||
4304           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4305         return false;
4306     } else if (Idx >= 0) {
4307       unsigned Opc = V1.getOpcode();
4308       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4309         continue;
4310       if (Opc != ISD::BUILD_VECTOR ||
4311           !X86::isZeroNode(V1.getOperand(Idx)))
4312         return false;
4313     }
4314   }
4315   return true;
4316 }
4317
4318 /// getZeroVector - Returns a vector of specified type with all zero elements.
4319 ///
4320 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4321                              DebugLoc dl) {
4322   assert(VT.isVector() && "Expected a vector type");
4323
4324   // Always build SSE zero vectors as <4 x i32> bitcasted
4325   // to their dest type. This ensures they get CSE'd.
4326   SDValue Vec;
4327   if (VT.getSizeInBits() == 128) {  // SSE
4328     if (HasXMMInt) {  // SSE2
4329       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4330       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4331     } else { // SSE1
4332       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4333       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4334     }
4335   } else if (VT.getSizeInBits() == 256) { // AVX
4336     // 256-bit logic and arithmetic instructions in AVX are
4337     // all floating-point, no support for integer ops. Default
4338     // to emitting fp zeroed vectors then.
4339     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4340     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4341     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4342   }
4343   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4344 }
4345
4346 /// getOnesVector - Returns a vector of specified type with all bits set.
4347 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4348 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4349 /// original type, ensuring they get CSE'd.
4350 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4351   assert(VT.isVector() && "Expected a vector type");
4352   assert((VT.is128BitVector() || VT.is256BitVector())
4353          && "Expected a 128-bit or 256-bit vector type");
4354
4355   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4356   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4357                             Cst, Cst, Cst, Cst);
4358
4359   if (VT.is256BitVector()) {
4360     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4361                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4362     Vec = Insert128BitVector(InsV, Vec,
4363                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4364   }
4365
4366   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4367 }
4368
4369 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4370 /// that point to V2 points to its first element.
4371 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4372   EVT VT = SVOp->getValueType(0);
4373   unsigned NumElems = VT.getVectorNumElements();
4374
4375   bool Changed = false;
4376   SmallVector<int, 8> MaskVec;
4377   SVOp->getMask(MaskVec);
4378
4379   for (unsigned i = 0; i != NumElems; ++i) {
4380     if (MaskVec[i] > (int)NumElems) {
4381       MaskVec[i] = NumElems;
4382       Changed = true;
4383     }
4384   }
4385   if (Changed)
4386     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4387                                 SVOp->getOperand(1), &MaskVec[0]);
4388   return SDValue(SVOp, 0);
4389 }
4390
4391 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4392 /// operation of specified width.
4393 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4394                        SDValue V2) {
4395   unsigned NumElems = VT.getVectorNumElements();
4396   SmallVector<int, 8> Mask;
4397   Mask.push_back(NumElems);
4398   for (unsigned i = 1; i != NumElems; ++i)
4399     Mask.push_back(i);
4400   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4401 }
4402
4403 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4404 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4405                           SDValue V2) {
4406   unsigned NumElems = VT.getVectorNumElements();
4407   SmallVector<int, 8> Mask;
4408   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4409     Mask.push_back(i);
4410     Mask.push_back(i + NumElems);
4411   }
4412   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4413 }
4414
4415 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4416 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4417                           SDValue V2) {
4418   unsigned NumElems = VT.getVectorNumElements();
4419   unsigned Half = NumElems/2;
4420   SmallVector<int, 8> Mask;
4421   for (unsigned i = 0; i != Half; ++i) {
4422     Mask.push_back(i + Half);
4423     Mask.push_back(i + NumElems + Half);
4424   }
4425   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4426 }
4427
4428 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4429 // a generic shuffle instruction because the target has no such instructions.
4430 // Generate shuffles which repeat i16 and i8 several times until they can be
4431 // represented by v4f32 and then be manipulated by target suported shuffles.
4432 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4433   EVT VT = V.getValueType();
4434   int NumElems = VT.getVectorNumElements();
4435   DebugLoc dl = V.getDebugLoc();
4436
4437   while (NumElems > 4) {
4438     if (EltNo < NumElems/2) {
4439       V = getUnpackl(DAG, dl, VT, V, V);
4440     } else {
4441       V = getUnpackh(DAG, dl, VT, V, V);
4442       EltNo -= NumElems/2;
4443     }
4444     NumElems >>= 1;
4445   }
4446   return V;
4447 }
4448
4449 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4450 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4451   EVT VT = V.getValueType();
4452   DebugLoc dl = V.getDebugLoc();
4453   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4454          && "Vector size not supported");
4455
4456   if (VT.getSizeInBits() == 128) {
4457     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4458     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4459     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4460                              &SplatMask[0]);
4461   } else {
4462     // To use VPERMILPS to splat scalars, the second half of indicies must
4463     // refer to the higher part, which is a duplication of the lower one,
4464     // because VPERMILPS can only handle in-lane permutations.
4465     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4466                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4467
4468     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4469     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4470                              &SplatMask[0]);
4471   }
4472
4473   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4474 }
4475
4476 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4477 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4478   EVT SrcVT = SV->getValueType(0);
4479   SDValue V1 = SV->getOperand(0);
4480   DebugLoc dl = SV->getDebugLoc();
4481
4482   int EltNo = SV->getSplatIndex();
4483   int NumElems = SrcVT.getVectorNumElements();
4484   unsigned Size = SrcVT.getSizeInBits();
4485
4486   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4487           "Unknown how to promote splat for type");
4488
4489   // Extract the 128-bit part containing the splat element and update
4490   // the splat element index when it refers to the higher register.
4491   if (Size == 256) {
4492     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4493     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4494     if (Idx > 0)
4495       EltNo -= NumElems/2;
4496   }
4497
4498   // All i16 and i8 vector types can't be used directly by a generic shuffle
4499   // instruction because the target has no such instruction. Generate shuffles
4500   // which repeat i16 and i8 several times until they fit in i32, and then can
4501   // be manipulated by target suported shuffles.
4502   EVT EltVT = SrcVT.getVectorElementType();
4503   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4504     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4505
4506   // Recreate the 256-bit vector and place the same 128-bit vector
4507   // into the low and high part. This is necessary because we want
4508   // to use VPERM* to shuffle the vectors
4509   if (Size == 256) {
4510     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4511                          DAG.getConstant(0, MVT::i32), DAG, dl);
4512     V1 = Insert128BitVector(InsV, V1,
4513                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4514   }
4515
4516   return getLegalSplat(DAG, V1, EltNo);
4517 }
4518
4519 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4520 /// vector of zero or undef vector.  This produces a shuffle where the low
4521 /// element of V2 is swizzled into the zero/undef vector, landing at element
4522 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4523 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4524                                            bool isZero, bool HasXMMInt,
4525                                            SelectionDAG &DAG) {
4526   EVT VT = V2.getValueType();
4527   SDValue V1 = isZero
4528     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4529   unsigned NumElems = VT.getVectorNumElements();
4530   SmallVector<int, 16> MaskVec;
4531   for (unsigned i = 0; i != NumElems; ++i)
4532     // If this is the insertion idx, put the low elt of V2 here.
4533     MaskVec.push_back(i == Idx ? NumElems : i);
4534   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4535 }
4536
4537 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4538 /// element of the result of the vector shuffle.
4539 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4540                                    unsigned Depth) {
4541   if (Depth == 6)
4542     return SDValue();  // Limit search depth.
4543
4544   SDValue V = SDValue(N, 0);
4545   EVT VT = V.getValueType();
4546   unsigned Opcode = V.getOpcode();
4547
4548   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4549   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4550     Index = SV->getMaskElt(Index);
4551
4552     if (Index < 0)
4553       return DAG.getUNDEF(VT.getVectorElementType());
4554
4555     int NumElems = VT.getVectorNumElements();
4556     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4557     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4558   }
4559
4560   // Recurse into target specific vector shuffles to find scalars.
4561   if (isTargetShuffle(Opcode)) {
4562     int NumElems = VT.getVectorNumElements();
4563     SmallVector<unsigned, 16> ShuffleMask;
4564     SDValue ImmN;
4565
4566     switch(Opcode) {
4567     case X86ISD::SHUFPS:
4568     case X86ISD::SHUFPD:
4569       ImmN = N->getOperand(N->getNumOperands()-1);
4570       DecodeSHUFPSMask(NumElems,
4571                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4572                        ShuffleMask);
4573       break;
4574     case X86ISD::PUNPCKHBW:
4575     case X86ISD::PUNPCKHWD:
4576     case X86ISD::PUNPCKHDQ:
4577     case X86ISD::PUNPCKHQDQ:
4578       DecodePUNPCKHMask(NumElems, ShuffleMask);
4579       break;
4580     case X86ISD::UNPCKHPS:
4581     case X86ISD::UNPCKHPD:
4582     case X86ISD::VUNPCKHPSY:
4583     case X86ISD::VUNPCKHPDY:
4584       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4585       break;
4586     case X86ISD::PUNPCKLBW:
4587     case X86ISD::PUNPCKLWD:
4588     case X86ISD::PUNPCKLDQ:
4589     case X86ISD::PUNPCKLQDQ:
4590       DecodePUNPCKLMask(VT, ShuffleMask);
4591       break;
4592     case X86ISD::UNPCKLPS:
4593     case X86ISD::UNPCKLPD:
4594     case X86ISD::VUNPCKLPSY:
4595     case X86ISD::VUNPCKLPDY:
4596       DecodeUNPCKLPMask(VT, ShuffleMask);
4597       break;
4598     case X86ISD::MOVHLPS:
4599       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4600       break;
4601     case X86ISD::MOVLHPS:
4602       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4603       break;
4604     case X86ISD::PSHUFD:
4605       ImmN = N->getOperand(N->getNumOperands()-1);
4606       DecodePSHUFMask(NumElems,
4607                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4608                       ShuffleMask);
4609       break;
4610     case X86ISD::PSHUFHW:
4611       ImmN = N->getOperand(N->getNumOperands()-1);
4612       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4613                         ShuffleMask);
4614       break;
4615     case X86ISD::PSHUFLW:
4616       ImmN = N->getOperand(N->getNumOperands()-1);
4617       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4618                         ShuffleMask);
4619       break;
4620     case X86ISD::MOVSS:
4621     case X86ISD::MOVSD: {
4622       // The index 0 always comes from the first element of the second source,
4623       // this is why MOVSS and MOVSD are used in the first place. The other
4624       // elements come from the other positions of the first source vector.
4625       unsigned OpNum = (Index == 0) ? 1 : 0;
4626       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4627                                  Depth+1);
4628     }
4629     case X86ISD::VPERMILPS:
4630       ImmN = N->getOperand(N->getNumOperands()-1);
4631       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4632                         ShuffleMask);
4633       break;
4634     case X86ISD::VPERMILPSY:
4635       ImmN = N->getOperand(N->getNumOperands()-1);
4636       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4637                         ShuffleMask);
4638       break;
4639     case X86ISD::VPERMILPD:
4640       ImmN = N->getOperand(N->getNumOperands()-1);
4641       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4642                         ShuffleMask);
4643       break;
4644     case X86ISD::VPERMILPDY:
4645       ImmN = N->getOperand(N->getNumOperands()-1);
4646       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4647                         ShuffleMask);
4648       break;
4649     case X86ISD::VPERM2F128:
4650       ImmN = N->getOperand(N->getNumOperands()-1);
4651       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4652                            ShuffleMask);
4653       break;
4654     case X86ISD::MOVDDUP:
4655     case X86ISD::MOVLHPD:
4656     case X86ISD::MOVLPD:
4657     case X86ISD::MOVLPS:
4658     case X86ISD::MOVSHDUP:
4659     case X86ISD::MOVSLDUP:
4660     case X86ISD::PALIGN:
4661       return SDValue(); // Not yet implemented.
4662     default:
4663       assert(0 && "unknown target shuffle node");
4664       return SDValue();
4665     }
4666
4667     Index = ShuffleMask[Index];
4668     if (Index < 0)
4669       return DAG.getUNDEF(VT.getVectorElementType());
4670
4671     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4672     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4673                                Depth+1);
4674   }
4675
4676   // Actual nodes that may contain scalar elements
4677   if (Opcode == ISD::BITCAST) {
4678     V = V.getOperand(0);
4679     EVT SrcVT = V.getValueType();
4680     unsigned NumElems = VT.getVectorNumElements();
4681
4682     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4683       return SDValue();
4684   }
4685
4686   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4687     return (Index == 0) ? V.getOperand(0)
4688                           : DAG.getUNDEF(VT.getVectorElementType());
4689
4690   if (V.getOpcode() == ISD::BUILD_VECTOR)
4691     return V.getOperand(Index);
4692
4693   return SDValue();
4694 }
4695
4696 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4697 /// shuffle operation which come from a consecutively from a zero. The
4698 /// search can start in two different directions, from left or right.
4699 static
4700 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4701                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4702   int i = 0;
4703
4704   while (i < NumElems) {
4705     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4706     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4707     if (!(Elt.getNode() &&
4708          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4709       break;
4710     ++i;
4711   }
4712
4713   return i;
4714 }
4715
4716 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4717 /// MaskE correspond consecutively to elements from one of the vector operands,
4718 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4719 static
4720 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4721                               int OpIdx, int NumElems, unsigned &OpNum) {
4722   bool SeenV1 = false;
4723   bool SeenV2 = false;
4724
4725   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4726     int Idx = SVOp->getMaskElt(i);
4727     // Ignore undef indicies
4728     if (Idx < 0)
4729       continue;
4730
4731     if (Idx < NumElems)
4732       SeenV1 = true;
4733     else
4734       SeenV2 = true;
4735
4736     // Only accept consecutive elements from the same vector
4737     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4738       return false;
4739   }
4740
4741   OpNum = SeenV1 ? 0 : 1;
4742   return true;
4743 }
4744
4745 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4746 /// logical left shift of a vector.
4747 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4748                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4749   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4750   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4751               false /* check zeros from right */, DAG);
4752   unsigned OpSrc;
4753
4754   if (!NumZeros)
4755     return false;
4756
4757   // Considering the elements in the mask that are not consecutive zeros,
4758   // check if they consecutively come from only one of the source vectors.
4759   //
4760   //               V1 = {X, A, B, C}     0
4761   //                         \  \  \    /
4762   //   vector_shuffle V1, V2 <1, 2, 3, X>
4763   //
4764   if (!isShuffleMaskConsecutive(SVOp,
4765             0,                   // Mask Start Index
4766             NumElems-NumZeros-1, // Mask End Index
4767             NumZeros,            // Where to start looking in the src vector
4768             NumElems,            // Number of elements in vector
4769             OpSrc))              // Which source operand ?
4770     return false;
4771
4772   isLeft = false;
4773   ShAmt = NumZeros;
4774   ShVal = SVOp->getOperand(OpSrc);
4775   return true;
4776 }
4777
4778 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4779 /// logical left shift of a vector.
4780 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4781                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4782   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4783   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4784               true /* check zeros from left */, DAG);
4785   unsigned OpSrc;
4786
4787   if (!NumZeros)
4788     return false;
4789
4790   // Considering the elements in the mask that are not consecutive zeros,
4791   // check if they consecutively come from only one of the source vectors.
4792   //
4793   //                           0    { A, B, X, X } = V2
4794   //                          / \    /  /
4795   //   vector_shuffle V1, V2 <X, X, 4, 5>
4796   //
4797   if (!isShuffleMaskConsecutive(SVOp,
4798             NumZeros,     // Mask Start Index
4799             NumElems-1,   // Mask End Index
4800             0,            // Where to start looking in the src vector
4801             NumElems,     // Number of elements in vector
4802             OpSrc))       // Which source operand ?
4803     return false;
4804
4805   isLeft = true;
4806   ShAmt = NumZeros;
4807   ShVal = SVOp->getOperand(OpSrc);
4808   return true;
4809 }
4810
4811 /// isVectorShift - Returns true if the shuffle can be implemented as a
4812 /// logical left or right shift of a vector.
4813 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4814                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4815   // Although the logic below support any bitwidth size, there are no
4816   // shift instructions which handle more than 128-bit vectors.
4817   if (SVOp->getValueType(0).getSizeInBits() > 128)
4818     return false;
4819
4820   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4821       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4822     return true;
4823
4824   return false;
4825 }
4826
4827 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4828 ///
4829 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4830                                        unsigned NumNonZero, unsigned NumZero,
4831                                        SelectionDAG &DAG,
4832                                        const TargetLowering &TLI) {
4833   if (NumNonZero > 8)
4834     return SDValue();
4835
4836   DebugLoc dl = Op.getDebugLoc();
4837   SDValue V(0, 0);
4838   bool First = true;
4839   for (unsigned i = 0; i < 16; ++i) {
4840     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4841     if (ThisIsNonZero && First) {
4842       if (NumZero)
4843         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4844       else
4845         V = DAG.getUNDEF(MVT::v8i16);
4846       First = false;
4847     }
4848
4849     if ((i & 1) != 0) {
4850       SDValue ThisElt(0, 0), LastElt(0, 0);
4851       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4852       if (LastIsNonZero) {
4853         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4854                               MVT::i16, Op.getOperand(i-1));
4855       }
4856       if (ThisIsNonZero) {
4857         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4858         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4859                               ThisElt, DAG.getConstant(8, MVT::i8));
4860         if (LastIsNonZero)
4861           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4862       } else
4863         ThisElt = LastElt;
4864
4865       if (ThisElt.getNode())
4866         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4867                         DAG.getIntPtrConstant(i/2));
4868     }
4869   }
4870
4871   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4872 }
4873
4874 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4875 ///
4876 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4877                                      unsigned NumNonZero, unsigned NumZero,
4878                                      SelectionDAG &DAG,
4879                                      const TargetLowering &TLI) {
4880   if (NumNonZero > 4)
4881     return SDValue();
4882
4883   DebugLoc dl = Op.getDebugLoc();
4884   SDValue V(0, 0);
4885   bool First = true;
4886   for (unsigned i = 0; i < 8; ++i) {
4887     bool isNonZero = (NonZeros & (1 << i)) != 0;
4888     if (isNonZero) {
4889       if (First) {
4890         if (NumZero)
4891           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4892         else
4893           V = DAG.getUNDEF(MVT::v8i16);
4894         First = false;
4895       }
4896       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4897                       MVT::v8i16, V, Op.getOperand(i),
4898                       DAG.getIntPtrConstant(i));
4899     }
4900   }
4901
4902   return V;
4903 }
4904
4905 /// getVShift - Return a vector logical shift node.
4906 ///
4907 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4908                          unsigned NumBits, SelectionDAG &DAG,
4909                          const TargetLowering &TLI, DebugLoc dl) {
4910   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4911   EVT ShVT = MVT::v2i64;
4912   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4913   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4914   return DAG.getNode(ISD::BITCAST, dl, VT,
4915                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4916                              DAG.getConstant(NumBits,
4917                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4918 }
4919
4920 SDValue
4921 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4922                                           SelectionDAG &DAG) const {
4923
4924   // Check if the scalar load can be widened into a vector load. And if
4925   // the address is "base + cst" see if the cst can be "absorbed" into
4926   // the shuffle mask.
4927   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4928     SDValue Ptr = LD->getBasePtr();
4929     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4930       return SDValue();
4931     EVT PVT = LD->getValueType(0);
4932     if (PVT != MVT::i32 && PVT != MVT::f32)
4933       return SDValue();
4934
4935     int FI = -1;
4936     int64_t Offset = 0;
4937     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4938       FI = FINode->getIndex();
4939       Offset = 0;
4940     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4941                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4942       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4943       Offset = Ptr.getConstantOperandVal(1);
4944       Ptr = Ptr.getOperand(0);
4945     } else {
4946       return SDValue();
4947     }
4948
4949     // FIXME: 256-bit vector instructions don't require a strict alignment,
4950     // improve this code to support it better.
4951     unsigned RequiredAlign = VT.getSizeInBits()/8;
4952     SDValue Chain = LD->getChain();
4953     // Make sure the stack object alignment is at least 16 or 32.
4954     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4955     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4956       if (MFI->isFixedObjectIndex(FI)) {
4957         // Can't change the alignment. FIXME: It's possible to compute
4958         // the exact stack offset and reference FI + adjust offset instead.
4959         // If someone *really* cares about this. That's the way to implement it.
4960         return SDValue();
4961       } else {
4962         MFI->setObjectAlignment(FI, RequiredAlign);
4963       }
4964     }
4965
4966     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4967     // Ptr + (Offset & ~15).
4968     if (Offset < 0)
4969       return SDValue();
4970     if ((Offset % RequiredAlign) & 3)
4971       return SDValue();
4972     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4973     if (StartOffset)
4974       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4975                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4976
4977     int EltNo = (Offset - StartOffset) >> 2;
4978     int NumElems = VT.getVectorNumElements();
4979
4980     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4981     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4982     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4983                              LD->getPointerInfo().getWithOffset(StartOffset),
4984                              false, false, 0);
4985
4986     // Canonicalize it to a v4i32 or v8i32 shuffle.
4987     SmallVector<int, 8> Mask;
4988     for (int i = 0; i < NumElems; ++i)
4989       Mask.push_back(EltNo);
4990
4991     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4992     return DAG.getNode(ISD::BITCAST, dl, NVT,
4993                        DAG.getVectorShuffle(CanonVT, dl, V1,
4994                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4995   }
4996
4997   return SDValue();
4998 }
4999
5000 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5001 /// vector of type 'VT', see if the elements can be replaced by a single large
5002 /// load which has the same value as a build_vector whose operands are 'elts'.
5003 ///
5004 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5005 ///
5006 /// FIXME: we'd also like to handle the case where the last elements are zero
5007 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5008 /// There's even a handy isZeroNode for that purpose.
5009 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5010                                         DebugLoc &DL, SelectionDAG &DAG) {
5011   EVT EltVT = VT.getVectorElementType();
5012   unsigned NumElems = Elts.size();
5013
5014   LoadSDNode *LDBase = NULL;
5015   unsigned LastLoadedElt = -1U;
5016
5017   // For each element in the initializer, see if we've found a load or an undef.
5018   // If we don't find an initial load element, or later load elements are
5019   // non-consecutive, bail out.
5020   for (unsigned i = 0; i < NumElems; ++i) {
5021     SDValue Elt = Elts[i];
5022
5023     if (!Elt.getNode() ||
5024         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5025       return SDValue();
5026     if (!LDBase) {
5027       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5028         return SDValue();
5029       LDBase = cast<LoadSDNode>(Elt.getNode());
5030       LastLoadedElt = i;
5031       continue;
5032     }
5033     if (Elt.getOpcode() == ISD::UNDEF)
5034       continue;
5035
5036     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5037     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5038       return SDValue();
5039     LastLoadedElt = i;
5040   }
5041
5042   // If we have found an entire vector of loads and undefs, then return a large
5043   // load of the entire vector width starting at the base pointer.  If we found
5044   // consecutive loads for the low half, generate a vzext_load node.
5045   if (LastLoadedElt == NumElems - 1) {
5046     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5047       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5048                          LDBase->getPointerInfo(),
5049                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5050     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5051                        LDBase->getPointerInfo(),
5052                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5053                        LDBase->getAlignment());
5054   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5055              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5056     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5057     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5058     SDValue ResNode =
5059         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5060                                 LDBase->getPointerInfo(),
5061                                 LDBase->getAlignment(),
5062                                 false/*isVolatile*/, true/*ReadMem*/,
5063                                 false/*WriteMem*/);
5064     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5065   }
5066   return SDValue();
5067 }
5068
5069 SDValue
5070 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5071   DebugLoc dl = Op.getDebugLoc();
5072
5073   EVT VT = Op.getValueType();
5074   EVT ExtVT = VT.getVectorElementType();
5075   unsigned NumElems = Op.getNumOperands();
5076
5077   // Vectors containing all zeros can be matched by pxor and xorps later
5078   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5079     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5080     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5081     if (Op.getValueType() == MVT::v4i32 ||
5082         Op.getValueType() == MVT::v8i32)
5083       return Op;
5084
5085     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5086   }
5087
5088   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5089   // vectors or broken into v4i32 operations on 256-bit vectors.
5090   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5091     if (Op.getValueType() == MVT::v4i32)
5092       return Op;
5093
5094     return getOnesVector(Op.getValueType(), DAG, dl);
5095   }
5096
5097   unsigned EVTBits = ExtVT.getSizeInBits();
5098
5099   unsigned NumZero  = 0;
5100   unsigned NumNonZero = 0;
5101   unsigned NonZeros = 0;
5102   bool IsAllConstants = true;
5103   SmallSet<SDValue, 8> Values;
5104   for (unsigned i = 0; i < NumElems; ++i) {
5105     SDValue Elt = Op.getOperand(i);
5106     if (Elt.getOpcode() == ISD::UNDEF)
5107       continue;
5108     Values.insert(Elt);
5109     if (Elt.getOpcode() != ISD::Constant &&
5110         Elt.getOpcode() != ISD::ConstantFP)
5111       IsAllConstants = false;
5112     if (X86::isZeroNode(Elt))
5113       NumZero++;
5114     else {
5115       NonZeros |= (1 << i);
5116       NumNonZero++;
5117     }
5118   }
5119
5120   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5121   if (NumNonZero == 0)
5122     return DAG.getUNDEF(VT);
5123
5124   // Special case for single non-zero, non-undef, element.
5125   if (NumNonZero == 1) {
5126     unsigned Idx = CountTrailingZeros_32(NonZeros);
5127     SDValue Item = Op.getOperand(Idx);
5128
5129     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5130     // the value are obviously zero, truncate the value to i32 and do the
5131     // insertion that way.  Only do this if the value is non-constant or if the
5132     // value is a constant being inserted into element 0.  It is cheaper to do
5133     // a constant pool load than it is to do a movd + shuffle.
5134     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5135         (!IsAllConstants || Idx == 0)) {
5136       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5137         // Handle SSE only.
5138         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5139         EVT VecVT = MVT::v4i32;
5140         unsigned VecElts = 4;
5141
5142         // Truncate the value (which may itself be a constant) to i32, and
5143         // convert it to a vector with movd (S2V+shuffle to zero extend).
5144         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5145         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5146         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5147                                            Subtarget->hasXMMInt(), DAG);
5148
5149         // Now we have our 32-bit value zero extended in the low element of
5150         // a vector.  If Idx != 0, swizzle it into place.
5151         if (Idx != 0) {
5152           SmallVector<int, 4> Mask;
5153           Mask.push_back(Idx);
5154           for (unsigned i = 1; i != VecElts; ++i)
5155             Mask.push_back(i);
5156           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5157                                       DAG.getUNDEF(Item.getValueType()),
5158                                       &Mask[0]);
5159         }
5160         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5161       }
5162     }
5163
5164     // If we have a constant or non-constant insertion into the low element of
5165     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5166     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5167     // depending on what the source datatype is.
5168     if (Idx == 0) {
5169       if (NumZero == 0) {
5170         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5171       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5172           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5173         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5174         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5175         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5176                                            DAG);
5177       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5178         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5179         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5180         EVT MiddleVT = MVT::v4i32;
5181         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5182         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5183                                            Subtarget->hasXMMInt(), DAG);
5184         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5185       }
5186     }
5187
5188     // Is it a vector logical left shift?
5189     if (NumElems == 2 && Idx == 1 &&
5190         X86::isZeroNode(Op.getOperand(0)) &&
5191         !X86::isZeroNode(Op.getOperand(1))) {
5192       unsigned NumBits = VT.getSizeInBits();
5193       return getVShift(true, VT,
5194                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5195                                    VT, Op.getOperand(1)),
5196                        NumBits/2, DAG, *this, dl);
5197     }
5198
5199     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5200       return SDValue();
5201
5202     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5203     // is a non-constant being inserted into an element other than the low one,
5204     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5205     // movd/movss) to move this into the low element, then shuffle it into
5206     // place.
5207     if (EVTBits == 32) {
5208       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5209
5210       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5211       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5212                                          Subtarget->hasXMMInt(), DAG);
5213       SmallVector<int, 8> MaskVec;
5214       for (unsigned i = 0; i < NumElems; i++)
5215         MaskVec.push_back(i == Idx ? 0 : 1);
5216       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5217     }
5218   }
5219
5220   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5221   if (Values.size() == 1) {
5222     if (EVTBits == 32) {
5223       // Instead of a shuffle like this:
5224       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5225       // Check if it's possible to issue this instead.
5226       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5227       unsigned Idx = CountTrailingZeros_32(NonZeros);
5228       SDValue Item = Op.getOperand(Idx);
5229       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5230         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5231     }
5232     return SDValue();
5233   }
5234
5235   // A vector full of immediates; various special cases are already
5236   // handled, so this is best done with a single constant-pool load.
5237   if (IsAllConstants)
5238     return SDValue();
5239
5240   // For AVX-length vectors, build the individual 128-bit pieces and use
5241   // shuffles to put them in place.
5242   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5243     SmallVector<SDValue, 32> V;
5244     for (unsigned i = 0; i < NumElems; ++i)
5245       V.push_back(Op.getOperand(i));
5246
5247     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5248
5249     // Build both the lower and upper subvector.
5250     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5251     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5252                                 NumElems/2);
5253
5254     // Recreate the wider vector with the lower and upper part.
5255     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5256                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5257     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5258                               DAG, dl);
5259   }
5260
5261   // Let legalizer expand 2-wide build_vectors.
5262   if (EVTBits == 64) {
5263     if (NumNonZero == 1) {
5264       // One half is zero or undef.
5265       unsigned Idx = CountTrailingZeros_32(NonZeros);
5266       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5267                                  Op.getOperand(Idx));
5268       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5269                                          Subtarget->hasXMMInt(), DAG);
5270     }
5271     return SDValue();
5272   }
5273
5274   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5275   if (EVTBits == 8 && NumElems == 16) {
5276     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5277                                         *this);
5278     if (V.getNode()) return V;
5279   }
5280
5281   if (EVTBits == 16 && NumElems == 8) {
5282     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5283                                       *this);
5284     if (V.getNode()) return V;
5285   }
5286
5287   // If element VT is == 32 bits, turn it into a number of shuffles.
5288   SmallVector<SDValue, 8> V;
5289   V.resize(NumElems);
5290   if (NumElems == 4 && NumZero > 0) {
5291     for (unsigned i = 0; i < 4; ++i) {
5292       bool isZero = !(NonZeros & (1 << i));
5293       if (isZero)
5294         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5295       else
5296         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5297     }
5298
5299     for (unsigned i = 0; i < 2; ++i) {
5300       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5301         default: break;
5302         case 0:
5303           V[i] = V[i*2];  // Must be a zero vector.
5304           break;
5305         case 1:
5306           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5307           break;
5308         case 2:
5309           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5310           break;
5311         case 3:
5312           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5313           break;
5314       }
5315     }
5316
5317     SmallVector<int, 8> MaskVec;
5318     bool Reverse = (NonZeros & 0x3) == 2;
5319     for (unsigned i = 0; i < 2; ++i)
5320       MaskVec.push_back(Reverse ? 1-i : i);
5321     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5322     for (unsigned i = 0; i < 2; ++i)
5323       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5324     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5325   }
5326
5327   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5328     // Check for a build vector of consecutive loads.
5329     for (unsigned i = 0; i < NumElems; ++i)
5330       V[i] = Op.getOperand(i);
5331
5332     // Check for elements which are consecutive loads.
5333     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5334     if (LD.getNode())
5335       return LD;
5336
5337     // For SSE 4.1, use insertps to put the high elements into the low element.
5338     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5339       SDValue Result;
5340       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5341         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5342       else
5343         Result = DAG.getUNDEF(VT);
5344
5345       for (unsigned i = 1; i < NumElems; ++i) {
5346         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5347         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5348                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5349       }
5350       return Result;
5351     }
5352
5353     // Otherwise, expand into a number of unpckl*, start by extending each of
5354     // our (non-undef) elements to the full vector width with the element in the
5355     // bottom slot of the vector (which generates no code for SSE).
5356     for (unsigned i = 0; i < NumElems; ++i) {
5357       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5358         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5359       else
5360         V[i] = DAG.getUNDEF(VT);
5361     }
5362
5363     // Next, we iteratively mix elements, e.g. for v4f32:
5364     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5365     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5366     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5367     unsigned EltStride = NumElems >> 1;
5368     while (EltStride != 0) {
5369       for (unsigned i = 0; i < EltStride; ++i) {
5370         // If V[i+EltStride] is undef and this is the first round of mixing,
5371         // then it is safe to just drop this shuffle: V[i] is already in the
5372         // right place, the one element (since it's the first round) being
5373         // inserted as undef can be dropped.  This isn't safe for successive
5374         // rounds because they will permute elements within both vectors.
5375         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5376             EltStride == NumElems/2)
5377           continue;
5378
5379         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5380       }
5381       EltStride >>= 1;
5382     }
5383     return V[0];
5384   }
5385   return SDValue();
5386 }
5387
5388 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5389 // them in a MMX register.  This is better than doing a stack convert.
5390 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5391   DebugLoc dl = Op.getDebugLoc();
5392   EVT ResVT = Op.getValueType();
5393
5394   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5395          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5396   int Mask[2];
5397   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5398   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5399   InVec = Op.getOperand(1);
5400   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5401     unsigned NumElts = ResVT.getVectorNumElements();
5402     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5403     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5404                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5405   } else {
5406     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5407     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5408     Mask[0] = 0; Mask[1] = 2;
5409     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5410   }
5411   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5412 }
5413
5414 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5415 // to create 256-bit vectors from two other 128-bit ones.
5416 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5417   DebugLoc dl = Op.getDebugLoc();
5418   EVT ResVT = Op.getValueType();
5419
5420   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5421
5422   SDValue V1 = Op.getOperand(0);
5423   SDValue V2 = Op.getOperand(1);
5424   unsigned NumElems = ResVT.getVectorNumElements();
5425
5426   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5427                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5428   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5429                             DAG, dl);
5430 }
5431
5432 SDValue
5433 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5434   EVT ResVT = Op.getValueType();
5435
5436   assert(Op.getNumOperands() == 2);
5437   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5438          "Unsupported CONCAT_VECTORS for value type");
5439
5440   // We support concatenate two MMX registers and place them in a MMX register.
5441   // This is better than doing a stack convert.
5442   if (ResVT.is128BitVector())
5443     return LowerMMXCONCAT_VECTORS(Op, DAG);
5444
5445   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5446   // from two other 128-bit ones.
5447   return LowerAVXCONCAT_VECTORS(Op, DAG);
5448 }
5449
5450 // v8i16 shuffles - Prefer shuffles in the following order:
5451 // 1. [all]   pshuflw, pshufhw, optional move
5452 // 2. [ssse3] 1 x pshufb
5453 // 3. [ssse3] 2 x pshufb + 1 x por
5454 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5455 SDValue
5456 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5457                                             SelectionDAG &DAG) const {
5458   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5459   SDValue V1 = SVOp->getOperand(0);
5460   SDValue V2 = SVOp->getOperand(1);
5461   DebugLoc dl = SVOp->getDebugLoc();
5462   SmallVector<int, 8> MaskVals;
5463
5464   // Determine if more than 1 of the words in each of the low and high quadwords
5465   // of the result come from the same quadword of one of the two inputs.  Undef
5466   // mask values count as coming from any quadword, for better codegen.
5467   unsigned LoQuad[] = { 0, 0, 0, 0 };
5468   unsigned HiQuad[] = { 0, 0, 0, 0 };
5469   BitVector InputQuads(4);
5470   for (unsigned i = 0; i < 8; ++i) {
5471     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5472     int EltIdx = SVOp->getMaskElt(i);
5473     MaskVals.push_back(EltIdx);
5474     if (EltIdx < 0) {
5475       ++Quad[0];
5476       ++Quad[1];
5477       ++Quad[2];
5478       ++Quad[3];
5479       continue;
5480     }
5481     ++Quad[EltIdx / 4];
5482     InputQuads.set(EltIdx / 4);
5483   }
5484
5485   int BestLoQuad = -1;
5486   unsigned MaxQuad = 1;
5487   for (unsigned i = 0; i < 4; ++i) {
5488     if (LoQuad[i] > MaxQuad) {
5489       BestLoQuad = i;
5490       MaxQuad = LoQuad[i];
5491     }
5492   }
5493
5494   int BestHiQuad = -1;
5495   MaxQuad = 1;
5496   for (unsigned i = 0; i < 4; ++i) {
5497     if (HiQuad[i] > MaxQuad) {
5498       BestHiQuad = i;
5499       MaxQuad = HiQuad[i];
5500     }
5501   }
5502
5503   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5504   // of the two input vectors, shuffle them into one input vector so only a
5505   // single pshufb instruction is necessary. If There are more than 2 input
5506   // quads, disable the next transformation since it does not help SSSE3.
5507   bool V1Used = InputQuads[0] || InputQuads[1];
5508   bool V2Used = InputQuads[2] || InputQuads[3];
5509   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5510     if (InputQuads.count() == 2 && V1Used && V2Used) {
5511       BestLoQuad = InputQuads.find_first();
5512       BestHiQuad = InputQuads.find_next(BestLoQuad);
5513     }
5514     if (InputQuads.count() > 2) {
5515       BestLoQuad = -1;
5516       BestHiQuad = -1;
5517     }
5518   }
5519
5520   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5521   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5522   // words from all 4 input quadwords.
5523   SDValue NewV;
5524   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5525     SmallVector<int, 8> MaskV;
5526     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5527     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5528     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5529                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5530                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5531     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5532
5533     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5534     // source words for the shuffle, to aid later transformations.
5535     bool AllWordsInNewV = true;
5536     bool InOrder[2] = { true, true };
5537     for (unsigned i = 0; i != 8; ++i) {
5538       int idx = MaskVals[i];
5539       if (idx != (int)i)
5540         InOrder[i/4] = false;
5541       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5542         continue;
5543       AllWordsInNewV = false;
5544       break;
5545     }
5546
5547     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5548     if (AllWordsInNewV) {
5549       for (int i = 0; i != 8; ++i) {
5550         int idx = MaskVals[i];
5551         if (idx < 0)
5552           continue;
5553         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5554         if ((idx != i) && idx < 4)
5555           pshufhw = false;
5556         if ((idx != i) && idx > 3)
5557           pshuflw = false;
5558       }
5559       V1 = NewV;
5560       V2Used = false;
5561       BestLoQuad = 0;
5562       BestHiQuad = 1;
5563     }
5564
5565     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5566     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5567     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5568       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5569       unsigned TargetMask = 0;
5570       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5571                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5572       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5573                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5574       V1 = NewV.getOperand(0);
5575       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5576     }
5577   }
5578
5579   // If we have SSSE3, and all words of the result are from 1 input vector,
5580   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5581   // is present, fall back to case 4.
5582   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5583     SmallVector<SDValue,16> pshufbMask;
5584
5585     // If we have elements from both input vectors, set the high bit of the
5586     // shuffle mask element to zero out elements that come from V2 in the V1
5587     // mask, and elements that come from V1 in the V2 mask, so that the two
5588     // results can be OR'd together.
5589     bool TwoInputs = V1Used && V2Used;
5590     for (unsigned i = 0; i != 8; ++i) {
5591       int EltIdx = MaskVals[i] * 2;
5592       if (TwoInputs && (EltIdx >= 16)) {
5593         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5594         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5595         continue;
5596       }
5597       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5598       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5599     }
5600     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5601     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5602                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5603                                  MVT::v16i8, &pshufbMask[0], 16));
5604     if (!TwoInputs)
5605       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5606
5607     // Calculate the shuffle mask for the second input, shuffle it, and
5608     // OR it with the first shuffled input.
5609     pshufbMask.clear();
5610     for (unsigned i = 0; i != 8; ++i) {
5611       int EltIdx = MaskVals[i] * 2;
5612       if (EltIdx < 16) {
5613         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5614         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5615         continue;
5616       }
5617       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5618       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5619     }
5620     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5621     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5622                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5623                                  MVT::v16i8, &pshufbMask[0], 16));
5624     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5625     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5626   }
5627
5628   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5629   // and update MaskVals with new element order.
5630   BitVector InOrder(8);
5631   if (BestLoQuad >= 0) {
5632     SmallVector<int, 8> MaskV;
5633     for (int i = 0; i != 4; ++i) {
5634       int idx = MaskVals[i];
5635       if (idx < 0) {
5636         MaskV.push_back(-1);
5637         InOrder.set(i);
5638       } else if ((idx / 4) == BestLoQuad) {
5639         MaskV.push_back(idx & 3);
5640         InOrder.set(i);
5641       } else {
5642         MaskV.push_back(-1);
5643       }
5644     }
5645     for (unsigned i = 4; i != 8; ++i)
5646       MaskV.push_back(i);
5647     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5648                                 &MaskV[0]);
5649
5650     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5651         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5652       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5653                                NewV.getOperand(0),
5654                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5655                                DAG);
5656   }
5657
5658   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5659   // and update MaskVals with the new element order.
5660   if (BestHiQuad >= 0) {
5661     SmallVector<int, 8> MaskV;
5662     for (unsigned i = 0; i != 4; ++i)
5663       MaskV.push_back(i);
5664     for (unsigned i = 4; i != 8; ++i) {
5665       int idx = MaskVals[i];
5666       if (idx < 0) {
5667         MaskV.push_back(-1);
5668         InOrder.set(i);
5669       } else if ((idx / 4) == BestHiQuad) {
5670         MaskV.push_back((idx & 3) + 4);
5671         InOrder.set(i);
5672       } else {
5673         MaskV.push_back(-1);
5674       }
5675     }
5676     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5677                                 &MaskV[0]);
5678
5679     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5680         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5681       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5682                               NewV.getOperand(0),
5683                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5684                               DAG);
5685   }
5686
5687   // In case BestHi & BestLo were both -1, which means each quadword has a word
5688   // from each of the four input quadwords, calculate the InOrder bitvector now
5689   // before falling through to the insert/extract cleanup.
5690   if (BestLoQuad == -1 && BestHiQuad == -1) {
5691     NewV = V1;
5692     for (int i = 0; i != 8; ++i)
5693       if (MaskVals[i] < 0 || MaskVals[i] == i)
5694         InOrder.set(i);
5695   }
5696
5697   // The other elements are put in the right place using pextrw and pinsrw.
5698   for (unsigned i = 0; i != 8; ++i) {
5699     if (InOrder[i])
5700       continue;
5701     int EltIdx = MaskVals[i];
5702     if (EltIdx < 0)
5703       continue;
5704     SDValue ExtOp = (EltIdx < 8)
5705     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5706                   DAG.getIntPtrConstant(EltIdx))
5707     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5708                   DAG.getIntPtrConstant(EltIdx - 8));
5709     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5710                        DAG.getIntPtrConstant(i));
5711   }
5712   return NewV;
5713 }
5714
5715 // v16i8 shuffles - Prefer shuffles in the following order:
5716 // 1. [ssse3] 1 x pshufb
5717 // 2. [ssse3] 2 x pshufb + 1 x por
5718 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5719 static
5720 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5721                                  SelectionDAG &DAG,
5722                                  const X86TargetLowering &TLI) {
5723   SDValue V1 = SVOp->getOperand(0);
5724   SDValue V2 = SVOp->getOperand(1);
5725   DebugLoc dl = SVOp->getDebugLoc();
5726   SmallVector<int, 16> MaskVals;
5727   SVOp->getMask(MaskVals);
5728
5729   // If we have SSSE3, case 1 is generated when all result bytes come from
5730   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5731   // present, fall back to case 3.
5732   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5733   bool V1Only = true;
5734   bool V2Only = true;
5735   for (unsigned i = 0; i < 16; ++i) {
5736     int EltIdx = MaskVals[i];
5737     if (EltIdx < 0)
5738       continue;
5739     if (EltIdx < 16)
5740       V2Only = false;
5741     else
5742       V1Only = false;
5743   }
5744
5745   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5746   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5747     SmallVector<SDValue,16> pshufbMask;
5748
5749     // If all result elements are from one input vector, then only translate
5750     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5751     //
5752     // Otherwise, we have elements from both input vectors, and must zero out
5753     // elements that come from V2 in the first mask, and V1 in the second mask
5754     // so that we can OR them together.
5755     bool TwoInputs = !(V1Only || V2Only);
5756     for (unsigned i = 0; i != 16; ++i) {
5757       int EltIdx = MaskVals[i];
5758       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5759         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5760         continue;
5761       }
5762       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5763     }
5764     // If all the elements are from V2, assign it to V1 and return after
5765     // building the first pshufb.
5766     if (V2Only)
5767       V1 = V2;
5768     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5769                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5770                                  MVT::v16i8, &pshufbMask[0], 16));
5771     if (!TwoInputs)
5772       return V1;
5773
5774     // Calculate the shuffle mask for the second input, shuffle it, and
5775     // OR it with the first shuffled input.
5776     pshufbMask.clear();
5777     for (unsigned i = 0; i != 16; ++i) {
5778       int EltIdx = MaskVals[i];
5779       if (EltIdx < 16) {
5780         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5781         continue;
5782       }
5783       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5784     }
5785     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5786                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5787                                  MVT::v16i8, &pshufbMask[0], 16));
5788     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5789   }
5790
5791   // No SSSE3 - Calculate in place words and then fix all out of place words
5792   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5793   // the 16 different words that comprise the two doublequadword input vectors.
5794   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5795   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5796   SDValue NewV = V2Only ? V2 : V1;
5797   for (int i = 0; i != 8; ++i) {
5798     int Elt0 = MaskVals[i*2];
5799     int Elt1 = MaskVals[i*2+1];
5800
5801     // This word of the result is all undef, skip it.
5802     if (Elt0 < 0 && Elt1 < 0)
5803       continue;
5804
5805     // This word of the result is already in the correct place, skip it.
5806     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5807       continue;
5808     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5809       continue;
5810
5811     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5812     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5813     SDValue InsElt;
5814
5815     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5816     // using a single extract together, load it and store it.
5817     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5818       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5819                            DAG.getIntPtrConstant(Elt1 / 2));
5820       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5821                         DAG.getIntPtrConstant(i));
5822       continue;
5823     }
5824
5825     // If Elt1 is defined, extract it from the appropriate source.  If the
5826     // source byte is not also odd, shift the extracted word left 8 bits
5827     // otherwise clear the bottom 8 bits if we need to do an or.
5828     if (Elt1 >= 0) {
5829       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5830                            DAG.getIntPtrConstant(Elt1 / 2));
5831       if ((Elt1 & 1) == 0)
5832         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5833                              DAG.getConstant(8,
5834                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5835       else if (Elt0 >= 0)
5836         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5837                              DAG.getConstant(0xFF00, MVT::i16));
5838     }
5839     // If Elt0 is defined, extract it from the appropriate source.  If the
5840     // source byte is not also even, shift the extracted word right 8 bits. If
5841     // Elt1 was also defined, OR the extracted values together before
5842     // inserting them in the result.
5843     if (Elt0 >= 0) {
5844       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5845                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5846       if ((Elt0 & 1) != 0)
5847         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5848                               DAG.getConstant(8,
5849                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5850       else if (Elt1 >= 0)
5851         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5852                              DAG.getConstant(0x00FF, MVT::i16));
5853       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5854                          : InsElt0;
5855     }
5856     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5857                        DAG.getIntPtrConstant(i));
5858   }
5859   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5860 }
5861
5862 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5863 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5864 /// done when every pair / quad of shuffle mask elements point to elements in
5865 /// the right sequence. e.g.
5866 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5867 static
5868 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5869                                  SelectionDAG &DAG, DebugLoc dl) {
5870   EVT VT = SVOp->getValueType(0);
5871   SDValue V1 = SVOp->getOperand(0);
5872   SDValue V2 = SVOp->getOperand(1);
5873   unsigned NumElems = VT.getVectorNumElements();
5874   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5875   EVT NewVT;
5876   switch (VT.getSimpleVT().SimpleTy) {
5877   default: assert(false && "Unexpected!");
5878   case MVT::v4f32: NewVT = MVT::v2f64; break;
5879   case MVT::v4i32: NewVT = MVT::v2i64; break;
5880   case MVT::v8i16: NewVT = MVT::v4i32; break;
5881   case MVT::v16i8: NewVT = MVT::v4i32; break;
5882   }
5883
5884   int Scale = NumElems / NewWidth;
5885   SmallVector<int, 8> MaskVec;
5886   for (unsigned i = 0; i < NumElems; i += Scale) {
5887     int StartIdx = -1;
5888     for (int j = 0; j < Scale; ++j) {
5889       int EltIdx = SVOp->getMaskElt(i+j);
5890       if (EltIdx < 0)
5891         continue;
5892       if (StartIdx == -1)
5893         StartIdx = EltIdx - (EltIdx % Scale);
5894       if (EltIdx != StartIdx + j)
5895         return SDValue();
5896     }
5897     if (StartIdx == -1)
5898       MaskVec.push_back(-1);
5899     else
5900       MaskVec.push_back(StartIdx / Scale);
5901   }
5902
5903   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5904   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5905   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5906 }
5907
5908 /// getVZextMovL - Return a zero-extending vector move low node.
5909 ///
5910 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5911                             SDValue SrcOp, SelectionDAG &DAG,
5912                             const X86Subtarget *Subtarget, DebugLoc dl) {
5913   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5914     LoadSDNode *LD = NULL;
5915     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5916       LD = dyn_cast<LoadSDNode>(SrcOp);
5917     if (!LD) {
5918       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5919       // instead.
5920       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5921       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5922           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5923           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5924           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5925         // PR2108
5926         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5927         return DAG.getNode(ISD::BITCAST, dl, VT,
5928                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5929                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5930                                                    OpVT,
5931                                                    SrcOp.getOperand(0)
5932                                                           .getOperand(0))));
5933       }
5934     }
5935   }
5936
5937   return DAG.getNode(ISD::BITCAST, dl, VT,
5938                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5939                                  DAG.getNode(ISD::BITCAST, dl,
5940                                              OpVT, SrcOp)));
5941 }
5942
5943 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5944 /// shuffle node referes to only one lane in the sources.
5945 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5946   EVT VT = SVOp->getValueType(0);
5947   int NumElems = VT.getVectorNumElements();
5948   int HalfSize = NumElems/2;
5949   SmallVector<int, 16> M;
5950   SVOp->getMask(M);
5951   bool MatchA = false, MatchB = false;
5952
5953   for (int l = 0; l < NumElems*2; l += HalfSize) {
5954     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5955       MatchA = true;
5956       break;
5957     }
5958   }
5959
5960   for (int l = 0; l < NumElems*2; l += HalfSize) {
5961     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5962       MatchB = true;
5963       break;
5964     }
5965   }
5966
5967   return MatchA && MatchB;
5968 }
5969
5970 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5971 /// which could not be matched by any known target speficic shuffle
5972 static SDValue
5973 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5974   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5975     // If each half of a vector shuffle node referes to only one lane in the
5976     // source vectors, extract each used 128-bit lane and shuffle them using
5977     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5978     // the work to the legalizer.
5979     DebugLoc dl = SVOp->getDebugLoc();
5980     EVT VT = SVOp->getValueType(0);
5981     int NumElems = VT.getVectorNumElements();
5982     int HalfSize = NumElems/2;
5983
5984     // Extract the reference for each half
5985     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5986     int FstVecOpNum = 0, SndVecOpNum = 0;
5987     for (int i = 0; i < HalfSize; ++i) {
5988       int Elt = SVOp->getMaskElt(i);
5989       if (SVOp->getMaskElt(i) < 0)
5990         continue;
5991       FstVecOpNum = Elt/NumElems;
5992       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5993       break;
5994     }
5995     for (int i = HalfSize; i < NumElems; ++i) {
5996       int Elt = SVOp->getMaskElt(i);
5997       if (SVOp->getMaskElt(i) < 0)
5998         continue;
5999       SndVecOpNum = Elt/NumElems;
6000       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6001       break;
6002     }
6003
6004     // Extract the subvectors
6005     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6006                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6007     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6008                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6009
6010     // Generate 128-bit shuffles
6011     SmallVector<int, 16> MaskV1, MaskV2;
6012     for (int i = 0; i < HalfSize; ++i) {
6013       int Elt = SVOp->getMaskElt(i);
6014       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6015     }
6016     for (int i = HalfSize; i < NumElems; ++i) {
6017       int Elt = SVOp->getMaskElt(i);
6018       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6019     }
6020
6021     EVT NVT = V1.getValueType();
6022     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6023     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6024
6025     // Concatenate the result back
6026     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6027                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6028     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6029                               DAG, dl);
6030   }
6031
6032   return SDValue();
6033 }
6034
6035 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6036 /// 4 elements, and match them with several different shuffle types.
6037 static SDValue
6038 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6039   SDValue V1 = SVOp->getOperand(0);
6040   SDValue V2 = SVOp->getOperand(1);
6041   DebugLoc dl = SVOp->getDebugLoc();
6042   EVT VT = SVOp->getValueType(0);
6043
6044   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6045
6046   SmallVector<std::pair<int, int>, 8> Locs;
6047   Locs.resize(4);
6048   SmallVector<int, 8> Mask1(4U, -1);
6049   SmallVector<int, 8> PermMask;
6050   SVOp->getMask(PermMask);
6051
6052   unsigned NumHi = 0;
6053   unsigned NumLo = 0;
6054   for (unsigned i = 0; i != 4; ++i) {
6055     int Idx = PermMask[i];
6056     if (Idx < 0) {
6057       Locs[i] = std::make_pair(-1, -1);
6058     } else {
6059       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6060       if (Idx < 4) {
6061         Locs[i] = std::make_pair(0, NumLo);
6062         Mask1[NumLo] = Idx;
6063         NumLo++;
6064       } else {
6065         Locs[i] = std::make_pair(1, NumHi);
6066         if (2+NumHi < 4)
6067           Mask1[2+NumHi] = Idx;
6068         NumHi++;
6069       }
6070     }
6071   }
6072
6073   if (NumLo <= 2 && NumHi <= 2) {
6074     // If no more than two elements come from either vector. This can be
6075     // implemented with two shuffles. First shuffle gather the elements.
6076     // The second shuffle, which takes the first shuffle as both of its
6077     // vector operands, put the elements into the right order.
6078     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6079
6080     SmallVector<int, 8> Mask2(4U, -1);
6081
6082     for (unsigned i = 0; i != 4; ++i) {
6083       if (Locs[i].first == -1)
6084         continue;
6085       else {
6086         unsigned Idx = (i < 2) ? 0 : 4;
6087         Idx += Locs[i].first * 2 + Locs[i].second;
6088         Mask2[i] = Idx;
6089       }
6090     }
6091
6092     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6093   } else if (NumLo == 3 || NumHi == 3) {
6094     // Otherwise, we must have three elements from one vector, call it X, and
6095     // one element from the other, call it Y.  First, use a shufps to build an
6096     // intermediate vector with the one element from Y and the element from X
6097     // that will be in the same half in the final destination (the indexes don't
6098     // matter). Then, use a shufps to build the final vector, taking the half
6099     // containing the element from Y from the intermediate, and the other half
6100     // from X.
6101     if (NumHi == 3) {
6102       // Normalize it so the 3 elements come from V1.
6103       CommuteVectorShuffleMask(PermMask, VT);
6104       std::swap(V1, V2);
6105     }
6106
6107     // Find the element from V2.
6108     unsigned HiIndex;
6109     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6110       int Val = PermMask[HiIndex];
6111       if (Val < 0)
6112         continue;
6113       if (Val >= 4)
6114         break;
6115     }
6116
6117     Mask1[0] = PermMask[HiIndex];
6118     Mask1[1] = -1;
6119     Mask1[2] = PermMask[HiIndex^1];
6120     Mask1[3] = -1;
6121     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6122
6123     if (HiIndex >= 2) {
6124       Mask1[0] = PermMask[0];
6125       Mask1[1] = PermMask[1];
6126       Mask1[2] = HiIndex & 1 ? 6 : 4;
6127       Mask1[3] = HiIndex & 1 ? 4 : 6;
6128       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6129     } else {
6130       Mask1[0] = HiIndex & 1 ? 2 : 0;
6131       Mask1[1] = HiIndex & 1 ? 0 : 2;
6132       Mask1[2] = PermMask[2];
6133       Mask1[3] = PermMask[3];
6134       if (Mask1[2] >= 0)
6135         Mask1[2] += 4;
6136       if (Mask1[3] >= 0)
6137         Mask1[3] += 4;
6138       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6139     }
6140   }
6141
6142   // Break it into (shuffle shuffle_hi, shuffle_lo).
6143   Locs.clear();
6144   Locs.resize(4);
6145   SmallVector<int,8> LoMask(4U, -1);
6146   SmallVector<int,8> HiMask(4U, -1);
6147
6148   SmallVector<int,8> *MaskPtr = &LoMask;
6149   unsigned MaskIdx = 0;
6150   unsigned LoIdx = 0;
6151   unsigned HiIdx = 2;
6152   for (unsigned i = 0; i != 4; ++i) {
6153     if (i == 2) {
6154       MaskPtr = &HiMask;
6155       MaskIdx = 1;
6156       LoIdx = 0;
6157       HiIdx = 2;
6158     }
6159     int Idx = PermMask[i];
6160     if (Idx < 0) {
6161       Locs[i] = std::make_pair(-1, -1);
6162     } else if (Idx < 4) {
6163       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6164       (*MaskPtr)[LoIdx] = Idx;
6165       LoIdx++;
6166     } else {
6167       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6168       (*MaskPtr)[HiIdx] = Idx;
6169       HiIdx++;
6170     }
6171   }
6172
6173   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6174   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6175   SmallVector<int, 8> MaskOps;
6176   for (unsigned i = 0; i != 4; ++i) {
6177     if (Locs[i].first == -1) {
6178       MaskOps.push_back(-1);
6179     } else {
6180       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6181       MaskOps.push_back(Idx);
6182     }
6183   }
6184   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6185 }
6186
6187 static bool MayFoldVectorLoad(SDValue V) {
6188   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6189     V = V.getOperand(0);
6190   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6191     V = V.getOperand(0);
6192   if (MayFoldLoad(V))
6193     return true;
6194   return false;
6195 }
6196
6197 // FIXME: the version above should always be used. Since there's
6198 // a bug where several vector shuffles can't be folded because the
6199 // DAG is not updated during lowering and a node claims to have two
6200 // uses while it only has one, use this version, and let isel match
6201 // another instruction if the load really happens to have more than
6202 // one use. Remove this version after this bug get fixed.
6203 // rdar://8434668, PR8156
6204 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6205   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6206     V = V.getOperand(0);
6207   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6208     V = V.getOperand(0);
6209   if (ISD::isNormalLoad(V.getNode()))
6210     return true;
6211   return false;
6212 }
6213
6214 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6215 /// a vector extract, and if both can be later optimized into a single load.
6216 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6217 /// here because otherwise a target specific shuffle node is going to be
6218 /// emitted for this shuffle, and the optimization not done.
6219 /// FIXME: This is probably not the best approach, but fix the problem
6220 /// until the right path is decided.
6221 static
6222 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6223                                          const TargetLowering &TLI) {
6224   EVT VT = V.getValueType();
6225   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6226
6227   // Be sure that the vector shuffle is present in a pattern like this:
6228   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6229   if (!V.hasOneUse())
6230     return false;
6231
6232   SDNode *N = *V.getNode()->use_begin();
6233   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6234     return false;
6235
6236   SDValue EltNo = N->getOperand(1);
6237   if (!isa<ConstantSDNode>(EltNo))
6238     return false;
6239
6240   // If the bit convert changed the number of elements, it is unsafe
6241   // to examine the mask.
6242   bool HasShuffleIntoBitcast = false;
6243   if (V.getOpcode() == ISD::BITCAST) {
6244     EVT SrcVT = V.getOperand(0).getValueType();
6245     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6246       return false;
6247     V = V.getOperand(0);
6248     HasShuffleIntoBitcast = true;
6249   }
6250
6251   // Select the input vector, guarding against out of range extract vector.
6252   unsigned NumElems = VT.getVectorNumElements();
6253   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6254   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6255   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6256
6257   // Skip one more bit_convert if necessary
6258   if (V.getOpcode() == ISD::BITCAST)
6259     V = V.getOperand(0);
6260
6261   if (ISD::isNormalLoad(V.getNode())) {
6262     // Is the original load suitable?
6263     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6264
6265     // FIXME: avoid the multi-use bug that is preventing lots of
6266     // of foldings to be detected, this is still wrong of course, but
6267     // give the temporary desired behavior, and if it happens that
6268     // the load has real more uses, during isel it will not fold, and
6269     // will generate poor code.
6270     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6271       return false;
6272
6273     if (!HasShuffleIntoBitcast)
6274       return true;
6275
6276     // If there's a bitcast before the shuffle, check if the load type and
6277     // alignment is valid.
6278     unsigned Align = LN0->getAlignment();
6279     unsigned NewAlign =
6280       TLI.getTargetData()->getABITypeAlignment(
6281                                     VT.getTypeForEVT(*DAG.getContext()));
6282
6283     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6284       return false;
6285   }
6286
6287   return true;
6288 }
6289
6290 static
6291 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6292   EVT VT = Op.getValueType();
6293
6294   // Canonizalize to v2f64.
6295   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6296   return DAG.getNode(ISD::BITCAST, dl, VT,
6297                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6298                                           V1, DAG));
6299 }
6300
6301 static
6302 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6303                         bool HasXMMInt) {
6304   SDValue V1 = Op.getOperand(0);
6305   SDValue V2 = Op.getOperand(1);
6306   EVT VT = Op.getValueType();
6307
6308   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6309
6310   if (HasXMMInt && VT == MVT::v2f64)
6311     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6312
6313   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6314   return DAG.getNode(ISD::BITCAST, dl, VT,
6315                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6316                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6317                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6318 }
6319
6320 static
6321 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6322   SDValue V1 = Op.getOperand(0);
6323   SDValue V2 = Op.getOperand(1);
6324   EVT VT = Op.getValueType();
6325
6326   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6327          "unsupported shuffle type");
6328
6329   if (V2.getOpcode() == ISD::UNDEF)
6330     V2 = V1;
6331
6332   // v4i32 or v4f32
6333   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6334 }
6335
6336 static inline unsigned getSHUFPOpcode(EVT VT) {
6337   switch(VT.getSimpleVT().SimpleTy) {
6338   case MVT::v8i32: // Use fp unit for int unpack.
6339   case MVT::v8f32:
6340   case MVT::v4i32: // Use fp unit for int unpack.
6341   case MVT::v4f32: return X86ISD::SHUFPS;
6342   case MVT::v4i64: // Use fp unit for int unpack.
6343   case MVT::v4f64:
6344   case MVT::v2i64: // Use fp unit for int unpack.
6345   case MVT::v2f64: return X86ISD::SHUFPD;
6346   default:
6347     llvm_unreachable("Unknown type for shufp*");
6348   }
6349   return 0;
6350 }
6351
6352 static
6353 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6354   SDValue V1 = Op.getOperand(0);
6355   SDValue V2 = Op.getOperand(1);
6356   EVT VT = Op.getValueType();
6357   unsigned NumElems = VT.getVectorNumElements();
6358
6359   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6360   // operand of these instructions is only memory, so check if there's a
6361   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6362   // same masks.
6363   bool CanFoldLoad = false;
6364
6365   // Trivial case, when V2 comes from a load.
6366   if (MayFoldVectorLoad(V2))
6367     CanFoldLoad = true;
6368
6369   // When V1 is a load, it can be folded later into a store in isel, example:
6370   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6371   //    turns into:
6372   //  (MOVLPSmr addr:$src1, VR128:$src2)
6373   // So, recognize this potential and also use MOVLPS or MOVLPD
6374   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6375     CanFoldLoad = true;
6376
6377   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6378
6379   // Both of them can't be memory operations though.
6380   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6381     CanFoldLoad = false;
6382
6383   if (CanFoldLoad) {
6384     if (HasXMMInt && NumElems == 2)
6385       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6386
6387     if (NumElems == 4)
6388       // If we don't care about the second element, procede to use movss.
6389       if (SVOp->getMaskElt(1) != -1)
6390         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6391   }
6392
6393   // movl and movlp will both match v2i64, but v2i64 is never matched by
6394   // movl earlier because we make it strict to avoid messing with the movlp load
6395   // folding logic (see the code above getMOVLP call). Match it here then,
6396   // this is horrible, but will stay like this until we move all shuffle
6397   // matching to x86 specific nodes. Note that for the 1st condition all
6398   // types are matched with movsd.
6399   if (HasXMMInt) {
6400     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6401     // as to remove this logic from here, as much as possible
6402     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6403       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6404     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6405   }
6406
6407   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6408
6409   // Invert the operand order and use SHUFPS to match it.
6410   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6411                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6412 }
6413
6414 static inline unsigned getUNPCKLOpcode(EVT VT) {
6415   switch(VT.getSimpleVT().SimpleTy) {
6416   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6417   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6418   case MVT::v4f32: return X86ISD::UNPCKLPS;
6419   case MVT::v2f64: return X86ISD::UNPCKLPD;
6420   case MVT::v8i32: // Use fp unit for int unpack.
6421   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6422   case MVT::v4i64: // Use fp unit for int unpack.
6423   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6424   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6425   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6426   default:
6427     llvm_unreachable("Unknown type for unpckl");
6428   }
6429   return 0;
6430 }
6431
6432 static inline unsigned getUNPCKHOpcode(EVT VT) {
6433   switch(VT.getSimpleVT().SimpleTy) {
6434   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6435   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6436   case MVT::v4f32: return X86ISD::UNPCKHPS;
6437   case MVT::v2f64: return X86ISD::UNPCKHPD;
6438   case MVT::v8i32: // Use fp unit for int unpack.
6439   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6440   case MVT::v4i64: // Use fp unit for int unpack.
6441   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6442   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6443   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6444   default:
6445     llvm_unreachable("Unknown type for unpckh");
6446   }
6447   return 0;
6448 }
6449
6450 static inline unsigned getVPERMILOpcode(EVT VT) {
6451   switch(VT.getSimpleVT().SimpleTy) {
6452   case MVT::v4i32:
6453   case MVT::v4f32: return X86ISD::VPERMILPS;
6454   case MVT::v2i64:
6455   case MVT::v2f64: return X86ISD::VPERMILPD;
6456   case MVT::v8i32:
6457   case MVT::v8f32: return X86ISD::VPERMILPSY;
6458   case MVT::v4i64:
6459   case MVT::v4f64: return X86ISD::VPERMILPDY;
6460   default:
6461     llvm_unreachable("Unknown type for vpermil");
6462   }
6463   return 0;
6464 }
6465
6466 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6467 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6468 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6469 static bool isVectorBroadcast(SDValue &Op) {
6470   EVT VT = Op.getValueType();
6471   bool Is256 = VT.getSizeInBits() == 256;
6472
6473   assert((VT.getSizeInBits() == 128 || Is256) &&
6474          "Unsupported type for vbroadcast node");
6475
6476   SDValue V = Op;
6477   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6478     V = V.getOperand(0);
6479
6480   if (Is256 && !(V.hasOneUse() &&
6481                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6482                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6483     return false;
6484
6485   if (Is256)
6486     V = V.getOperand(1);
6487
6488   if (!V.hasOneUse())
6489     return false;
6490
6491   // Check the source scalar_to_vector type. 256-bit broadcasts are
6492   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6493   // for 32-bit scalars.
6494   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6495     return false;
6496
6497   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6498   if (ScalarSize != 32 && ScalarSize != 64)
6499     return false;
6500   if (!Is256 && ScalarSize == 64)
6501     return false;
6502
6503   V = V.getOperand(0);
6504   if (!MayFoldLoad(V))
6505     return false;
6506
6507   // Return the load node
6508   Op = V;
6509   return true;
6510 }
6511
6512 static
6513 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6514                                const TargetLowering &TLI,
6515                                const X86Subtarget *Subtarget) {
6516   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6517   EVT VT = Op.getValueType();
6518   DebugLoc dl = Op.getDebugLoc();
6519   SDValue V1 = Op.getOperand(0);
6520   SDValue V2 = Op.getOperand(1);
6521
6522   if (isZeroShuffle(SVOp))
6523     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6524
6525   // Handle splat operations
6526   if (SVOp->isSplat()) {
6527     unsigned NumElem = VT.getVectorNumElements();
6528     int Size = VT.getSizeInBits();
6529     // Special case, this is the only place now where it's allowed to return
6530     // a vector_shuffle operation without using a target specific node, because
6531     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6532     // this be moved to DAGCombine instead?
6533     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6534       return Op;
6535
6536     // Use vbroadcast whenever the splat comes from a foldable load
6537     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6538       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6539
6540     // Handle splats by matching through known shuffle masks
6541     if ((Size == 128 && NumElem <= 4) ||
6542         (Size == 256 && NumElem < 8))
6543       return SDValue();
6544
6545     // All remaning splats are promoted to target supported vector shuffles.
6546     return PromoteSplat(SVOp, DAG);
6547   }
6548
6549   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6550   // do it!
6551   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6552     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6553     if (NewOp.getNode())
6554       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6555   } else if ((VT == MVT::v4i32 ||
6556              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6557     // FIXME: Figure out a cleaner way to do this.
6558     // Try to make use of movq to zero out the top part.
6559     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6560       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6561       if (NewOp.getNode()) {
6562         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6563           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6564                               DAG, Subtarget, dl);
6565       }
6566     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6567       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6568       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6569         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6570                             DAG, Subtarget, dl);
6571     }
6572   }
6573   return SDValue();
6574 }
6575
6576 SDValue
6577 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6578   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6579   SDValue V1 = Op.getOperand(0);
6580   SDValue V2 = Op.getOperand(1);
6581   EVT VT = Op.getValueType();
6582   DebugLoc dl = Op.getDebugLoc();
6583   unsigned NumElems = VT.getVectorNumElements();
6584   bool isMMX = VT.getSizeInBits() == 64;
6585   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6586   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6587   bool V1IsSplat = false;
6588   bool V2IsSplat = false;
6589   bool HasXMMInt = Subtarget->hasXMMInt();
6590   MachineFunction &MF = DAG.getMachineFunction();
6591   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6592
6593   // Shuffle operations on MMX not supported.
6594   if (isMMX)
6595     return Op;
6596
6597   // Vector shuffle lowering takes 3 steps:
6598   //
6599   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6600   //    narrowing and commutation of operands should be handled.
6601   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6602   //    shuffle nodes.
6603   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6604   //    so the shuffle can be broken into other shuffles and the legalizer can
6605   //    try the lowering again.
6606   //
6607   // The general ideia is that no vector_shuffle operation should be left to
6608   // be matched during isel, all of them must be converted to a target specific
6609   // node here.
6610
6611   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6612   // narrowing and commutation of operands should be handled. The actual code
6613   // doesn't include all of those, work in progress...
6614   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6615   if (NewOp.getNode())
6616     return NewOp;
6617
6618   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6619   // unpckh_undef). Only use pshufd if speed is more important than size.
6620   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6621     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6622   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6623     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6624
6625   if (X86::isMOVDDUPMask(SVOp) &&
6626       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6627       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6628     return getMOVDDup(Op, dl, V1, DAG);
6629
6630   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6631     return getMOVHighToLow(Op, dl, DAG);
6632
6633   // Use to match splats
6634   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6635       (VT == MVT::v2f64 || VT == MVT::v2i64))
6636     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6637
6638   if (X86::isPSHUFDMask(SVOp)) {
6639     // The actual implementation will match the mask in the if above and then
6640     // during isel it can match several different instructions, not only pshufd
6641     // as its name says, sad but true, emulate the behavior for now...
6642     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6643         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6644
6645     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6646
6647     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6648       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6649
6650     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6651                                 TargetMask, DAG);
6652   }
6653
6654   // Check if this can be converted into a logical shift.
6655   bool isLeft = false;
6656   unsigned ShAmt = 0;
6657   SDValue ShVal;
6658   bool isShift = getSubtarget()->hasXMMInt() &&
6659                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6660   if (isShift && ShVal.hasOneUse()) {
6661     // If the shifted value has multiple uses, it may be cheaper to use
6662     // v_set0 + movlhps or movhlps, etc.
6663     EVT EltVT = VT.getVectorElementType();
6664     ShAmt *= EltVT.getSizeInBits();
6665     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6666   }
6667
6668   if (X86::isMOVLMask(SVOp)) {
6669     if (V1IsUndef)
6670       return V2;
6671     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6672       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6673     if (!X86::isMOVLPMask(SVOp)) {
6674       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6675         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6676
6677       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6678         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6679     }
6680   }
6681
6682   // FIXME: fold these into legal mask.
6683   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6684     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6685
6686   if (X86::isMOVHLPSMask(SVOp))
6687     return getMOVHighToLow(Op, dl, DAG);
6688
6689   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6690     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6691
6692   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6693     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6694
6695   if (X86::isMOVLPMask(SVOp))
6696     return getMOVLP(Op, dl, DAG, HasXMMInt);
6697
6698   if (ShouldXformToMOVHLPS(SVOp) ||
6699       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6700     return CommuteVectorShuffle(SVOp, DAG);
6701
6702   if (isShift) {
6703     // No better options. Use a vshl / vsrl.
6704     EVT EltVT = VT.getVectorElementType();
6705     ShAmt *= EltVT.getSizeInBits();
6706     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6707   }
6708
6709   bool Commuted = false;
6710   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6711   // 1,1,1,1 -> v8i16 though.
6712   V1IsSplat = isSplatVector(V1.getNode());
6713   V2IsSplat = isSplatVector(V2.getNode());
6714
6715   // Canonicalize the splat or undef, if present, to be on the RHS.
6716   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6717     Op = CommuteVectorShuffle(SVOp, DAG);
6718     SVOp = cast<ShuffleVectorSDNode>(Op);
6719     V1 = SVOp->getOperand(0);
6720     V2 = SVOp->getOperand(1);
6721     std::swap(V1IsSplat, V2IsSplat);
6722     std::swap(V1IsUndef, V2IsUndef);
6723     Commuted = true;
6724   }
6725
6726   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6727     // Shuffling low element of v1 into undef, just return v1.
6728     if (V2IsUndef)
6729       return V1;
6730     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6731     // the instruction selector will not match, so get a canonical MOVL with
6732     // swapped operands to undo the commute.
6733     return getMOVL(DAG, dl, VT, V2, V1);
6734   }
6735
6736   if (X86::isUNPCKLMask(SVOp))
6737     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6738
6739   if (X86::isUNPCKHMask(SVOp))
6740     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6741
6742   if (V2IsSplat) {
6743     // Normalize mask so all entries that point to V2 points to its first
6744     // element then try to match unpck{h|l} again. If match, return a
6745     // new vector_shuffle with the corrected mask.
6746     SDValue NewMask = NormalizeMask(SVOp, DAG);
6747     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6748     if (NSVOp != SVOp) {
6749       if (X86::isUNPCKLMask(NSVOp, true)) {
6750         return NewMask;
6751       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6752         return NewMask;
6753       }
6754     }
6755   }
6756
6757   if (Commuted) {
6758     // Commute is back and try unpck* again.
6759     // FIXME: this seems wrong.
6760     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6761     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6762
6763     if (X86::isUNPCKLMask(NewSVOp))
6764       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6765
6766     if (X86::isUNPCKHMask(NewSVOp))
6767       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6768   }
6769
6770   // Normalize the node to match x86 shuffle ops if needed
6771   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6772     return CommuteVectorShuffle(SVOp, DAG);
6773
6774   // The checks below are all present in isShuffleMaskLegal, but they are
6775   // inlined here right now to enable us to directly emit target specific
6776   // nodes, and remove one by one until they don't return Op anymore.
6777   SmallVector<int, 16> M;
6778   SVOp->getMask(M);
6779
6780   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6781     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6782                                 X86::getShufflePALIGNRImmediate(SVOp),
6783                                 DAG);
6784
6785   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6786       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6787     if (VT == MVT::v2f64)
6788       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6789     if (VT == MVT::v2i64)
6790       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6791   }
6792
6793   if (isPSHUFHWMask(M, VT))
6794     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6795                                 X86::getShufflePSHUFHWImmediate(SVOp),
6796                                 DAG);
6797
6798   if (isPSHUFLWMask(M, VT))
6799     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6800                                 X86::getShufflePSHUFLWImmediate(SVOp),
6801                                 DAG);
6802
6803   if (isSHUFPMask(M, VT))
6804     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6805                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6806
6807   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6808     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6809   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6810     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6811
6812   //===--------------------------------------------------------------------===//
6813   // Generate target specific nodes for 128 or 256-bit shuffles only
6814   // supported in the AVX instruction set.
6815   //
6816
6817   // Handle VMOVDDUPY permutations
6818   if (isMOVDDUPYMask(SVOp, Subtarget))
6819     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6820
6821   // Handle VPERMILPS* permutations
6822   if (isVPERMILPSMask(M, VT, Subtarget))
6823     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6824                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6825
6826   // Handle VPERMILPD* permutations
6827   if (isVPERMILPDMask(M, VT, Subtarget))
6828     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6829                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6830
6831   // Handle VPERM2F128 permutations
6832   if (isVPERM2F128Mask(M, VT, Subtarget))
6833     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6834                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6835
6836   // Handle VSHUFPSY permutations
6837   if (isVSHUFPSYMask(M, VT, Subtarget))
6838     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6839                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6840
6841   // Handle VSHUFPDY permutations
6842   if (isVSHUFPDYMask(M, VT, Subtarget))
6843     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6844                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6845
6846   //===--------------------------------------------------------------------===//
6847   // Since no target specific shuffle was selected for this generic one,
6848   // lower it into other known shuffles. FIXME: this isn't true yet, but
6849   // this is the plan.
6850   //
6851
6852   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6853   if (VT == MVT::v8i16) {
6854     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6855     if (NewOp.getNode())
6856       return NewOp;
6857   }
6858
6859   if (VT == MVT::v16i8) {
6860     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6861     if (NewOp.getNode())
6862       return NewOp;
6863   }
6864
6865   // Handle all 128-bit wide vectors with 4 elements, and match them with
6866   // several different shuffle types.
6867   if (NumElems == 4 && VT.getSizeInBits() == 128)
6868     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6869
6870   // Handle general 256-bit shuffles
6871   if (VT.is256BitVector())
6872     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6873
6874   return SDValue();
6875 }
6876
6877 SDValue
6878 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6879                                                 SelectionDAG &DAG) const {
6880   EVT VT = Op.getValueType();
6881   DebugLoc dl = Op.getDebugLoc();
6882
6883   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6884     return SDValue();
6885
6886   if (VT.getSizeInBits() == 8) {
6887     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6888                                     Op.getOperand(0), Op.getOperand(1));
6889     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6890                                     DAG.getValueType(VT));
6891     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6892   } else if (VT.getSizeInBits() == 16) {
6893     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6894     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6895     if (Idx == 0)
6896       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6897                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6898                                      DAG.getNode(ISD::BITCAST, dl,
6899                                                  MVT::v4i32,
6900                                                  Op.getOperand(0)),
6901                                      Op.getOperand(1)));
6902     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6903                                     Op.getOperand(0), Op.getOperand(1));
6904     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6905                                     DAG.getValueType(VT));
6906     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6907   } else if (VT == MVT::f32) {
6908     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6909     // the result back to FR32 register. It's only worth matching if the
6910     // result has a single use which is a store or a bitcast to i32.  And in
6911     // the case of a store, it's not worth it if the index is a constant 0,
6912     // because a MOVSSmr can be used instead, which is smaller and faster.
6913     if (!Op.hasOneUse())
6914       return SDValue();
6915     SDNode *User = *Op.getNode()->use_begin();
6916     if ((User->getOpcode() != ISD::STORE ||
6917          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6918           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6919         (User->getOpcode() != ISD::BITCAST ||
6920          User->getValueType(0) != MVT::i32))
6921       return SDValue();
6922     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6923                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6924                                               Op.getOperand(0)),
6925                                               Op.getOperand(1));
6926     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6927   } else if (VT == MVT::i32) {
6928     // ExtractPS works with constant index.
6929     if (isa<ConstantSDNode>(Op.getOperand(1)))
6930       return Op;
6931   }
6932   return SDValue();
6933 }
6934
6935
6936 SDValue
6937 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6938                                            SelectionDAG &DAG) const {
6939   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6940     return SDValue();
6941
6942   SDValue Vec = Op.getOperand(0);
6943   EVT VecVT = Vec.getValueType();
6944
6945   // If this is a 256-bit vector result, first extract the 128-bit vector and
6946   // then extract the element from the 128-bit vector.
6947   if (VecVT.getSizeInBits() == 256) {
6948     DebugLoc dl = Op.getNode()->getDebugLoc();
6949     unsigned NumElems = VecVT.getVectorNumElements();
6950     SDValue Idx = Op.getOperand(1);
6951     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6952
6953     // Get the 128-bit vector.
6954     bool Upper = IdxVal >= NumElems/2;
6955     Vec = Extract128BitVector(Vec,
6956                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6957
6958     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6959                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6960   }
6961
6962   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6963
6964   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6965     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6966     if (Res.getNode())
6967       return Res;
6968   }
6969
6970   EVT VT = Op.getValueType();
6971   DebugLoc dl = Op.getDebugLoc();
6972   // TODO: handle v16i8.
6973   if (VT.getSizeInBits() == 16) {
6974     SDValue Vec = Op.getOperand(0);
6975     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6976     if (Idx == 0)
6977       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6978                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6979                                      DAG.getNode(ISD::BITCAST, dl,
6980                                                  MVT::v4i32, Vec),
6981                                      Op.getOperand(1)));
6982     // Transform it so it match pextrw which produces a 32-bit result.
6983     EVT EltVT = MVT::i32;
6984     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6985                                     Op.getOperand(0), Op.getOperand(1));
6986     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6987                                     DAG.getValueType(VT));
6988     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6989   } else if (VT.getSizeInBits() == 32) {
6990     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6991     if (Idx == 0)
6992       return Op;
6993
6994     // SHUFPS the element to the lowest double word, then movss.
6995     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6996     EVT VVT = Op.getOperand(0).getValueType();
6997     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6998                                        DAG.getUNDEF(VVT), Mask);
6999     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7000                        DAG.getIntPtrConstant(0));
7001   } else if (VT.getSizeInBits() == 64) {
7002     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7003     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7004     //        to match extract_elt for f64.
7005     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7006     if (Idx == 0)
7007       return Op;
7008
7009     // UNPCKHPD the element to the lowest double word, then movsd.
7010     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7011     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7012     int Mask[2] = { 1, -1 };
7013     EVT VVT = Op.getOperand(0).getValueType();
7014     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7015                                        DAG.getUNDEF(VVT), Mask);
7016     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7017                        DAG.getIntPtrConstant(0));
7018   }
7019
7020   return SDValue();
7021 }
7022
7023 SDValue
7024 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7025                                                SelectionDAG &DAG) const {
7026   EVT VT = Op.getValueType();
7027   EVT EltVT = VT.getVectorElementType();
7028   DebugLoc dl = Op.getDebugLoc();
7029
7030   SDValue N0 = Op.getOperand(0);
7031   SDValue N1 = Op.getOperand(1);
7032   SDValue N2 = Op.getOperand(2);
7033
7034   if (VT.getSizeInBits() == 256)
7035     return SDValue();
7036
7037   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7038       isa<ConstantSDNode>(N2)) {
7039     unsigned Opc;
7040     if (VT == MVT::v8i16)
7041       Opc = X86ISD::PINSRW;
7042     else if (VT == MVT::v16i8)
7043       Opc = X86ISD::PINSRB;
7044     else
7045       Opc = X86ISD::PINSRB;
7046
7047     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7048     // argument.
7049     if (N1.getValueType() != MVT::i32)
7050       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7051     if (N2.getValueType() != MVT::i32)
7052       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7053     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7054   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7055     // Bits [7:6] of the constant are the source select.  This will always be
7056     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7057     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7058     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7059     // Bits [5:4] of the constant are the destination select.  This is the
7060     //  value of the incoming immediate.
7061     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7062     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7063     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7064     // Create this as a scalar to vector..
7065     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7066     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7067   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7068     // PINSR* works with constant index.
7069     return Op;
7070   }
7071   return SDValue();
7072 }
7073
7074 SDValue
7075 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7076   EVT VT = Op.getValueType();
7077   EVT EltVT = VT.getVectorElementType();
7078
7079   DebugLoc dl = Op.getDebugLoc();
7080   SDValue N0 = Op.getOperand(0);
7081   SDValue N1 = Op.getOperand(1);
7082   SDValue N2 = Op.getOperand(2);
7083
7084   // If this is a 256-bit vector result, first extract the 128-bit vector,
7085   // insert the element into the extracted half and then place it back.
7086   if (VT.getSizeInBits() == 256) {
7087     if (!isa<ConstantSDNode>(N2))
7088       return SDValue();
7089
7090     // Get the desired 128-bit vector half.
7091     unsigned NumElems = VT.getVectorNumElements();
7092     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7093     bool Upper = IdxVal >= NumElems/2;
7094     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7095     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7096
7097     // Insert the element into the desired half.
7098     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7099                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7100
7101     // Insert the changed part back to the 256-bit vector
7102     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7103   }
7104
7105   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7106     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7107
7108   if (EltVT == MVT::i8)
7109     return SDValue();
7110
7111   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7112     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7113     // as its second argument.
7114     if (N1.getValueType() != MVT::i32)
7115       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7116     if (N2.getValueType() != MVT::i32)
7117       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7118     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7119   }
7120   return SDValue();
7121 }
7122
7123 SDValue
7124 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7125   LLVMContext *Context = DAG.getContext();
7126   DebugLoc dl = Op.getDebugLoc();
7127   EVT OpVT = Op.getValueType();
7128
7129   // If this is a 256-bit vector result, first insert into a 128-bit
7130   // vector and then insert into the 256-bit vector.
7131   if (OpVT.getSizeInBits() > 128) {
7132     // Insert into a 128-bit vector.
7133     EVT VT128 = EVT::getVectorVT(*Context,
7134                                  OpVT.getVectorElementType(),
7135                                  OpVT.getVectorNumElements() / 2);
7136
7137     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7138
7139     // Insert the 128-bit vector.
7140     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7141                               DAG.getConstant(0, MVT::i32),
7142                               DAG, dl);
7143   }
7144
7145   if (Op.getValueType() == MVT::v1i64 &&
7146       Op.getOperand(0).getValueType() == MVT::i64)
7147     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7148
7149   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7150   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7151          "Expected an SSE type!");
7152   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7153                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7154 }
7155
7156 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7157 // a simple subregister reference or explicit instructions to grab
7158 // upper bits of a vector.
7159 SDValue
7160 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7161   if (Subtarget->hasAVX()) {
7162     DebugLoc dl = Op.getNode()->getDebugLoc();
7163     SDValue Vec = Op.getNode()->getOperand(0);
7164     SDValue Idx = Op.getNode()->getOperand(1);
7165
7166     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7167         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7168         return Extract128BitVector(Vec, Idx, DAG, dl);
7169     }
7170   }
7171   return SDValue();
7172 }
7173
7174 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7175 // simple superregister reference or explicit instructions to insert
7176 // the upper bits of a vector.
7177 SDValue
7178 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7179   if (Subtarget->hasAVX()) {
7180     DebugLoc dl = Op.getNode()->getDebugLoc();
7181     SDValue Vec = Op.getNode()->getOperand(0);
7182     SDValue SubVec = Op.getNode()->getOperand(1);
7183     SDValue Idx = Op.getNode()->getOperand(2);
7184
7185     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7186         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7187       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7188     }
7189   }
7190   return SDValue();
7191 }
7192
7193 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7194 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7195 // one of the above mentioned nodes. It has to be wrapped because otherwise
7196 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7197 // be used to form addressing mode. These wrapped nodes will be selected
7198 // into MOV32ri.
7199 SDValue
7200 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7201   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7202
7203   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7204   // global base reg.
7205   unsigned char OpFlag = 0;
7206   unsigned WrapperKind = X86ISD::Wrapper;
7207   CodeModel::Model M = getTargetMachine().getCodeModel();
7208
7209   if (Subtarget->isPICStyleRIPRel() &&
7210       (M == CodeModel::Small || M == CodeModel::Kernel))
7211     WrapperKind = X86ISD::WrapperRIP;
7212   else if (Subtarget->isPICStyleGOT())
7213     OpFlag = X86II::MO_GOTOFF;
7214   else if (Subtarget->isPICStyleStubPIC())
7215     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7216
7217   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7218                                              CP->getAlignment(),
7219                                              CP->getOffset(), OpFlag);
7220   DebugLoc DL = CP->getDebugLoc();
7221   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7222   // With PIC, the address is actually $g + Offset.
7223   if (OpFlag) {
7224     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7225                          DAG.getNode(X86ISD::GlobalBaseReg,
7226                                      DebugLoc(), getPointerTy()),
7227                          Result);
7228   }
7229
7230   return Result;
7231 }
7232
7233 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7234   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7235
7236   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7237   // global base reg.
7238   unsigned char OpFlag = 0;
7239   unsigned WrapperKind = X86ISD::Wrapper;
7240   CodeModel::Model M = getTargetMachine().getCodeModel();
7241
7242   if (Subtarget->isPICStyleRIPRel() &&
7243       (M == CodeModel::Small || M == CodeModel::Kernel))
7244     WrapperKind = X86ISD::WrapperRIP;
7245   else if (Subtarget->isPICStyleGOT())
7246     OpFlag = X86II::MO_GOTOFF;
7247   else if (Subtarget->isPICStyleStubPIC())
7248     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7249
7250   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7251                                           OpFlag);
7252   DebugLoc DL = JT->getDebugLoc();
7253   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7254
7255   // With PIC, the address is actually $g + Offset.
7256   if (OpFlag)
7257     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7258                          DAG.getNode(X86ISD::GlobalBaseReg,
7259                                      DebugLoc(), getPointerTy()),
7260                          Result);
7261
7262   return Result;
7263 }
7264
7265 SDValue
7266 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7267   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7268
7269   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7270   // global base reg.
7271   unsigned char OpFlag = 0;
7272   unsigned WrapperKind = X86ISD::Wrapper;
7273   CodeModel::Model M = getTargetMachine().getCodeModel();
7274
7275   if (Subtarget->isPICStyleRIPRel() &&
7276       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7277     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7278       OpFlag = X86II::MO_GOTPCREL;
7279     WrapperKind = X86ISD::WrapperRIP;
7280   } else if (Subtarget->isPICStyleGOT()) {
7281     OpFlag = X86II::MO_GOT;
7282   } else if (Subtarget->isPICStyleStubPIC()) {
7283     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7284   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7285     OpFlag = X86II::MO_DARWIN_NONLAZY;
7286   }
7287
7288   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7289
7290   DebugLoc DL = Op.getDebugLoc();
7291   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7292
7293
7294   // With PIC, the address is actually $g + Offset.
7295   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7296       !Subtarget->is64Bit()) {
7297     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7298                          DAG.getNode(X86ISD::GlobalBaseReg,
7299                                      DebugLoc(), getPointerTy()),
7300                          Result);
7301   }
7302
7303   // For symbols that require a load from a stub to get the address, emit the
7304   // load.
7305   if (isGlobalStubReference(OpFlag))
7306     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7307                          MachinePointerInfo::getGOT(), false, false, 0);
7308
7309   return Result;
7310 }
7311
7312 SDValue
7313 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7314   // Create the TargetBlockAddressAddress node.
7315   unsigned char OpFlags =
7316     Subtarget->ClassifyBlockAddressReference();
7317   CodeModel::Model M = getTargetMachine().getCodeModel();
7318   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7319   DebugLoc dl = Op.getDebugLoc();
7320   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7321                                        /*isTarget=*/true, OpFlags);
7322
7323   if (Subtarget->isPICStyleRIPRel() &&
7324       (M == CodeModel::Small || M == CodeModel::Kernel))
7325     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7326   else
7327     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7328
7329   // With PIC, the address is actually $g + Offset.
7330   if (isGlobalRelativeToPICBase(OpFlags)) {
7331     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7332                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7333                          Result);
7334   }
7335
7336   return Result;
7337 }
7338
7339 SDValue
7340 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7341                                       int64_t Offset,
7342                                       SelectionDAG &DAG) const {
7343   // Create the TargetGlobalAddress node, folding in the constant
7344   // offset if it is legal.
7345   unsigned char OpFlags =
7346     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7347   CodeModel::Model M = getTargetMachine().getCodeModel();
7348   SDValue Result;
7349   if (OpFlags == X86II::MO_NO_FLAG &&
7350       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7351     // A direct static reference to a global.
7352     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7353     Offset = 0;
7354   } else {
7355     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7356   }
7357
7358   if (Subtarget->isPICStyleRIPRel() &&
7359       (M == CodeModel::Small || M == CodeModel::Kernel))
7360     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7361   else
7362     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7363
7364   // With PIC, the address is actually $g + Offset.
7365   if (isGlobalRelativeToPICBase(OpFlags)) {
7366     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7367                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7368                          Result);
7369   }
7370
7371   // For globals that require a load from a stub to get the address, emit the
7372   // load.
7373   if (isGlobalStubReference(OpFlags))
7374     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7375                          MachinePointerInfo::getGOT(), false, false, 0);
7376
7377   // If there was a non-zero offset that we didn't fold, create an explicit
7378   // addition for it.
7379   if (Offset != 0)
7380     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7381                          DAG.getConstant(Offset, getPointerTy()));
7382
7383   return Result;
7384 }
7385
7386 SDValue
7387 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7388   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7389   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7390   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7391 }
7392
7393 static SDValue
7394 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7395            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7396            unsigned char OperandFlags) {
7397   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7398   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7399   DebugLoc dl = GA->getDebugLoc();
7400   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7401                                            GA->getValueType(0),
7402                                            GA->getOffset(),
7403                                            OperandFlags);
7404   if (InFlag) {
7405     SDValue Ops[] = { Chain,  TGA, *InFlag };
7406     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7407   } else {
7408     SDValue Ops[]  = { Chain, TGA };
7409     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7410   }
7411
7412   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7413   MFI->setAdjustsStack(true);
7414
7415   SDValue Flag = Chain.getValue(1);
7416   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7417 }
7418
7419 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7420 static SDValue
7421 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7422                                 const EVT PtrVT) {
7423   SDValue InFlag;
7424   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7425   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7426                                      DAG.getNode(X86ISD::GlobalBaseReg,
7427                                                  DebugLoc(), PtrVT), InFlag);
7428   InFlag = Chain.getValue(1);
7429
7430   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7431 }
7432
7433 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7434 static SDValue
7435 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7436                                 const EVT PtrVT) {
7437   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7438                     X86::RAX, X86II::MO_TLSGD);
7439 }
7440
7441 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7442 // "local exec" model.
7443 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7444                                    const EVT PtrVT, TLSModel::Model model,
7445                                    bool is64Bit) {
7446   DebugLoc dl = GA->getDebugLoc();
7447
7448   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7449   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7450                                                          is64Bit ? 257 : 256));
7451
7452   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7453                                       DAG.getIntPtrConstant(0),
7454                                       MachinePointerInfo(Ptr), false, false, 0);
7455
7456   unsigned char OperandFlags = 0;
7457   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7458   // initialexec.
7459   unsigned WrapperKind = X86ISD::Wrapper;
7460   if (model == TLSModel::LocalExec) {
7461     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7462   } else if (is64Bit) {
7463     assert(model == TLSModel::InitialExec);
7464     OperandFlags = X86II::MO_GOTTPOFF;
7465     WrapperKind = X86ISD::WrapperRIP;
7466   } else {
7467     assert(model == TLSModel::InitialExec);
7468     OperandFlags = X86II::MO_INDNTPOFF;
7469   }
7470
7471   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7472   // exec)
7473   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7474                                            GA->getValueType(0),
7475                                            GA->getOffset(), OperandFlags);
7476   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7477
7478   if (model == TLSModel::InitialExec)
7479     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7480                          MachinePointerInfo::getGOT(), false, false, 0);
7481
7482   // The address of the thread local variable is the add of the thread
7483   // pointer with the offset of the variable.
7484   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7485 }
7486
7487 SDValue
7488 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7489
7490   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7491   const GlobalValue *GV = GA->getGlobal();
7492
7493   if (Subtarget->isTargetELF()) {
7494     // TODO: implement the "local dynamic" model
7495     // TODO: implement the "initial exec"model for pic executables
7496
7497     // If GV is an alias then use the aliasee for determining
7498     // thread-localness.
7499     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7500       GV = GA->resolveAliasedGlobal(false);
7501
7502     TLSModel::Model model
7503       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7504
7505     switch (model) {
7506       case TLSModel::GeneralDynamic:
7507       case TLSModel::LocalDynamic: // not implemented
7508         if (Subtarget->is64Bit())
7509           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7510         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7511
7512       case TLSModel::InitialExec:
7513       case TLSModel::LocalExec:
7514         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7515                                    Subtarget->is64Bit());
7516     }
7517   } else if (Subtarget->isTargetDarwin()) {
7518     // Darwin only has one model of TLS.  Lower to that.
7519     unsigned char OpFlag = 0;
7520     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7521                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7522
7523     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7524     // global base reg.
7525     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7526                   !Subtarget->is64Bit();
7527     if (PIC32)
7528       OpFlag = X86II::MO_TLVP_PIC_BASE;
7529     else
7530       OpFlag = X86II::MO_TLVP;
7531     DebugLoc DL = Op.getDebugLoc();
7532     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7533                                                 GA->getValueType(0),
7534                                                 GA->getOffset(), OpFlag);
7535     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7536
7537     // With PIC32, the address is actually $g + Offset.
7538     if (PIC32)
7539       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7540                            DAG.getNode(X86ISD::GlobalBaseReg,
7541                                        DebugLoc(), getPointerTy()),
7542                            Offset);
7543
7544     // Lowering the machine isd will make sure everything is in the right
7545     // location.
7546     SDValue Chain = DAG.getEntryNode();
7547     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7548     SDValue Args[] = { Chain, Offset };
7549     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7550
7551     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7552     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7553     MFI->setAdjustsStack(true);
7554
7555     // And our return value (tls address) is in the standard call return value
7556     // location.
7557     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7558     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7559                               Chain.getValue(1));
7560   }
7561
7562   assert(false &&
7563          "TLS not implemented for this target.");
7564
7565   llvm_unreachable("Unreachable");
7566   return SDValue();
7567 }
7568
7569
7570 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7571 /// take a 2 x i32 value to shift plus a shift amount.
7572 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7573   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7574   EVT VT = Op.getValueType();
7575   unsigned VTBits = VT.getSizeInBits();
7576   DebugLoc dl = Op.getDebugLoc();
7577   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7578   SDValue ShOpLo = Op.getOperand(0);
7579   SDValue ShOpHi = Op.getOperand(1);
7580   SDValue ShAmt  = Op.getOperand(2);
7581   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7582                                      DAG.getConstant(VTBits - 1, MVT::i8))
7583                        : DAG.getConstant(0, VT);
7584
7585   SDValue Tmp2, Tmp3;
7586   if (Op.getOpcode() == ISD::SHL_PARTS) {
7587     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7588     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7589   } else {
7590     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7591     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7592   }
7593
7594   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7595                                 DAG.getConstant(VTBits, MVT::i8));
7596   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7597                              AndNode, DAG.getConstant(0, MVT::i8));
7598
7599   SDValue Hi, Lo;
7600   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7601   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7602   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7603
7604   if (Op.getOpcode() == ISD::SHL_PARTS) {
7605     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7606     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7607   } else {
7608     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7609     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7610   }
7611
7612   SDValue Ops[2] = { Lo, Hi };
7613   return DAG.getMergeValues(Ops, 2, dl);
7614 }
7615
7616 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7617                                            SelectionDAG &DAG) const {
7618   EVT SrcVT = Op.getOperand(0).getValueType();
7619
7620   if (SrcVT.isVector())
7621     return SDValue();
7622
7623   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7624          "Unknown SINT_TO_FP to lower!");
7625
7626   // These are really Legal; return the operand so the caller accepts it as
7627   // Legal.
7628   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7629     return Op;
7630   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7631       Subtarget->is64Bit()) {
7632     return Op;
7633   }
7634
7635   DebugLoc dl = Op.getDebugLoc();
7636   unsigned Size = SrcVT.getSizeInBits()/8;
7637   MachineFunction &MF = DAG.getMachineFunction();
7638   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7639   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7640   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7641                                StackSlot,
7642                                MachinePointerInfo::getFixedStack(SSFI),
7643                                false, false, 0);
7644   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7645 }
7646
7647 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7648                                      SDValue StackSlot,
7649                                      SelectionDAG &DAG) const {
7650   // Build the FILD
7651   DebugLoc DL = Op.getDebugLoc();
7652   SDVTList Tys;
7653   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7654   if (useSSE)
7655     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7656   else
7657     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7658
7659   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7660
7661   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7662   MachineMemOperand *MMO;
7663   if (FI) {
7664     int SSFI = FI->getIndex();
7665     MMO =
7666       DAG.getMachineFunction()
7667       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7668                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7669   } else {
7670     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7671     StackSlot = StackSlot.getOperand(1);
7672   }
7673   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7674   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7675                                            X86ISD::FILD, DL,
7676                                            Tys, Ops, array_lengthof(Ops),
7677                                            SrcVT, MMO);
7678
7679   if (useSSE) {
7680     Chain = Result.getValue(1);
7681     SDValue InFlag = Result.getValue(2);
7682
7683     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7684     // shouldn't be necessary except that RFP cannot be live across
7685     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7686     MachineFunction &MF = DAG.getMachineFunction();
7687     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7688     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7689     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7690     Tys = DAG.getVTList(MVT::Other);
7691     SDValue Ops[] = {
7692       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7693     };
7694     MachineMemOperand *MMO =
7695       DAG.getMachineFunction()
7696       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7697                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7698
7699     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7700                                     Ops, array_lengthof(Ops),
7701                                     Op.getValueType(), MMO);
7702     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7703                          MachinePointerInfo::getFixedStack(SSFI),
7704                          false, false, 0);
7705   }
7706
7707   return Result;
7708 }
7709
7710 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7711 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7712                                                SelectionDAG &DAG) const {
7713   // This algorithm is not obvious. Here it is in C code, more or less:
7714   /*
7715     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7716       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7717       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7718
7719       // Copy ints to xmm registers.
7720       __m128i xh = _mm_cvtsi32_si128( hi );
7721       __m128i xl = _mm_cvtsi32_si128( lo );
7722
7723       // Combine into low half of a single xmm register.
7724       __m128i x = _mm_unpacklo_epi32( xh, xl );
7725       __m128d d;
7726       double sd;
7727
7728       // Merge in appropriate exponents to give the integer bits the right
7729       // magnitude.
7730       x = _mm_unpacklo_epi32( x, exp );
7731
7732       // Subtract away the biases to deal with the IEEE-754 double precision
7733       // implicit 1.
7734       d = _mm_sub_pd( (__m128d) x, bias );
7735
7736       // All conversions up to here are exact. The correctly rounded result is
7737       // calculated using the current rounding mode using the following
7738       // horizontal add.
7739       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7740       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7741                                 // store doesn't really need to be here (except
7742                                 // maybe to zero the other double)
7743       return sd;
7744     }
7745   */
7746
7747   DebugLoc dl = Op.getDebugLoc();
7748   LLVMContext *Context = DAG.getContext();
7749
7750   // Build some magic constants.
7751   std::vector<Constant*> CV0;
7752   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7753   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7754   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7755   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7756   Constant *C0 = ConstantVector::get(CV0);
7757   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7758
7759   std::vector<Constant*> CV1;
7760   CV1.push_back(
7761     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7762   CV1.push_back(
7763     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7764   Constant *C1 = ConstantVector::get(CV1);
7765   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7766
7767   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7768                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7769                                         Op.getOperand(0),
7770                                         DAG.getIntPtrConstant(1)));
7771   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7772                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7773                                         Op.getOperand(0),
7774                                         DAG.getIntPtrConstant(0)));
7775   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7776   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7777                               MachinePointerInfo::getConstantPool(),
7778                               false, false, 16);
7779   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7780   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7781   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7782                               MachinePointerInfo::getConstantPool(),
7783                               false, false, 16);
7784   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7785
7786   // Add the halves; easiest way is to swap them into another reg first.
7787   int ShufMask[2] = { 1, -1 };
7788   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7789                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7790   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7791   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7792                      DAG.getIntPtrConstant(0));
7793 }
7794
7795 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7796 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7797                                                SelectionDAG &DAG) const {
7798   DebugLoc dl = Op.getDebugLoc();
7799   // FP constant to bias correct the final result.
7800   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7801                                    MVT::f64);
7802
7803   // Load the 32-bit value into an XMM register.
7804   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7805                              Op.getOperand(0));
7806
7807   // Zero out the upper parts of the register.
7808   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7809                                      DAG);
7810
7811   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7812                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7813                      DAG.getIntPtrConstant(0));
7814
7815   // Or the load with the bias.
7816   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7817                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7818                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7819                                                    MVT::v2f64, Load)),
7820                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7821                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7822                                                    MVT::v2f64, Bias)));
7823   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7824                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7825                    DAG.getIntPtrConstant(0));
7826
7827   // Subtract the bias.
7828   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7829
7830   // Handle final rounding.
7831   EVT DestVT = Op.getValueType();
7832
7833   if (DestVT.bitsLT(MVT::f64)) {
7834     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7835                        DAG.getIntPtrConstant(0));
7836   } else if (DestVT.bitsGT(MVT::f64)) {
7837     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7838   }
7839
7840   // Handle final rounding.
7841   return Sub;
7842 }
7843
7844 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7845                                            SelectionDAG &DAG) const {
7846   SDValue N0 = Op.getOperand(0);
7847   DebugLoc dl = Op.getDebugLoc();
7848
7849   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7850   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7851   // the optimization here.
7852   if (DAG.SignBitIsZero(N0))
7853     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7854
7855   EVT SrcVT = N0.getValueType();
7856   EVT DstVT = Op.getValueType();
7857   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7858     return LowerUINT_TO_FP_i64(Op, DAG);
7859   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7860     return LowerUINT_TO_FP_i32(Op, DAG);
7861
7862   // Make a 64-bit buffer, and use it to build an FILD.
7863   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7864   if (SrcVT == MVT::i32) {
7865     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7866     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7867                                      getPointerTy(), StackSlot, WordOff);
7868     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7869                                   StackSlot, MachinePointerInfo(),
7870                                   false, false, 0);
7871     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7872                                   OffsetSlot, MachinePointerInfo(),
7873                                   false, false, 0);
7874     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7875     return Fild;
7876   }
7877
7878   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7879   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7880                                 StackSlot, MachinePointerInfo(),
7881                                false, false, 0);
7882   // For i64 source, we need to add the appropriate power of 2 if the input
7883   // was negative.  This is the same as the optimization in
7884   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7885   // we must be careful to do the computation in x87 extended precision, not
7886   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7887   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7888   MachineMemOperand *MMO =
7889     DAG.getMachineFunction()
7890     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7891                           MachineMemOperand::MOLoad, 8, 8);
7892
7893   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7894   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7895   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7896                                          MVT::i64, MMO);
7897
7898   APInt FF(32, 0x5F800000ULL);
7899
7900   // Check whether the sign bit is set.
7901   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7902                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7903                                  ISD::SETLT);
7904
7905   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7906   SDValue FudgePtr = DAG.getConstantPool(
7907                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7908                                          getPointerTy());
7909
7910   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7911   SDValue Zero = DAG.getIntPtrConstant(0);
7912   SDValue Four = DAG.getIntPtrConstant(4);
7913   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7914                                Zero, Four);
7915   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7916
7917   // Load the value out, extending it from f32 to f80.
7918   // FIXME: Avoid the extend by constructing the right constant pool?
7919   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7920                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7921                                  MVT::f32, false, false, 4);
7922   // Extend everything to 80 bits to force it to be done on x87.
7923   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7924   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7925 }
7926
7927 std::pair<SDValue,SDValue> X86TargetLowering::
7928 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7929   DebugLoc DL = Op.getDebugLoc();
7930
7931   EVT DstTy = Op.getValueType();
7932
7933   if (!IsSigned) {
7934     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7935     DstTy = MVT::i64;
7936   }
7937
7938   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7939          DstTy.getSimpleVT() >= MVT::i16 &&
7940          "Unknown FP_TO_SINT to lower!");
7941
7942   // These are really Legal.
7943   if (DstTy == MVT::i32 &&
7944       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7945     return std::make_pair(SDValue(), SDValue());
7946   if (Subtarget->is64Bit() &&
7947       DstTy == MVT::i64 &&
7948       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7949     return std::make_pair(SDValue(), SDValue());
7950
7951   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7952   // stack slot.
7953   MachineFunction &MF = DAG.getMachineFunction();
7954   unsigned MemSize = DstTy.getSizeInBits()/8;
7955   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7956   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7957
7958
7959
7960   unsigned Opc;
7961   switch (DstTy.getSimpleVT().SimpleTy) {
7962   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7963   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7964   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7965   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7966   }
7967
7968   SDValue Chain = DAG.getEntryNode();
7969   SDValue Value = Op.getOperand(0);
7970   EVT TheVT = Op.getOperand(0).getValueType();
7971   if (isScalarFPTypeInSSEReg(TheVT)) {
7972     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7973     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7974                          MachinePointerInfo::getFixedStack(SSFI),
7975                          false, false, 0);
7976     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7977     SDValue Ops[] = {
7978       Chain, StackSlot, DAG.getValueType(TheVT)
7979     };
7980
7981     MachineMemOperand *MMO =
7982       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7983                               MachineMemOperand::MOLoad, MemSize, MemSize);
7984     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7985                                     DstTy, MMO);
7986     Chain = Value.getValue(1);
7987     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7988     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7989   }
7990
7991   MachineMemOperand *MMO =
7992     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7993                             MachineMemOperand::MOStore, MemSize, MemSize);
7994
7995   // Build the FP_TO_INT*_IN_MEM
7996   SDValue Ops[] = { Chain, Value, StackSlot };
7997   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7998                                          Ops, 3, DstTy, MMO);
7999
8000   return std::make_pair(FIST, StackSlot);
8001 }
8002
8003 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8004                                            SelectionDAG &DAG) const {
8005   if (Op.getValueType().isVector())
8006     return SDValue();
8007
8008   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8009   SDValue FIST = Vals.first, StackSlot = Vals.second;
8010   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8011   if (FIST.getNode() == 0) return Op;
8012
8013   // Load the result.
8014   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8015                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
8016 }
8017
8018 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8019                                            SelectionDAG &DAG) const {
8020   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8021   SDValue FIST = Vals.first, StackSlot = Vals.second;
8022   assert(FIST.getNode() && "Unexpected failure");
8023
8024   // Load the result.
8025   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8026                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
8027 }
8028
8029 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8030                                      SelectionDAG &DAG) const {
8031   LLVMContext *Context = DAG.getContext();
8032   DebugLoc dl = Op.getDebugLoc();
8033   EVT VT = Op.getValueType();
8034   EVT EltVT = VT;
8035   if (VT.isVector())
8036     EltVT = VT.getVectorElementType();
8037   std::vector<Constant*> CV;
8038   if (EltVT == MVT::f64) {
8039     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8040     CV.push_back(C);
8041     CV.push_back(C);
8042   } else {
8043     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8044     CV.push_back(C);
8045     CV.push_back(C);
8046     CV.push_back(C);
8047     CV.push_back(C);
8048   }
8049   Constant *C = ConstantVector::get(CV);
8050   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8051   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8052                              MachinePointerInfo::getConstantPool(),
8053                              false, false, 16);
8054   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8055 }
8056
8057 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8058   LLVMContext *Context = DAG.getContext();
8059   DebugLoc dl = Op.getDebugLoc();
8060   EVT VT = Op.getValueType();
8061   EVT EltVT = VT;
8062   if (VT.isVector())
8063     EltVT = VT.getVectorElementType();
8064   std::vector<Constant*> CV;
8065   if (EltVT == MVT::f64) {
8066     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8067     CV.push_back(C);
8068     CV.push_back(C);
8069   } else {
8070     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8071     CV.push_back(C);
8072     CV.push_back(C);
8073     CV.push_back(C);
8074     CV.push_back(C);
8075   }
8076   Constant *C = ConstantVector::get(CV);
8077   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8078   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8079                              MachinePointerInfo::getConstantPool(),
8080                              false, false, 16);
8081   if (VT.isVector()) {
8082     return DAG.getNode(ISD::BITCAST, dl, VT,
8083                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8084                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8085                                 Op.getOperand(0)),
8086                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8087   } else {
8088     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8089   }
8090 }
8091
8092 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8093   LLVMContext *Context = DAG.getContext();
8094   SDValue Op0 = Op.getOperand(0);
8095   SDValue Op1 = Op.getOperand(1);
8096   DebugLoc dl = Op.getDebugLoc();
8097   EVT VT = Op.getValueType();
8098   EVT SrcVT = Op1.getValueType();
8099
8100   // If second operand is smaller, extend it first.
8101   if (SrcVT.bitsLT(VT)) {
8102     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8103     SrcVT = VT;
8104   }
8105   // And if it is bigger, shrink it first.
8106   if (SrcVT.bitsGT(VT)) {
8107     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8108     SrcVT = VT;
8109   }
8110
8111   // At this point the operands and the result should have the same
8112   // type, and that won't be f80 since that is not custom lowered.
8113
8114   // First get the sign bit of second operand.
8115   std::vector<Constant*> CV;
8116   if (SrcVT == MVT::f64) {
8117     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8118     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8119   } else {
8120     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8121     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8122     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8123     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8124   }
8125   Constant *C = ConstantVector::get(CV);
8126   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8127   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8128                               MachinePointerInfo::getConstantPool(),
8129                               false, false, 16);
8130   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8131
8132   // Shift sign bit right or left if the two operands have different types.
8133   if (SrcVT.bitsGT(VT)) {
8134     // Op0 is MVT::f32, Op1 is MVT::f64.
8135     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8136     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8137                           DAG.getConstant(32, MVT::i32));
8138     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8139     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8140                           DAG.getIntPtrConstant(0));
8141   }
8142
8143   // Clear first operand sign bit.
8144   CV.clear();
8145   if (VT == MVT::f64) {
8146     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8147     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8148   } else {
8149     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8150     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8151     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8152     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8153   }
8154   C = ConstantVector::get(CV);
8155   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8156   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8157                               MachinePointerInfo::getConstantPool(),
8158                               false, false, 16);
8159   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8160
8161   // Or the value with the sign bit.
8162   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8163 }
8164
8165 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8166   SDValue N0 = Op.getOperand(0);
8167   DebugLoc dl = Op.getDebugLoc();
8168   EVT VT = Op.getValueType();
8169
8170   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8171   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8172                                   DAG.getConstant(1, VT));
8173   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8174 }
8175
8176 /// Emit nodes that will be selected as "test Op0,Op0", or something
8177 /// equivalent.
8178 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8179                                     SelectionDAG &DAG) const {
8180   DebugLoc dl = Op.getDebugLoc();
8181
8182   // CF and OF aren't always set the way we want. Determine which
8183   // of these we need.
8184   bool NeedCF = false;
8185   bool NeedOF = false;
8186   switch (X86CC) {
8187   default: break;
8188   case X86::COND_A: case X86::COND_AE:
8189   case X86::COND_B: case X86::COND_BE:
8190     NeedCF = true;
8191     break;
8192   case X86::COND_G: case X86::COND_GE:
8193   case X86::COND_L: case X86::COND_LE:
8194   case X86::COND_O: case X86::COND_NO:
8195     NeedOF = true;
8196     break;
8197   }
8198
8199   // See if we can use the EFLAGS value from the operand instead of
8200   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8201   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8202   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8203     // Emit a CMP with 0, which is the TEST pattern.
8204     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8205                        DAG.getConstant(0, Op.getValueType()));
8206
8207   unsigned Opcode = 0;
8208   unsigned NumOperands = 0;
8209   switch (Op.getNode()->getOpcode()) {
8210   case ISD::ADD:
8211     // Due to an isel shortcoming, be conservative if this add is likely to be
8212     // selected as part of a load-modify-store instruction. When the root node
8213     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8214     // uses of other nodes in the match, such as the ADD in this case. This
8215     // leads to the ADD being left around and reselected, with the result being
8216     // two adds in the output.  Alas, even if none our users are stores, that
8217     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8218     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8219     // climbing the DAG back to the root, and it doesn't seem to be worth the
8220     // effort.
8221     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8222            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8223       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8224         goto default_case;
8225
8226     if (ConstantSDNode *C =
8227         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8228       // An add of one will be selected as an INC.
8229       if (C->getAPIntValue() == 1) {
8230         Opcode = X86ISD::INC;
8231         NumOperands = 1;
8232         break;
8233       }
8234
8235       // An add of negative one (subtract of one) will be selected as a DEC.
8236       if (C->getAPIntValue().isAllOnesValue()) {
8237         Opcode = X86ISD::DEC;
8238         NumOperands = 1;
8239         break;
8240       }
8241     }
8242
8243     // Otherwise use a regular EFLAGS-setting add.
8244     Opcode = X86ISD::ADD;
8245     NumOperands = 2;
8246     break;
8247   case ISD::AND: {
8248     // If the primary and result isn't used, don't bother using X86ISD::AND,
8249     // because a TEST instruction will be better.
8250     bool NonFlagUse = false;
8251     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8252            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8253       SDNode *User = *UI;
8254       unsigned UOpNo = UI.getOperandNo();
8255       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8256         // Look pass truncate.
8257         UOpNo = User->use_begin().getOperandNo();
8258         User = *User->use_begin();
8259       }
8260
8261       if (User->getOpcode() != ISD::BRCOND &&
8262           User->getOpcode() != ISD::SETCC &&
8263           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8264         NonFlagUse = true;
8265         break;
8266       }
8267     }
8268
8269     if (!NonFlagUse)
8270       break;
8271   }
8272     // FALL THROUGH
8273   case ISD::SUB:
8274   case ISD::OR:
8275   case ISD::XOR:
8276     // Due to the ISEL shortcoming noted above, be conservative if this op is
8277     // likely to be selected as part of a load-modify-store instruction.
8278     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8279            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8280       if (UI->getOpcode() == ISD::STORE)
8281         goto default_case;
8282
8283     // Otherwise use a regular EFLAGS-setting instruction.
8284     switch (Op.getNode()->getOpcode()) {
8285     default: llvm_unreachable("unexpected operator!");
8286     case ISD::SUB: Opcode = X86ISD::SUB; break;
8287     case ISD::OR:  Opcode = X86ISD::OR;  break;
8288     case ISD::XOR: Opcode = X86ISD::XOR; break;
8289     case ISD::AND: Opcode = X86ISD::AND; break;
8290     }
8291
8292     NumOperands = 2;
8293     break;
8294   case X86ISD::ADD:
8295   case X86ISD::SUB:
8296   case X86ISD::INC:
8297   case X86ISD::DEC:
8298   case X86ISD::OR:
8299   case X86ISD::XOR:
8300   case X86ISD::AND:
8301     return SDValue(Op.getNode(), 1);
8302   default:
8303   default_case:
8304     break;
8305   }
8306
8307   if (Opcode == 0)
8308     // Emit a CMP with 0, which is the TEST pattern.
8309     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8310                        DAG.getConstant(0, Op.getValueType()));
8311
8312   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8313   SmallVector<SDValue, 4> Ops;
8314   for (unsigned i = 0; i != NumOperands; ++i)
8315     Ops.push_back(Op.getOperand(i));
8316
8317   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8318   DAG.ReplaceAllUsesWith(Op, New);
8319   return SDValue(New.getNode(), 1);
8320 }
8321
8322 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8323 /// equivalent.
8324 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8325                                    SelectionDAG &DAG) const {
8326   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8327     if (C->getAPIntValue() == 0)
8328       return EmitTest(Op0, X86CC, DAG);
8329
8330   DebugLoc dl = Op0.getDebugLoc();
8331   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8332 }
8333
8334 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8335 /// if it's possible.
8336 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8337                                      DebugLoc dl, SelectionDAG &DAG) const {
8338   SDValue Op0 = And.getOperand(0);
8339   SDValue Op1 = And.getOperand(1);
8340   if (Op0.getOpcode() == ISD::TRUNCATE)
8341     Op0 = Op0.getOperand(0);
8342   if (Op1.getOpcode() == ISD::TRUNCATE)
8343     Op1 = Op1.getOperand(0);
8344
8345   SDValue LHS, RHS;
8346   if (Op1.getOpcode() == ISD::SHL)
8347     std::swap(Op0, Op1);
8348   if (Op0.getOpcode() == ISD::SHL) {
8349     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8350       if (And00C->getZExtValue() == 1) {
8351         // If we looked past a truncate, check that it's only truncating away
8352         // known zeros.
8353         unsigned BitWidth = Op0.getValueSizeInBits();
8354         unsigned AndBitWidth = And.getValueSizeInBits();
8355         if (BitWidth > AndBitWidth) {
8356           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8357           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8358           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8359             return SDValue();
8360         }
8361         LHS = Op1;
8362         RHS = Op0.getOperand(1);
8363       }
8364   } else if (Op1.getOpcode() == ISD::Constant) {
8365     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8366     SDValue AndLHS = Op0;
8367     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8368       LHS = AndLHS.getOperand(0);
8369       RHS = AndLHS.getOperand(1);
8370     }
8371   }
8372
8373   if (LHS.getNode()) {
8374     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8375     // instruction.  Since the shift amount is in-range-or-undefined, we know
8376     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8377     // the encoding for the i16 version is larger than the i32 version.
8378     // Also promote i16 to i32 for performance / code size reason.
8379     if (LHS.getValueType() == MVT::i8 ||
8380         LHS.getValueType() == MVT::i16)
8381       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8382
8383     // If the operand types disagree, extend the shift amount to match.  Since
8384     // BT ignores high bits (like shifts) we can use anyextend.
8385     if (LHS.getValueType() != RHS.getValueType())
8386       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8387
8388     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8389     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8390     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8391                        DAG.getConstant(Cond, MVT::i8), BT);
8392   }
8393
8394   return SDValue();
8395 }
8396
8397 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8398
8399   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8400
8401   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8402   SDValue Op0 = Op.getOperand(0);
8403   SDValue Op1 = Op.getOperand(1);
8404   DebugLoc dl = Op.getDebugLoc();
8405   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8406
8407   // Optimize to BT if possible.
8408   // Lower (X & (1 << N)) == 0 to BT(X, N).
8409   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8410   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8411   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8412       Op1.getOpcode() == ISD::Constant &&
8413       cast<ConstantSDNode>(Op1)->isNullValue() &&
8414       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8415     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8416     if (NewSetCC.getNode())
8417       return NewSetCC;
8418   }
8419
8420   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8421   // these.
8422   if (Op1.getOpcode() == ISD::Constant &&
8423       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8424        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8425       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8426
8427     // If the input is a setcc, then reuse the input setcc or use a new one with
8428     // the inverted condition.
8429     if (Op0.getOpcode() == X86ISD::SETCC) {
8430       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8431       bool Invert = (CC == ISD::SETNE) ^
8432         cast<ConstantSDNode>(Op1)->isNullValue();
8433       if (!Invert) return Op0;
8434
8435       CCode = X86::GetOppositeBranchCondition(CCode);
8436       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8437                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8438     }
8439   }
8440
8441   bool isFP = Op1.getValueType().isFloatingPoint();
8442   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8443   if (X86CC == X86::COND_INVALID)
8444     return SDValue();
8445
8446   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8447   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8448                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8449 }
8450
8451 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8452 // ones, and then concatenate the result back.
8453 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8454   EVT VT = Op.getValueType();
8455
8456   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8457          "Unsupported value type for operation");
8458
8459   int NumElems = VT.getVectorNumElements();
8460   DebugLoc dl = Op.getDebugLoc();
8461   SDValue CC = Op.getOperand(2);
8462   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8463   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8464
8465   // Extract the LHS vectors
8466   SDValue LHS = Op.getOperand(0);
8467   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8468   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8469
8470   // Extract the RHS vectors
8471   SDValue RHS = Op.getOperand(1);
8472   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8473   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8474
8475   // Issue the operation on the smaller types and concatenate the result back
8476   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8477   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8478   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8479                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8480                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8481 }
8482
8483
8484 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8485   SDValue Cond;
8486   SDValue Op0 = Op.getOperand(0);
8487   SDValue Op1 = Op.getOperand(1);
8488   SDValue CC = Op.getOperand(2);
8489   EVT VT = Op.getValueType();
8490   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8491   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8492   DebugLoc dl = Op.getDebugLoc();
8493
8494   if (isFP) {
8495     unsigned SSECC = 8;
8496     EVT EltVT = Op0.getValueType().getVectorElementType();
8497     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8498
8499     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8500     bool Swap = false;
8501
8502     // SSE Condition code mapping:
8503     //  0 - EQ
8504     //  1 - LT
8505     //  2 - LE
8506     //  3 - UNORD
8507     //  4 - NEQ
8508     //  5 - NLT
8509     //  6 - NLE
8510     //  7 - ORD
8511     switch (SetCCOpcode) {
8512     default: break;
8513     case ISD::SETOEQ:
8514     case ISD::SETEQ:  SSECC = 0; break;
8515     case ISD::SETOGT:
8516     case ISD::SETGT: Swap = true; // Fallthrough
8517     case ISD::SETLT:
8518     case ISD::SETOLT: SSECC = 1; break;
8519     case ISD::SETOGE:
8520     case ISD::SETGE: Swap = true; // Fallthrough
8521     case ISD::SETLE:
8522     case ISD::SETOLE: SSECC = 2; break;
8523     case ISD::SETUO:  SSECC = 3; break;
8524     case ISD::SETUNE:
8525     case ISD::SETNE:  SSECC = 4; break;
8526     case ISD::SETULE: Swap = true;
8527     case ISD::SETUGE: SSECC = 5; break;
8528     case ISD::SETULT: Swap = true;
8529     case ISD::SETUGT: SSECC = 6; break;
8530     case ISD::SETO:   SSECC = 7; break;
8531     }
8532     if (Swap)
8533       std::swap(Op0, Op1);
8534
8535     // In the two special cases we can't handle, emit two comparisons.
8536     if (SSECC == 8) {
8537       if (SetCCOpcode == ISD::SETUEQ) {
8538         SDValue UNORD, EQ;
8539         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8540         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8541         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8542       }
8543       else if (SetCCOpcode == ISD::SETONE) {
8544         SDValue ORD, NEQ;
8545         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8546         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8547         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8548       }
8549       llvm_unreachable("Illegal FP comparison");
8550     }
8551     // Handle all other FP comparisons here.
8552     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8553   }
8554
8555   // Break 256-bit integer vector compare into smaller ones.
8556   if (!isFP && VT.getSizeInBits() == 256)
8557     return Lower256IntVSETCC(Op, DAG);
8558
8559   // We are handling one of the integer comparisons here.  Since SSE only has
8560   // GT and EQ comparisons for integer, swapping operands and multiple
8561   // operations may be required for some comparisons.
8562   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8563   bool Swap = false, Invert = false, FlipSigns = false;
8564
8565   switch (VT.getSimpleVT().SimpleTy) {
8566   default: break;
8567   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8568   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8569   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8570   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8571   }
8572
8573   switch (SetCCOpcode) {
8574   default: break;
8575   case ISD::SETNE:  Invert = true;
8576   case ISD::SETEQ:  Opc = EQOpc; break;
8577   case ISD::SETLT:  Swap = true;
8578   case ISD::SETGT:  Opc = GTOpc; break;
8579   case ISD::SETGE:  Swap = true;
8580   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8581   case ISD::SETULT: Swap = true;
8582   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8583   case ISD::SETUGE: Swap = true;
8584   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8585   }
8586   if (Swap)
8587     std::swap(Op0, Op1);
8588
8589   // Check that the operation in question is available (most are plain SSE2,
8590   // but PCMPGTQ and PCMPEQQ have different requirements).
8591   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8592     return SDValue();
8593   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8594     return SDValue();
8595
8596   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8597   // bits of the inputs before performing those operations.
8598   if (FlipSigns) {
8599     EVT EltVT = VT.getVectorElementType();
8600     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8601                                       EltVT);
8602     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8603     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8604                                     SignBits.size());
8605     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8606     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8607   }
8608
8609   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8610
8611   // If the logical-not of the result is required, perform that now.
8612   if (Invert)
8613     Result = DAG.getNOT(dl, Result, VT);
8614
8615   return Result;
8616 }
8617
8618 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8619 static bool isX86LogicalCmp(SDValue Op) {
8620   unsigned Opc = Op.getNode()->getOpcode();
8621   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8622     return true;
8623   if (Op.getResNo() == 1 &&
8624       (Opc == X86ISD::ADD ||
8625        Opc == X86ISD::SUB ||
8626        Opc == X86ISD::ADC ||
8627        Opc == X86ISD::SBB ||
8628        Opc == X86ISD::SMUL ||
8629        Opc == X86ISD::UMUL ||
8630        Opc == X86ISD::INC ||
8631        Opc == X86ISD::DEC ||
8632        Opc == X86ISD::OR ||
8633        Opc == X86ISD::XOR ||
8634        Opc == X86ISD::AND))
8635     return true;
8636
8637   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8638     return true;
8639
8640   return false;
8641 }
8642
8643 static bool isZero(SDValue V) {
8644   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8645   return C && C->isNullValue();
8646 }
8647
8648 static bool isAllOnes(SDValue V) {
8649   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8650   return C && C->isAllOnesValue();
8651 }
8652
8653 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8654   bool addTest = true;
8655   SDValue Cond  = Op.getOperand(0);
8656   SDValue Op1 = Op.getOperand(1);
8657   SDValue Op2 = Op.getOperand(2);
8658   DebugLoc DL = Op.getDebugLoc();
8659   SDValue CC;
8660
8661   if (Cond.getOpcode() == ISD::SETCC) {
8662     SDValue NewCond = LowerSETCC(Cond, DAG);
8663     if (NewCond.getNode())
8664       Cond = NewCond;
8665   }
8666
8667   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8668   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8669   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8670   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8671   if (Cond.getOpcode() == X86ISD::SETCC &&
8672       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8673       isZero(Cond.getOperand(1).getOperand(1))) {
8674     SDValue Cmp = Cond.getOperand(1);
8675
8676     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8677
8678     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8679         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8680       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8681
8682       SDValue CmpOp0 = Cmp.getOperand(0);
8683       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8684                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8685
8686       SDValue Res =   // Res = 0 or -1.
8687         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8688                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8689
8690       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8691         Res = DAG.getNOT(DL, Res, Res.getValueType());
8692
8693       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8694       if (N2C == 0 || !N2C->isNullValue())
8695         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8696       return Res;
8697     }
8698   }
8699
8700   // Look past (and (setcc_carry (cmp ...)), 1).
8701   if (Cond.getOpcode() == ISD::AND &&
8702       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8703     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8704     if (C && C->getAPIntValue() == 1)
8705       Cond = Cond.getOperand(0);
8706   }
8707
8708   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8709   // setting operand in place of the X86ISD::SETCC.
8710   unsigned CondOpcode = Cond.getOpcode();
8711   if (CondOpcode == X86ISD::SETCC ||
8712       CondOpcode == X86ISD::SETCC_CARRY) {
8713     CC = Cond.getOperand(0);
8714
8715     SDValue Cmp = Cond.getOperand(1);
8716     unsigned Opc = Cmp.getOpcode();
8717     EVT VT = Op.getValueType();
8718
8719     bool IllegalFPCMov = false;
8720     if (VT.isFloatingPoint() && !VT.isVector() &&
8721         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8722       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8723
8724     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8725         Opc == X86ISD::BT) { // FIXME
8726       Cond = Cmp;
8727       addTest = false;
8728     }
8729   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8730              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8731              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8732               Cond.getOperand(0).getValueType() != MVT::i8)) {
8733     SDValue LHS = Cond.getOperand(0);
8734     SDValue RHS = Cond.getOperand(1);
8735     unsigned X86Opcode;
8736     unsigned X86Cond;
8737     SDVTList VTs;
8738     switch (CondOpcode) {
8739     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8740     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8741     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8742     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8743     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8744     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8745     default: llvm_unreachable("unexpected overflowing operator");
8746     }
8747     if (CondOpcode == ISD::UMULO)
8748       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8749                           MVT::i32);
8750     else
8751       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8752
8753     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8754
8755     if (CondOpcode == ISD::UMULO)
8756       Cond = X86Op.getValue(2);
8757     else
8758       Cond = X86Op.getValue(1);
8759
8760     CC = DAG.getConstant(X86Cond, MVT::i8);
8761     addTest = false;
8762   }
8763
8764   if (addTest) {
8765     // Look pass the truncate.
8766     if (Cond.getOpcode() == ISD::TRUNCATE)
8767       Cond = Cond.getOperand(0);
8768
8769     // We know the result of AND is compared against zero. Try to match
8770     // it to BT.
8771     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8772       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8773       if (NewSetCC.getNode()) {
8774         CC = NewSetCC.getOperand(0);
8775         Cond = NewSetCC.getOperand(1);
8776         addTest = false;
8777       }
8778     }
8779   }
8780
8781   if (addTest) {
8782     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8783     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8784   }
8785
8786   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8787   // a <  b ?  0 : -1 -> RES = setcc_carry
8788   // a >= b ? -1 :  0 -> RES = setcc_carry
8789   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8790   if (Cond.getOpcode() == X86ISD::CMP) {
8791     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8792
8793     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8794         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8795       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8796                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8797       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8798         return DAG.getNOT(DL, Res, Res.getValueType());
8799       return Res;
8800     }
8801   }
8802
8803   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8804   // condition is true.
8805   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8806   SDValue Ops[] = { Op2, Op1, CC, Cond };
8807   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8808 }
8809
8810 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8811 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8812 // from the AND / OR.
8813 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8814   Opc = Op.getOpcode();
8815   if (Opc != ISD::OR && Opc != ISD::AND)
8816     return false;
8817   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8818           Op.getOperand(0).hasOneUse() &&
8819           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8820           Op.getOperand(1).hasOneUse());
8821 }
8822
8823 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8824 // 1 and that the SETCC node has a single use.
8825 static bool isXor1OfSetCC(SDValue Op) {
8826   if (Op.getOpcode() != ISD::XOR)
8827     return false;
8828   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8829   if (N1C && N1C->getAPIntValue() == 1) {
8830     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8831       Op.getOperand(0).hasOneUse();
8832   }
8833   return false;
8834 }
8835
8836 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8837   bool addTest = true;
8838   SDValue Chain = Op.getOperand(0);
8839   SDValue Cond  = Op.getOperand(1);
8840   SDValue Dest  = Op.getOperand(2);
8841   DebugLoc dl = Op.getDebugLoc();
8842   SDValue CC;
8843   bool Inverted = false;
8844
8845   if (Cond.getOpcode() == ISD::SETCC) {
8846     // Check for setcc([su]{add,sub,mul}o == 0).
8847     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8848         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8849         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8850         Cond.getOperand(0).getResNo() == 1 &&
8851         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8852          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8853          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8854          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8855          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8856          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8857       Inverted = true;
8858       Cond = Cond.getOperand(0);
8859     } else {
8860       SDValue NewCond = LowerSETCC(Cond, DAG);
8861       if (NewCond.getNode())
8862         Cond = NewCond;
8863     }
8864   }
8865 #if 0
8866   // FIXME: LowerXALUO doesn't handle these!!
8867   else if (Cond.getOpcode() == X86ISD::ADD  ||
8868            Cond.getOpcode() == X86ISD::SUB  ||
8869            Cond.getOpcode() == X86ISD::SMUL ||
8870            Cond.getOpcode() == X86ISD::UMUL)
8871     Cond = LowerXALUO(Cond, DAG);
8872 #endif
8873
8874   // Look pass (and (setcc_carry (cmp ...)), 1).
8875   if (Cond.getOpcode() == ISD::AND &&
8876       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8877     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8878     if (C && C->getAPIntValue() == 1)
8879       Cond = Cond.getOperand(0);
8880   }
8881
8882   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8883   // setting operand in place of the X86ISD::SETCC.
8884   unsigned CondOpcode = Cond.getOpcode();
8885   if (CondOpcode == X86ISD::SETCC ||
8886       CondOpcode == X86ISD::SETCC_CARRY) {
8887     CC = Cond.getOperand(0);
8888
8889     SDValue Cmp = Cond.getOperand(1);
8890     unsigned Opc = Cmp.getOpcode();
8891     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8892     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8893       Cond = Cmp;
8894       addTest = false;
8895     } else {
8896       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8897       default: break;
8898       case X86::COND_O:
8899       case X86::COND_B:
8900         // These can only come from an arithmetic instruction with overflow,
8901         // e.g. SADDO, UADDO.
8902         Cond = Cond.getNode()->getOperand(1);
8903         addTest = false;
8904         break;
8905       }
8906     }
8907   }
8908   CondOpcode = Cond.getOpcode();
8909   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8910       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8911       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8912        Cond.getOperand(0).getValueType() != MVT::i8)) {
8913     SDValue LHS = Cond.getOperand(0);
8914     SDValue RHS = Cond.getOperand(1);
8915     unsigned X86Opcode;
8916     unsigned X86Cond;
8917     SDVTList VTs;
8918     switch (CondOpcode) {
8919     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8920     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8921     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8922     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8923     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8924     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8925     default: llvm_unreachable("unexpected overflowing operator");
8926     }
8927     if (Inverted)
8928       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8929     if (CondOpcode == ISD::UMULO)
8930       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8931                           MVT::i32);
8932     else
8933       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8934
8935     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8936
8937     if (CondOpcode == ISD::UMULO)
8938       Cond = X86Op.getValue(2);
8939     else
8940       Cond = X86Op.getValue(1);
8941
8942     CC = DAG.getConstant(X86Cond, MVT::i8);
8943     addTest = false;
8944   } else {
8945     unsigned CondOpc;
8946     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8947       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8948       if (CondOpc == ISD::OR) {
8949         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8950         // two branches instead of an explicit OR instruction with a
8951         // separate test.
8952         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8953             isX86LogicalCmp(Cmp)) {
8954           CC = Cond.getOperand(0).getOperand(0);
8955           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8956                               Chain, Dest, CC, Cmp);
8957           CC = Cond.getOperand(1).getOperand(0);
8958           Cond = Cmp;
8959           addTest = false;
8960         }
8961       } else { // ISD::AND
8962         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8963         // two branches instead of an explicit AND instruction with a
8964         // separate test. However, we only do this if this block doesn't
8965         // have a fall-through edge, because this requires an explicit
8966         // jmp when the condition is false.
8967         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8968             isX86LogicalCmp(Cmp) &&
8969             Op.getNode()->hasOneUse()) {
8970           X86::CondCode CCode =
8971             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8972           CCode = X86::GetOppositeBranchCondition(CCode);
8973           CC = DAG.getConstant(CCode, MVT::i8);
8974           SDNode *User = *Op.getNode()->use_begin();
8975           // Look for an unconditional branch following this conditional branch.
8976           // We need this because we need to reverse the successors in order
8977           // to implement FCMP_OEQ.
8978           if (User->getOpcode() == ISD::BR) {
8979             SDValue FalseBB = User->getOperand(1);
8980             SDNode *NewBR =
8981               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8982             assert(NewBR == User);
8983             (void)NewBR;
8984             Dest = FalseBB;
8985
8986             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8987                                 Chain, Dest, CC, Cmp);
8988             X86::CondCode CCode =
8989               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8990             CCode = X86::GetOppositeBranchCondition(CCode);
8991             CC = DAG.getConstant(CCode, MVT::i8);
8992             Cond = Cmp;
8993             addTest = false;
8994           }
8995         }
8996       }
8997     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8998       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8999       // It should be transformed during dag combiner except when the condition
9000       // is set by a arithmetics with overflow node.
9001       X86::CondCode CCode =
9002         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9003       CCode = X86::GetOppositeBranchCondition(CCode);
9004       CC = DAG.getConstant(CCode, MVT::i8);
9005       Cond = Cond.getOperand(0).getOperand(1);
9006       addTest = false;
9007     } else if (Cond.getOpcode() == ISD::SETCC &&
9008                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9009       // For FCMP_OEQ, we can emit
9010       // two branches instead of an explicit AND instruction with a
9011       // separate test. However, we only do this if this block doesn't
9012       // have a fall-through edge, because this requires an explicit
9013       // jmp when the condition is false.
9014       if (Op.getNode()->hasOneUse()) {
9015         SDNode *User = *Op.getNode()->use_begin();
9016         // Look for an unconditional branch following this conditional branch.
9017         // We need this because we need to reverse the successors in order
9018         // to implement FCMP_OEQ.
9019         if (User->getOpcode() == ISD::BR) {
9020           SDValue FalseBB = User->getOperand(1);
9021           SDNode *NewBR =
9022             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9023           assert(NewBR == User);
9024           (void)NewBR;
9025           Dest = FalseBB;
9026
9027           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9028                                     Cond.getOperand(0), Cond.getOperand(1));
9029           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9030           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9031                               Chain, Dest, CC, Cmp);
9032           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9033           Cond = Cmp;
9034           addTest = false;
9035         }
9036       }
9037     } else if (Cond.getOpcode() == ISD::SETCC &&
9038                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9039       // For FCMP_UNE, we can emit
9040       // two branches instead of an explicit AND instruction with a
9041       // separate test. However, we only do this if this block doesn't
9042       // have a fall-through edge, because this requires an explicit
9043       // jmp when the condition is false.
9044       if (Op.getNode()->hasOneUse()) {
9045         SDNode *User = *Op.getNode()->use_begin();
9046         // Look for an unconditional branch following this conditional branch.
9047         // We need this because we need to reverse the successors in order
9048         // to implement FCMP_UNE.
9049         if (User->getOpcode() == ISD::BR) {
9050           SDValue FalseBB = User->getOperand(1);
9051           SDNode *NewBR =
9052             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9053           assert(NewBR == User);
9054           (void)NewBR;
9055
9056           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9057                                     Cond.getOperand(0), Cond.getOperand(1));
9058           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9059           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9060                               Chain, Dest, CC, Cmp);
9061           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9062           Cond = Cmp;
9063           addTest = false;
9064           Dest = FalseBB;
9065         }
9066       }
9067     }
9068   }
9069
9070   if (addTest) {
9071     // Look pass the truncate.
9072     if (Cond.getOpcode() == ISD::TRUNCATE)
9073       Cond = Cond.getOperand(0);
9074
9075     // We know the result of AND is compared against zero. Try to match
9076     // it to BT.
9077     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9078       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9079       if (NewSetCC.getNode()) {
9080         CC = NewSetCC.getOperand(0);
9081         Cond = NewSetCC.getOperand(1);
9082         addTest = false;
9083       }
9084     }
9085   }
9086
9087   if (addTest) {
9088     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9089     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9090   }
9091   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9092                      Chain, Dest, CC, Cond);
9093 }
9094
9095
9096 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9097 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9098 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9099 // that the guard pages used by the OS virtual memory manager are allocated in
9100 // correct sequence.
9101 SDValue
9102 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9103                                            SelectionDAG &DAG) const {
9104   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9105           EnableSegmentedStacks) &&
9106          "This should be used only on Windows targets or when segmented stacks "
9107          "are being used");
9108   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9109   DebugLoc dl = Op.getDebugLoc();
9110
9111   // Get the inputs.
9112   SDValue Chain = Op.getOperand(0);
9113   SDValue Size  = Op.getOperand(1);
9114   // FIXME: Ensure alignment here
9115
9116   bool Is64Bit = Subtarget->is64Bit();
9117   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9118
9119   if (EnableSegmentedStacks) {
9120     MachineFunction &MF = DAG.getMachineFunction();
9121     MachineRegisterInfo &MRI = MF.getRegInfo();
9122
9123     if (Is64Bit) {
9124       // The 64 bit implementation of segmented stacks needs to clobber both r10
9125       // r11. This makes it impossible to use it along with nested parameters.
9126       const Function *F = MF.getFunction();
9127
9128       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9129            I != E; I++)
9130         if (I->hasNestAttr())
9131           report_fatal_error("Cannot use segmented stacks with functions that "
9132                              "have nested arguments.");
9133     }
9134
9135     const TargetRegisterClass *AddrRegClass =
9136       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9137     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9138     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9139     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9140                                 DAG.getRegister(Vreg, SPTy));
9141     SDValue Ops1[2] = { Value, Chain };
9142     return DAG.getMergeValues(Ops1, 2, dl);
9143   } else {
9144     SDValue Flag;
9145     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9146
9147     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9148     Flag = Chain.getValue(1);
9149     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9150
9151     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9152     Flag = Chain.getValue(1);
9153
9154     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9155
9156     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9157     return DAG.getMergeValues(Ops1, 2, dl);
9158   }
9159 }
9160
9161 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9162   MachineFunction &MF = DAG.getMachineFunction();
9163   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9164
9165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9166   DebugLoc DL = Op.getDebugLoc();
9167
9168   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9169     // vastart just stores the address of the VarArgsFrameIndex slot into the
9170     // memory location argument.
9171     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9172                                    getPointerTy());
9173     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9174                         MachinePointerInfo(SV), false, false, 0);
9175   }
9176
9177   // __va_list_tag:
9178   //   gp_offset         (0 - 6 * 8)
9179   //   fp_offset         (48 - 48 + 8 * 16)
9180   //   overflow_arg_area (point to parameters coming in memory).
9181   //   reg_save_area
9182   SmallVector<SDValue, 8> MemOps;
9183   SDValue FIN = Op.getOperand(1);
9184   // Store gp_offset
9185   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9186                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9187                                                MVT::i32),
9188                                FIN, MachinePointerInfo(SV), false, false, 0);
9189   MemOps.push_back(Store);
9190
9191   // Store fp_offset
9192   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9193                     FIN, DAG.getIntPtrConstant(4));
9194   Store = DAG.getStore(Op.getOperand(0), DL,
9195                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9196                                        MVT::i32),
9197                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9198   MemOps.push_back(Store);
9199
9200   // Store ptr to overflow_arg_area
9201   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9202                     FIN, DAG.getIntPtrConstant(4));
9203   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9204                                     getPointerTy());
9205   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9206                        MachinePointerInfo(SV, 8),
9207                        false, false, 0);
9208   MemOps.push_back(Store);
9209
9210   // Store ptr to reg_save_area.
9211   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9212                     FIN, DAG.getIntPtrConstant(8));
9213   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9214                                     getPointerTy());
9215   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9216                        MachinePointerInfo(SV, 16), false, false, 0);
9217   MemOps.push_back(Store);
9218   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9219                      &MemOps[0], MemOps.size());
9220 }
9221
9222 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9223   assert(Subtarget->is64Bit() &&
9224          "LowerVAARG only handles 64-bit va_arg!");
9225   assert((Subtarget->isTargetLinux() ||
9226           Subtarget->isTargetDarwin()) &&
9227           "Unhandled target in LowerVAARG");
9228   assert(Op.getNode()->getNumOperands() == 4);
9229   SDValue Chain = Op.getOperand(0);
9230   SDValue SrcPtr = Op.getOperand(1);
9231   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9232   unsigned Align = Op.getConstantOperandVal(3);
9233   DebugLoc dl = Op.getDebugLoc();
9234
9235   EVT ArgVT = Op.getNode()->getValueType(0);
9236   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9237   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9238   uint8_t ArgMode;
9239
9240   // Decide which area this value should be read from.
9241   // TODO: Implement the AMD64 ABI in its entirety. This simple
9242   // selection mechanism works only for the basic types.
9243   if (ArgVT == MVT::f80) {
9244     llvm_unreachable("va_arg for f80 not yet implemented");
9245   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9246     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9247   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9248     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9249   } else {
9250     llvm_unreachable("Unhandled argument type in LowerVAARG");
9251   }
9252
9253   if (ArgMode == 2) {
9254     // Sanity Check: Make sure using fp_offset makes sense.
9255     assert(!UseSoftFloat &&
9256            !(DAG.getMachineFunction()
9257                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9258            Subtarget->hasXMM());
9259   }
9260
9261   // Insert VAARG_64 node into the DAG
9262   // VAARG_64 returns two values: Variable Argument Address, Chain
9263   SmallVector<SDValue, 11> InstOps;
9264   InstOps.push_back(Chain);
9265   InstOps.push_back(SrcPtr);
9266   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9267   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9268   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9269   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9270   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9271                                           VTs, &InstOps[0], InstOps.size(),
9272                                           MVT::i64,
9273                                           MachinePointerInfo(SV),
9274                                           /*Align=*/0,
9275                                           /*Volatile=*/false,
9276                                           /*ReadMem=*/true,
9277                                           /*WriteMem=*/true);
9278   Chain = VAARG.getValue(1);
9279
9280   // Load the next argument and return it
9281   return DAG.getLoad(ArgVT, dl,
9282                      Chain,
9283                      VAARG,
9284                      MachinePointerInfo(),
9285                      false, false, 0);
9286 }
9287
9288 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9289   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9290   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9291   SDValue Chain = Op.getOperand(0);
9292   SDValue DstPtr = Op.getOperand(1);
9293   SDValue SrcPtr = Op.getOperand(2);
9294   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9295   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9296   DebugLoc DL = Op.getDebugLoc();
9297
9298   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9299                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9300                        false,
9301                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9302 }
9303
9304 SDValue
9305 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9306   DebugLoc dl = Op.getDebugLoc();
9307   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9308   switch (IntNo) {
9309   default: return SDValue();    // Don't custom lower most intrinsics.
9310   // Comparison intrinsics.
9311   case Intrinsic::x86_sse_comieq_ss:
9312   case Intrinsic::x86_sse_comilt_ss:
9313   case Intrinsic::x86_sse_comile_ss:
9314   case Intrinsic::x86_sse_comigt_ss:
9315   case Intrinsic::x86_sse_comige_ss:
9316   case Intrinsic::x86_sse_comineq_ss:
9317   case Intrinsic::x86_sse_ucomieq_ss:
9318   case Intrinsic::x86_sse_ucomilt_ss:
9319   case Intrinsic::x86_sse_ucomile_ss:
9320   case Intrinsic::x86_sse_ucomigt_ss:
9321   case Intrinsic::x86_sse_ucomige_ss:
9322   case Intrinsic::x86_sse_ucomineq_ss:
9323   case Intrinsic::x86_sse2_comieq_sd:
9324   case Intrinsic::x86_sse2_comilt_sd:
9325   case Intrinsic::x86_sse2_comile_sd:
9326   case Intrinsic::x86_sse2_comigt_sd:
9327   case Intrinsic::x86_sse2_comige_sd:
9328   case Intrinsic::x86_sse2_comineq_sd:
9329   case Intrinsic::x86_sse2_ucomieq_sd:
9330   case Intrinsic::x86_sse2_ucomilt_sd:
9331   case Intrinsic::x86_sse2_ucomile_sd:
9332   case Intrinsic::x86_sse2_ucomigt_sd:
9333   case Intrinsic::x86_sse2_ucomige_sd:
9334   case Intrinsic::x86_sse2_ucomineq_sd: {
9335     unsigned Opc = 0;
9336     ISD::CondCode CC = ISD::SETCC_INVALID;
9337     switch (IntNo) {
9338     default: break;
9339     case Intrinsic::x86_sse_comieq_ss:
9340     case Intrinsic::x86_sse2_comieq_sd:
9341       Opc = X86ISD::COMI;
9342       CC = ISD::SETEQ;
9343       break;
9344     case Intrinsic::x86_sse_comilt_ss:
9345     case Intrinsic::x86_sse2_comilt_sd:
9346       Opc = X86ISD::COMI;
9347       CC = ISD::SETLT;
9348       break;
9349     case Intrinsic::x86_sse_comile_ss:
9350     case Intrinsic::x86_sse2_comile_sd:
9351       Opc = X86ISD::COMI;
9352       CC = ISD::SETLE;
9353       break;
9354     case Intrinsic::x86_sse_comigt_ss:
9355     case Intrinsic::x86_sse2_comigt_sd:
9356       Opc = X86ISD::COMI;
9357       CC = ISD::SETGT;
9358       break;
9359     case Intrinsic::x86_sse_comige_ss:
9360     case Intrinsic::x86_sse2_comige_sd:
9361       Opc = X86ISD::COMI;
9362       CC = ISD::SETGE;
9363       break;
9364     case Intrinsic::x86_sse_comineq_ss:
9365     case Intrinsic::x86_sse2_comineq_sd:
9366       Opc = X86ISD::COMI;
9367       CC = ISD::SETNE;
9368       break;
9369     case Intrinsic::x86_sse_ucomieq_ss:
9370     case Intrinsic::x86_sse2_ucomieq_sd:
9371       Opc = X86ISD::UCOMI;
9372       CC = ISD::SETEQ;
9373       break;
9374     case Intrinsic::x86_sse_ucomilt_ss:
9375     case Intrinsic::x86_sse2_ucomilt_sd:
9376       Opc = X86ISD::UCOMI;
9377       CC = ISD::SETLT;
9378       break;
9379     case Intrinsic::x86_sse_ucomile_ss:
9380     case Intrinsic::x86_sse2_ucomile_sd:
9381       Opc = X86ISD::UCOMI;
9382       CC = ISD::SETLE;
9383       break;
9384     case Intrinsic::x86_sse_ucomigt_ss:
9385     case Intrinsic::x86_sse2_ucomigt_sd:
9386       Opc = X86ISD::UCOMI;
9387       CC = ISD::SETGT;
9388       break;
9389     case Intrinsic::x86_sse_ucomige_ss:
9390     case Intrinsic::x86_sse2_ucomige_sd:
9391       Opc = X86ISD::UCOMI;
9392       CC = ISD::SETGE;
9393       break;
9394     case Intrinsic::x86_sse_ucomineq_ss:
9395     case Intrinsic::x86_sse2_ucomineq_sd:
9396       Opc = X86ISD::UCOMI;
9397       CC = ISD::SETNE;
9398       break;
9399     }
9400
9401     SDValue LHS = Op.getOperand(1);
9402     SDValue RHS = Op.getOperand(2);
9403     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9404     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9405     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9406     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9407                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9408     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9409   }
9410   // Arithmetic intrinsics.
9411   case Intrinsic::x86_sse3_hadd_ps:
9412   case Intrinsic::x86_sse3_hadd_pd:
9413   case Intrinsic::x86_avx_hadd_ps_256:
9414   case Intrinsic::x86_avx_hadd_pd_256:
9415     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9416                        Op.getOperand(1), Op.getOperand(2));
9417   case Intrinsic::x86_sse3_hsub_ps:
9418   case Intrinsic::x86_sse3_hsub_pd:
9419   case Intrinsic::x86_avx_hsub_ps_256:
9420   case Intrinsic::x86_avx_hsub_pd_256:
9421     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9422                        Op.getOperand(1), Op.getOperand(2));
9423   // ptest and testp intrinsics. The intrinsic these come from are designed to
9424   // return an integer value, not just an instruction so lower it to the ptest
9425   // or testp pattern and a setcc for the result.
9426   case Intrinsic::x86_sse41_ptestz:
9427   case Intrinsic::x86_sse41_ptestc:
9428   case Intrinsic::x86_sse41_ptestnzc:
9429   case Intrinsic::x86_avx_ptestz_256:
9430   case Intrinsic::x86_avx_ptestc_256:
9431   case Intrinsic::x86_avx_ptestnzc_256:
9432   case Intrinsic::x86_avx_vtestz_ps:
9433   case Intrinsic::x86_avx_vtestc_ps:
9434   case Intrinsic::x86_avx_vtestnzc_ps:
9435   case Intrinsic::x86_avx_vtestz_pd:
9436   case Intrinsic::x86_avx_vtestc_pd:
9437   case Intrinsic::x86_avx_vtestnzc_pd:
9438   case Intrinsic::x86_avx_vtestz_ps_256:
9439   case Intrinsic::x86_avx_vtestc_ps_256:
9440   case Intrinsic::x86_avx_vtestnzc_ps_256:
9441   case Intrinsic::x86_avx_vtestz_pd_256:
9442   case Intrinsic::x86_avx_vtestc_pd_256:
9443   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9444     bool IsTestPacked = false;
9445     unsigned X86CC = 0;
9446     switch (IntNo) {
9447     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9448     case Intrinsic::x86_avx_vtestz_ps:
9449     case Intrinsic::x86_avx_vtestz_pd:
9450     case Intrinsic::x86_avx_vtestz_ps_256:
9451     case Intrinsic::x86_avx_vtestz_pd_256:
9452       IsTestPacked = true; // Fallthrough
9453     case Intrinsic::x86_sse41_ptestz:
9454     case Intrinsic::x86_avx_ptestz_256:
9455       // ZF = 1
9456       X86CC = X86::COND_E;
9457       break;
9458     case Intrinsic::x86_avx_vtestc_ps:
9459     case Intrinsic::x86_avx_vtestc_pd:
9460     case Intrinsic::x86_avx_vtestc_ps_256:
9461     case Intrinsic::x86_avx_vtestc_pd_256:
9462       IsTestPacked = true; // Fallthrough
9463     case Intrinsic::x86_sse41_ptestc:
9464     case Intrinsic::x86_avx_ptestc_256:
9465       // CF = 1
9466       X86CC = X86::COND_B;
9467       break;
9468     case Intrinsic::x86_avx_vtestnzc_ps:
9469     case Intrinsic::x86_avx_vtestnzc_pd:
9470     case Intrinsic::x86_avx_vtestnzc_ps_256:
9471     case Intrinsic::x86_avx_vtestnzc_pd_256:
9472       IsTestPacked = true; // Fallthrough
9473     case Intrinsic::x86_sse41_ptestnzc:
9474     case Intrinsic::x86_avx_ptestnzc_256:
9475       // ZF and CF = 0
9476       X86CC = X86::COND_A;
9477       break;
9478     }
9479
9480     SDValue LHS = Op.getOperand(1);
9481     SDValue RHS = Op.getOperand(2);
9482     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9483     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9484     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9485     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9486     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9487   }
9488
9489   // Fix vector shift instructions where the last operand is a non-immediate
9490   // i32 value.
9491   case Intrinsic::x86_sse2_pslli_w:
9492   case Intrinsic::x86_sse2_pslli_d:
9493   case Intrinsic::x86_sse2_pslli_q:
9494   case Intrinsic::x86_sse2_psrli_w:
9495   case Intrinsic::x86_sse2_psrli_d:
9496   case Intrinsic::x86_sse2_psrli_q:
9497   case Intrinsic::x86_sse2_psrai_w:
9498   case Intrinsic::x86_sse2_psrai_d:
9499   case Intrinsic::x86_mmx_pslli_w:
9500   case Intrinsic::x86_mmx_pslli_d:
9501   case Intrinsic::x86_mmx_pslli_q:
9502   case Intrinsic::x86_mmx_psrli_w:
9503   case Intrinsic::x86_mmx_psrli_d:
9504   case Intrinsic::x86_mmx_psrli_q:
9505   case Intrinsic::x86_mmx_psrai_w:
9506   case Intrinsic::x86_mmx_psrai_d: {
9507     SDValue ShAmt = Op.getOperand(2);
9508     if (isa<ConstantSDNode>(ShAmt))
9509       return SDValue();
9510
9511     unsigned NewIntNo = 0;
9512     EVT ShAmtVT = MVT::v4i32;
9513     switch (IntNo) {
9514     case Intrinsic::x86_sse2_pslli_w:
9515       NewIntNo = Intrinsic::x86_sse2_psll_w;
9516       break;
9517     case Intrinsic::x86_sse2_pslli_d:
9518       NewIntNo = Intrinsic::x86_sse2_psll_d;
9519       break;
9520     case Intrinsic::x86_sse2_pslli_q:
9521       NewIntNo = Intrinsic::x86_sse2_psll_q;
9522       break;
9523     case Intrinsic::x86_sse2_psrli_w:
9524       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9525       break;
9526     case Intrinsic::x86_sse2_psrli_d:
9527       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9528       break;
9529     case Intrinsic::x86_sse2_psrli_q:
9530       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9531       break;
9532     case Intrinsic::x86_sse2_psrai_w:
9533       NewIntNo = Intrinsic::x86_sse2_psra_w;
9534       break;
9535     case Intrinsic::x86_sse2_psrai_d:
9536       NewIntNo = Intrinsic::x86_sse2_psra_d;
9537       break;
9538     default: {
9539       ShAmtVT = MVT::v2i32;
9540       switch (IntNo) {
9541       case Intrinsic::x86_mmx_pslli_w:
9542         NewIntNo = Intrinsic::x86_mmx_psll_w;
9543         break;
9544       case Intrinsic::x86_mmx_pslli_d:
9545         NewIntNo = Intrinsic::x86_mmx_psll_d;
9546         break;
9547       case Intrinsic::x86_mmx_pslli_q:
9548         NewIntNo = Intrinsic::x86_mmx_psll_q;
9549         break;
9550       case Intrinsic::x86_mmx_psrli_w:
9551         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9552         break;
9553       case Intrinsic::x86_mmx_psrli_d:
9554         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9555         break;
9556       case Intrinsic::x86_mmx_psrli_q:
9557         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9558         break;
9559       case Intrinsic::x86_mmx_psrai_w:
9560         NewIntNo = Intrinsic::x86_mmx_psra_w;
9561         break;
9562       case Intrinsic::x86_mmx_psrai_d:
9563         NewIntNo = Intrinsic::x86_mmx_psra_d;
9564         break;
9565       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9566       }
9567       break;
9568     }
9569     }
9570
9571     // The vector shift intrinsics with scalars uses 32b shift amounts but
9572     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9573     // to be zero.
9574     SDValue ShOps[4];
9575     ShOps[0] = ShAmt;
9576     ShOps[1] = DAG.getConstant(0, MVT::i32);
9577     if (ShAmtVT == MVT::v4i32) {
9578       ShOps[2] = DAG.getUNDEF(MVT::i32);
9579       ShOps[3] = DAG.getUNDEF(MVT::i32);
9580       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9581     } else {
9582       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9583 // FIXME this must be lowered to get rid of the invalid type.
9584     }
9585
9586     EVT VT = Op.getValueType();
9587     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9588     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9589                        DAG.getConstant(NewIntNo, MVT::i32),
9590                        Op.getOperand(1), ShAmt);
9591   }
9592   }
9593 }
9594
9595 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9596                                            SelectionDAG &DAG) const {
9597   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9598   MFI->setReturnAddressIsTaken(true);
9599
9600   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9601   DebugLoc dl = Op.getDebugLoc();
9602
9603   if (Depth > 0) {
9604     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9605     SDValue Offset =
9606       DAG.getConstant(TD->getPointerSize(),
9607                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9608     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9609                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9610                                    FrameAddr, Offset),
9611                        MachinePointerInfo(), false, false, 0);
9612   }
9613
9614   // Just load the return address.
9615   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9616   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9617                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9618 }
9619
9620 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9621   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9622   MFI->setFrameAddressIsTaken(true);
9623
9624   EVT VT = Op.getValueType();
9625   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9626   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9627   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9628   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9629   while (Depth--)
9630     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9631                             MachinePointerInfo(),
9632                             false, false, 0);
9633   return FrameAddr;
9634 }
9635
9636 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9637                                                      SelectionDAG &DAG) const {
9638   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9639 }
9640
9641 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9642   MachineFunction &MF = DAG.getMachineFunction();
9643   SDValue Chain     = Op.getOperand(0);
9644   SDValue Offset    = Op.getOperand(1);
9645   SDValue Handler   = Op.getOperand(2);
9646   DebugLoc dl       = Op.getDebugLoc();
9647
9648   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9649                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9650                                      getPointerTy());
9651   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9652
9653   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9654                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9655   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9656   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9657                        false, false, 0);
9658   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9659   MF.getRegInfo().addLiveOut(StoreAddrReg);
9660
9661   return DAG.getNode(X86ISD::EH_RETURN, dl,
9662                      MVT::Other,
9663                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9664 }
9665
9666 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9667                                                   SelectionDAG &DAG) const {
9668   return Op.getOperand(0);
9669 }
9670
9671 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9672                                                 SelectionDAG &DAG) const {
9673   SDValue Root = Op.getOperand(0);
9674   SDValue Trmp = Op.getOperand(1); // trampoline
9675   SDValue FPtr = Op.getOperand(2); // nested function
9676   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9677   DebugLoc dl  = Op.getDebugLoc();
9678
9679   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9680
9681   if (Subtarget->is64Bit()) {
9682     SDValue OutChains[6];
9683
9684     // Large code-model.
9685     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9686     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9687
9688     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9689     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9690
9691     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9692
9693     // Load the pointer to the nested function into R11.
9694     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9695     SDValue Addr = Trmp;
9696     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9697                                 Addr, MachinePointerInfo(TrmpAddr),
9698                                 false, false, 0);
9699
9700     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9701                        DAG.getConstant(2, MVT::i64));
9702     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9703                                 MachinePointerInfo(TrmpAddr, 2),
9704                                 false, false, 2);
9705
9706     // Load the 'nest' parameter value into R10.
9707     // R10 is specified in X86CallingConv.td
9708     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9709     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9710                        DAG.getConstant(10, MVT::i64));
9711     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9712                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9713                                 false, false, 0);
9714
9715     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9716                        DAG.getConstant(12, MVT::i64));
9717     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9718                                 MachinePointerInfo(TrmpAddr, 12),
9719                                 false, false, 2);
9720
9721     // Jump to the nested function.
9722     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9723     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9724                        DAG.getConstant(20, MVT::i64));
9725     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9726                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9727                                 false, false, 0);
9728
9729     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9730     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9731                        DAG.getConstant(22, MVT::i64));
9732     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9733                                 MachinePointerInfo(TrmpAddr, 22),
9734                                 false, false, 0);
9735
9736     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9737   } else {
9738     const Function *Func =
9739       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9740     CallingConv::ID CC = Func->getCallingConv();
9741     unsigned NestReg;
9742
9743     switch (CC) {
9744     default:
9745       llvm_unreachable("Unsupported calling convention");
9746     case CallingConv::C:
9747     case CallingConv::X86_StdCall: {
9748       // Pass 'nest' parameter in ECX.
9749       // Must be kept in sync with X86CallingConv.td
9750       NestReg = X86::ECX;
9751
9752       // Check that ECX wasn't needed by an 'inreg' parameter.
9753       FunctionType *FTy = Func->getFunctionType();
9754       const AttrListPtr &Attrs = Func->getAttributes();
9755
9756       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9757         unsigned InRegCount = 0;
9758         unsigned Idx = 1;
9759
9760         for (FunctionType::param_iterator I = FTy->param_begin(),
9761              E = FTy->param_end(); I != E; ++I, ++Idx)
9762           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9763             // FIXME: should only count parameters that are lowered to integers.
9764             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9765
9766         if (InRegCount > 2) {
9767           report_fatal_error("Nest register in use - reduce number of inreg"
9768                              " parameters!");
9769         }
9770       }
9771       break;
9772     }
9773     case CallingConv::X86_FastCall:
9774     case CallingConv::X86_ThisCall:
9775     case CallingConv::Fast:
9776       // Pass 'nest' parameter in EAX.
9777       // Must be kept in sync with X86CallingConv.td
9778       NestReg = X86::EAX;
9779       break;
9780     }
9781
9782     SDValue OutChains[4];
9783     SDValue Addr, Disp;
9784
9785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9786                        DAG.getConstant(10, MVT::i32));
9787     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9788
9789     // This is storing the opcode for MOV32ri.
9790     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9791     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9792     OutChains[0] = DAG.getStore(Root, dl,
9793                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9794                                 Trmp, MachinePointerInfo(TrmpAddr),
9795                                 false, false, 0);
9796
9797     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9798                        DAG.getConstant(1, MVT::i32));
9799     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9800                                 MachinePointerInfo(TrmpAddr, 1),
9801                                 false, false, 1);
9802
9803     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9805                        DAG.getConstant(5, MVT::i32));
9806     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9807                                 MachinePointerInfo(TrmpAddr, 5),
9808                                 false, false, 1);
9809
9810     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9811                        DAG.getConstant(6, MVT::i32));
9812     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9813                                 MachinePointerInfo(TrmpAddr, 6),
9814                                 false, false, 1);
9815
9816     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9817   }
9818 }
9819
9820 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9821                                             SelectionDAG &DAG) const {
9822   /*
9823    The rounding mode is in bits 11:10 of FPSR, and has the following
9824    settings:
9825      00 Round to nearest
9826      01 Round to -inf
9827      10 Round to +inf
9828      11 Round to 0
9829
9830   FLT_ROUNDS, on the other hand, expects the following:
9831     -1 Undefined
9832      0 Round to 0
9833      1 Round to nearest
9834      2 Round to +inf
9835      3 Round to -inf
9836
9837   To perform the conversion, we do:
9838     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9839   */
9840
9841   MachineFunction &MF = DAG.getMachineFunction();
9842   const TargetMachine &TM = MF.getTarget();
9843   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9844   unsigned StackAlignment = TFI.getStackAlignment();
9845   EVT VT = Op.getValueType();
9846   DebugLoc DL = Op.getDebugLoc();
9847
9848   // Save FP Control Word to stack slot
9849   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9850   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9851
9852
9853   MachineMemOperand *MMO =
9854    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9855                            MachineMemOperand::MOStore, 2, 2);
9856
9857   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9858   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9859                                           DAG.getVTList(MVT::Other),
9860                                           Ops, 2, MVT::i16, MMO);
9861
9862   // Load FP Control Word from stack slot
9863   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9864                             MachinePointerInfo(), false, false, 0);
9865
9866   // Transform as necessary
9867   SDValue CWD1 =
9868     DAG.getNode(ISD::SRL, DL, MVT::i16,
9869                 DAG.getNode(ISD::AND, DL, MVT::i16,
9870                             CWD, DAG.getConstant(0x800, MVT::i16)),
9871                 DAG.getConstant(11, MVT::i8));
9872   SDValue CWD2 =
9873     DAG.getNode(ISD::SRL, DL, MVT::i16,
9874                 DAG.getNode(ISD::AND, DL, MVT::i16,
9875                             CWD, DAG.getConstant(0x400, MVT::i16)),
9876                 DAG.getConstant(9, MVT::i8));
9877
9878   SDValue RetVal =
9879     DAG.getNode(ISD::AND, DL, MVT::i16,
9880                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9881                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9882                             DAG.getConstant(1, MVT::i16)),
9883                 DAG.getConstant(3, MVT::i16));
9884
9885
9886   return DAG.getNode((VT.getSizeInBits() < 16 ?
9887                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9888 }
9889
9890 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9891   EVT VT = Op.getValueType();
9892   EVT OpVT = VT;
9893   unsigned NumBits = VT.getSizeInBits();
9894   DebugLoc dl = Op.getDebugLoc();
9895
9896   Op = Op.getOperand(0);
9897   if (VT == MVT::i8) {
9898     // Zero extend to i32 since there is not an i8 bsr.
9899     OpVT = MVT::i32;
9900     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9901   }
9902
9903   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9904   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9905   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9906
9907   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9908   SDValue Ops[] = {
9909     Op,
9910     DAG.getConstant(NumBits+NumBits-1, OpVT),
9911     DAG.getConstant(X86::COND_E, MVT::i8),
9912     Op.getValue(1)
9913   };
9914   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9915
9916   // Finally xor with NumBits-1.
9917   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9918
9919   if (VT == MVT::i8)
9920     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9921   return Op;
9922 }
9923
9924 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9925   EVT VT = Op.getValueType();
9926   EVT OpVT = VT;
9927   unsigned NumBits = VT.getSizeInBits();
9928   DebugLoc dl = Op.getDebugLoc();
9929
9930   Op = Op.getOperand(0);
9931   if (VT == MVT::i8) {
9932     OpVT = MVT::i32;
9933     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9934   }
9935
9936   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9937   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9938   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9939
9940   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9941   SDValue Ops[] = {
9942     Op,
9943     DAG.getConstant(NumBits, OpVT),
9944     DAG.getConstant(X86::COND_E, MVT::i8),
9945     Op.getValue(1)
9946   };
9947   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9948
9949   if (VT == MVT::i8)
9950     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9951   return Op;
9952 }
9953
9954 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9955 // ones, and then concatenate the result back.
9956 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9957   EVT VT = Op.getValueType();
9958
9959   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9960          "Unsupported value type for operation");
9961
9962   int NumElems = VT.getVectorNumElements();
9963   DebugLoc dl = Op.getDebugLoc();
9964   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9965   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9966
9967   // Extract the LHS vectors
9968   SDValue LHS = Op.getOperand(0);
9969   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9970   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9971
9972   // Extract the RHS vectors
9973   SDValue RHS = Op.getOperand(1);
9974   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9975   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9976
9977   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9978   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9979
9980   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9981                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9982                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9983 }
9984
9985 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9986   assert(Op.getValueType().getSizeInBits() == 256 &&
9987          Op.getValueType().isInteger() &&
9988          "Only handle AVX 256-bit vector integer operation");
9989   return Lower256IntArith(Op, DAG);
9990 }
9991
9992 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9993   assert(Op.getValueType().getSizeInBits() == 256 &&
9994          Op.getValueType().isInteger() &&
9995          "Only handle AVX 256-bit vector integer operation");
9996   return Lower256IntArith(Op, DAG);
9997 }
9998
9999 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10000   EVT VT = Op.getValueType();
10001
10002   // Decompose 256-bit ops into smaller 128-bit ops.
10003   if (VT.getSizeInBits() == 256)
10004     return Lower256IntArith(Op, DAG);
10005
10006   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10007   DebugLoc dl = Op.getDebugLoc();
10008
10009   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10010   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10011   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10012   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10013   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10014   //
10015   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10016   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10017   //  return AloBlo + AloBhi + AhiBlo;
10018
10019   SDValue A = Op.getOperand(0);
10020   SDValue B = Op.getOperand(1);
10021
10022   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10023                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10024                        A, DAG.getConstant(32, MVT::i32));
10025   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10026                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10027                        B, DAG.getConstant(32, MVT::i32));
10028   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10029                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10030                        A, B);
10031   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10032                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10033                        A, Bhi);
10034   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10035                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10036                        Ahi, B);
10037   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10038                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10039                        AloBhi, DAG.getConstant(32, MVT::i32));
10040   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10041                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10042                        AhiBlo, DAG.getConstant(32, MVT::i32));
10043   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10044   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10045   return Res;
10046 }
10047
10048 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10049
10050   EVT VT = Op.getValueType();
10051   DebugLoc dl = Op.getDebugLoc();
10052   SDValue R = Op.getOperand(0);
10053   SDValue Amt = Op.getOperand(1);
10054   LLVMContext *Context = DAG.getContext();
10055
10056   if (!Subtarget->hasXMMInt())
10057     return SDValue();
10058
10059   // Decompose 256-bit shifts into smaller 128-bit shifts.
10060   if (VT.getSizeInBits() == 256) {
10061     int NumElems = VT.getVectorNumElements();
10062     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10063     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10064
10065     // Extract the two vectors
10066     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10067     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10068                                      DAG, dl);
10069
10070     // Recreate the shift amount vectors
10071     SDValue Amt1, Amt2;
10072     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10073       // Constant shift amount
10074       SmallVector<SDValue, 4> Amt1Csts;
10075       SmallVector<SDValue, 4> Amt2Csts;
10076       for (int i = 0; i < NumElems/2; ++i)
10077         Amt1Csts.push_back(Amt->getOperand(i));
10078       for (int i = NumElems/2; i < NumElems; ++i)
10079         Amt2Csts.push_back(Amt->getOperand(i));
10080
10081       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10082                                  &Amt1Csts[0], NumElems/2);
10083       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10084                                  &Amt2Csts[0], NumElems/2);
10085     } else {
10086       // Variable shift amount
10087       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10088       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10089                                  DAG, dl);
10090     }
10091
10092     // Issue new vector shifts for the smaller types
10093     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10094     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10095
10096     // Concatenate the result back
10097     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10098   }
10099
10100   // Optimize shl/srl/sra with constant shift amount.
10101   if (isSplatVector(Amt.getNode())) {
10102     SDValue SclrAmt = Amt->getOperand(0);
10103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10104       uint64_t ShiftAmt = C->getZExtValue();
10105
10106       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10107        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10108                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10109                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10110
10111       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10112        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10113                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10114                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10115
10116       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10117        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10118                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10119                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10120
10121       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10122        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10123                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10124                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10125
10126       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10127        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10128                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10129                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10130
10131       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10132        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10133                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10134                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10135
10136       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10137        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10138                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10139                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10140
10141       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10142        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10143                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10144                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10145     }
10146   }
10147
10148   // Lower SHL with variable shift amount.
10149   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10150     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10151                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10152                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10153
10154     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10155
10156     std::vector<Constant*> CV(4, CI);
10157     Constant *C = ConstantVector::get(CV);
10158     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10159     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10160                                  MachinePointerInfo::getConstantPool(),
10161                                  false, false, 16);
10162
10163     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10164     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10165     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10166     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10167   }
10168   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10169     // a = a << 5;
10170     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10171                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10172                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10173
10174     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10175     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10176
10177     std::vector<Constant*> CVM1(16, CM1);
10178     std::vector<Constant*> CVM2(16, CM2);
10179     Constant *C = ConstantVector::get(CVM1);
10180     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10181     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10182                             MachinePointerInfo::getConstantPool(),
10183                             false, false, 16);
10184
10185     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10186     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10187     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10188                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10189                     DAG.getConstant(4, MVT::i32));
10190     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10191     // a += a
10192     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10193
10194     C = ConstantVector::get(CVM2);
10195     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10196     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10197                     MachinePointerInfo::getConstantPool(),
10198                     false, false, 16);
10199
10200     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10201     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10202     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10203                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10204                     DAG.getConstant(2, MVT::i32));
10205     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10206     // a += a
10207     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10208
10209     // return pblendv(r, r+r, a);
10210     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10211                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10212     return R;
10213   }
10214   return SDValue();
10215 }
10216
10217 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10218   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10219   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10220   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10221   // has only one use.
10222   SDNode *N = Op.getNode();
10223   SDValue LHS = N->getOperand(0);
10224   SDValue RHS = N->getOperand(1);
10225   unsigned BaseOp = 0;
10226   unsigned Cond = 0;
10227   DebugLoc DL = Op.getDebugLoc();
10228   switch (Op.getOpcode()) {
10229   default: llvm_unreachable("Unknown ovf instruction!");
10230   case ISD::SADDO:
10231     // A subtract of one will be selected as a INC. Note that INC doesn't
10232     // set CF, so we can't do this for UADDO.
10233     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10234       if (C->isOne()) {
10235         BaseOp = X86ISD::INC;
10236         Cond = X86::COND_O;
10237         break;
10238       }
10239     BaseOp = X86ISD::ADD;
10240     Cond = X86::COND_O;
10241     break;
10242   case ISD::UADDO:
10243     BaseOp = X86ISD::ADD;
10244     Cond = X86::COND_B;
10245     break;
10246   case ISD::SSUBO:
10247     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10248     // set CF, so we can't do this for USUBO.
10249     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10250       if (C->isOne()) {
10251         BaseOp = X86ISD::DEC;
10252         Cond = X86::COND_O;
10253         break;
10254       }
10255     BaseOp = X86ISD::SUB;
10256     Cond = X86::COND_O;
10257     break;
10258   case ISD::USUBO:
10259     BaseOp = X86ISD::SUB;
10260     Cond = X86::COND_B;
10261     break;
10262   case ISD::SMULO:
10263     BaseOp = X86ISD::SMUL;
10264     Cond = X86::COND_O;
10265     break;
10266   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10267     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10268                                  MVT::i32);
10269     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10270
10271     SDValue SetCC =
10272       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10273                   DAG.getConstant(X86::COND_O, MVT::i32),
10274                   SDValue(Sum.getNode(), 2));
10275
10276     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10277   }
10278   }
10279
10280   // Also sets EFLAGS.
10281   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10282   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10283
10284   SDValue SetCC =
10285     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10286                 DAG.getConstant(Cond, MVT::i32),
10287                 SDValue(Sum.getNode(), 1));
10288
10289   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10290 }
10291
10292 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10293   DebugLoc dl = Op.getDebugLoc();
10294   SDNode* Node = Op.getNode();
10295   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10296   EVT VT = Node->getValueType(0);
10297   if (Subtarget->hasXMMInt() && VT.isVector()) {
10298     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10299                         ExtraVT.getScalarType().getSizeInBits();
10300     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10301
10302     unsigned SHLIntrinsicsID = 0;
10303     unsigned SRAIntrinsicsID = 0;
10304     switch (VT.getSimpleVT().SimpleTy) {
10305       default:
10306         return SDValue();
10307       case MVT::v4i32: {
10308         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10309         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10310         break;
10311       }
10312       case MVT::v8i16: {
10313         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10314         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10315         break;
10316       }
10317     }
10318
10319     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10320                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10321                          Node->getOperand(0), ShAmt);
10322
10323     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10324                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10325                        Tmp1, ShAmt);
10326   }
10327
10328   return SDValue();
10329 }
10330
10331
10332 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10333   DebugLoc dl = Op.getDebugLoc();
10334
10335   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10336   // There isn't any reason to disable it if the target processor supports it.
10337   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10338     SDValue Chain = Op.getOperand(0);
10339     SDValue Zero = DAG.getConstant(0, MVT::i32);
10340     SDValue Ops[] = {
10341       DAG.getRegister(X86::ESP, MVT::i32), // Base
10342       DAG.getTargetConstant(1, MVT::i8),   // Scale
10343       DAG.getRegister(0, MVT::i32),        // Index
10344       DAG.getTargetConstant(0, MVT::i32),  // Disp
10345       DAG.getRegister(0, MVT::i32),        // Segment.
10346       Zero,
10347       Chain
10348     };
10349     SDNode *Res =
10350       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10351                           array_lengthof(Ops));
10352     return SDValue(Res, 0);
10353   }
10354
10355   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10356   if (!isDev)
10357     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10358
10359   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10360   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10361   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10362   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10363
10364   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10365   if (!Op1 && !Op2 && !Op3 && Op4)
10366     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10367
10368   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10369   if (Op1 && !Op2 && !Op3 && !Op4)
10370     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10371
10372   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10373   //           (MFENCE)>;
10374   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10375 }
10376
10377 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10378                                              SelectionDAG &DAG) const {
10379   DebugLoc dl = Op.getDebugLoc();
10380   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10381     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10382   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10383     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10384
10385   // The only fence that needs an instruction is a sequentially-consistent
10386   // cross-thread fence.
10387   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10388     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10389     // no-sse2). There isn't any reason to disable it if the target processor
10390     // supports it.
10391     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10392       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10393
10394     SDValue Chain = Op.getOperand(0);
10395     SDValue Zero = DAG.getConstant(0, MVT::i32);
10396     SDValue Ops[] = {
10397       DAG.getRegister(X86::ESP, MVT::i32), // Base
10398       DAG.getTargetConstant(1, MVT::i8),   // Scale
10399       DAG.getRegister(0, MVT::i32),        // Index
10400       DAG.getTargetConstant(0, MVT::i32),  // Disp
10401       DAG.getRegister(0, MVT::i32),        // Segment.
10402       Zero,
10403       Chain
10404     };
10405     SDNode *Res =
10406       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10407                          array_lengthof(Ops));
10408     return SDValue(Res, 0);
10409   }
10410
10411   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10412   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10413 }
10414
10415
10416 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10417   EVT T = Op.getValueType();
10418   DebugLoc DL = Op.getDebugLoc();
10419   unsigned Reg = 0;
10420   unsigned size = 0;
10421   switch(T.getSimpleVT().SimpleTy) {
10422   default:
10423     assert(false && "Invalid value type!");
10424   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10425   case MVT::i16: Reg = X86::AX;  size = 2; break;
10426   case MVT::i32: Reg = X86::EAX; size = 4; break;
10427   case MVT::i64:
10428     assert(Subtarget->is64Bit() && "Node not type legal!");
10429     Reg = X86::RAX; size = 8;
10430     break;
10431   }
10432   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10433                                     Op.getOperand(2), SDValue());
10434   SDValue Ops[] = { cpIn.getValue(0),
10435                     Op.getOperand(1),
10436                     Op.getOperand(3),
10437                     DAG.getTargetConstant(size, MVT::i8),
10438                     cpIn.getValue(1) };
10439   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10440   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10441   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10442                                            Ops, 5, T, MMO);
10443   SDValue cpOut =
10444     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10445   return cpOut;
10446 }
10447
10448 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10449                                                  SelectionDAG &DAG) const {
10450   assert(Subtarget->is64Bit() && "Result not type legalized?");
10451   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10452   SDValue TheChain = Op.getOperand(0);
10453   DebugLoc dl = Op.getDebugLoc();
10454   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10455   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10456   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10457                                    rax.getValue(2));
10458   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10459                             DAG.getConstant(32, MVT::i8));
10460   SDValue Ops[] = {
10461     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10462     rdx.getValue(1)
10463   };
10464   return DAG.getMergeValues(Ops, 2, dl);
10465 }
10466
10467 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10468                                             SelectionDAG &DAG) const {
10469   EVT SrcVT = Op.getOperand(0).getValueType();
10470   EVT DstVT = Op.getValueType();
10471   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10472          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10473   assert((DstVT == MVT::i64 ||
10474           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10475          "Unexpected custom BITCAST");
10476   // i64 <=> MMX conversions are Legal.
10477   if (SrcVT==MVT::i64 && DstVT.isVector())
10478     return Op;
10479   if (DstVT==MVT::i64 && SrcVT.isVector())
10480     return Op;
10481   // MMX <=> MMX conversions are Legal.
10482   if (SrcVT.isVector() && DstVT.isVector())
10483     return Op;
10484   // All other conversions need to be expanded.
10485   return SDValue();
10486 }
10487
10488 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10489   SDNode *Node = Op.getNode();
10490   DebugLoc dl = Node->getDebugLoc();
10491   EVT T = Node->getValueType(0);
10492   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10493                               DAG.getConstant(0, T), Node->getOperand(2));
10494   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10495                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10496                        Node->getOperand(0),
10497                        Node->getOperand(1), negOp,
10498                        cast<AtomicSDNode>(Node)->getSrcValue(),
10499                        cast<AtomicSDNode>(Node)->getAlignment(),
10500                        cast<AtomicSDNode>(Node)->getOrdering(),
10501                        cast<AtomicSDNode>(Node)->getSynchScope());
10502 }
10503
10504 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10505   SDNode *Node = Op.getNode();
10506   DebugLoc dl = Node->getDebugLoc();
10507   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10508
10509   // Convert seq_cst store -> xchg
10510   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10511   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10512   //        (The only way to get a 16-byte store is cmpxchg16b)
10513   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10514   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10515       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10516     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10517                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10518                                  Node->getOperand(0),
10519                                  Node->getOperand(1), Node->getOperand(2),
10520                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10521                                  cast<AtomicSDNode>(Node)->getOrdering(),
10522                                  cast<AtomicSDNode>(Node)->getSynchScope());
10523     return Swap.getValue(1);
10524   }
10525   // Other atomic stores have a simple pattern.
10526   return Op;
10527 }
10528
10529 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10530   EVT VT = Op.getNode()->getValueType(0);
10531
10532   // Let legalize expand this if it isn't a legal type yet.
10533   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10534     return SDValue();
10535
10536   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10537
10538   unsigned Opc;
10539   bool ExtraOp = false;
10540   switch (Op.getOpcode()) {
10541   default: assert(0 && "Invalid code");
10542   case ISD::ADDC: Opc = X86ISD::ADD; break;
10543   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10544   case ISD::SUBC: Opc = X86ISD::SUB; break;
10545   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10546   }
10547
10548   if (!ExtraOp)
10549     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10550                        Op.getOperand(1));
10551   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10552                      Op.getOperand(1), Op.getOperand(2));
10553 }
10554
10555 /// LowerOperation - Provide custom lowering hooks for some operations.
10556 ///
10557 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10558   switch (Op.getOpcode()) {
10559   default: llvm_unreachable("Should not custom lower this!");
10560   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10561   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10562   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10563   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10564   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10565   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10566   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10567   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10568   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10569   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10570   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10571   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10572   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10573   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10574   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10575   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10576   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10577   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10578   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10579   case ISD::SHL_PARTS:
10580   case ISD::SRA_PARTS:
10581   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10582   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10583   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10584   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10585   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10586   case ISD::FABS:               return LowerFABS(Op, DAG);
10587   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10588   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10589   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10590   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10591   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10592   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10593   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10594   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10595   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10596   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10597   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10598   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10599   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10600   case ISD::FRAME_TO_ARGS_OFFSET:
10601                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10602   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10603   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10604   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10605   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10606   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10607   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10608   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10609   case ISD::MUL:                return LowerMUL(Op, DAG);
10610   case ISD::SRA:
10611   case ISD::SRL:
10612   case ISD::SHL:                return LowerShift(Op, DAG);
10613   case ISD::SADDO:
10614   case ISD::UADDO:
10615   case ISD::SSUBO:
10616   case ISD::USUBO:
10617   case ISD::SMULO:
10618   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10619   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10620   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10621   case ISD::ADDC:
10622   case ISD::ADDE:
10623   case ISD::SUBC:
10624   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10625   case ISD::ADD:                return LowerADD(Op, DAG);
10626   case ISD::SUB:                return LowerSUB(Op, DAG);
10627   }
10628 }
10629
10630 static void ReplaceATOMIC_LOAD(SDNode *Node,
10631                                   SmallVectorImpl<SDValue> &Results,
10632                                   SelectionDAG &DAG) {
10633   DebugLoc dl = Node->getDebugLoc();
10634   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10635
10636   // Convert wide load -> cmpxchg8b/cmpxchg16b
10637   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10638   //        (The only way to get a 16-byte load is cmpxchg16b)
10639   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10640   SDValue Zero = DAG.getConstant(0, VT);
10641   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10642                                Node->getOperand(0),
10643                                Node->getOperand(1), Zero, Zero,
10644                                cast<AtomicSDNode>(Node)->getMemOperand(),
10645                                cast<AtomicSDNode>(Node)->getOrdering(),
10646                                cast<AtomicSDNode>(Node)->getSynchScope());
10647   Results.push_back(Swap.getValue(0));
10648   Results.push_back(Swap.getValue(1));
10649 }
10650
10651 void X86TargetLowering::
10652 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10653                         SelectionDAG &DAG, unsigned NewOp) const {
10654   DebugLoc dl = Node->getDebugLoc();
10655   assert (Node->getValueType(0) == MVT::i64 &&
10656           "Only know how to expand i64 atomics");
10657
10658   SDValue Chain = Node->getOperand(0);
10659   SDValue In1 = Node->getOperand(1);
10660   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10661                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10662   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10663                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10664   SDValue Ops[] = { Chain, In1, In2L, In2H };
10665   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10666   SDValue Result =
10667     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10668                             cast<MemSDNode>(Node)->getMemOperand());
10669   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10670   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10671   Results.push_back(Result.getValue(2));
10672 }
10673
10674 /// ReplaceNodeResults - Replace a node with an illegal result type
10675 /// with a new node built out of custom code.
10676 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10677                                            SmallVectorImpl<SDValue>&Results,
10678                                            SelectionDAG &DAG) const {
10679   DebugLoc dl = N->getDebugLoc();
10680   switch (N->getOpcode()) {
10681   default:
10682     assert(false && "Do not know how to custom type legalize this operation!");
10683     return;
10684   case ISD::SIGN_EXTEND_INREG:
10685   case ISD::ADDC:
10686   case ISD::ADDE:
10687   case ISD::SUBC:
10688   case ISD::SUBE:
10689     // We don't want to expand or promote these.
10690     return;
10691   case ISD::FP_TO_SINT: {
10692     std::pair<SDValue,SDValue> Vals =
10693         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10694     SDValue FIST = Vals.first, StackSlot = Vals.second;
10695     if (FIST.getNode() != 0) {
10696       EVT VT = N->getValueType(0);
10697       // Return a load from the stack slot.
10698       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10699                                     MachinePointerInfo(), false, false, 0));
10700     }
10701     return;
10702   }
10703   case ISD::READCYCLECOUNTER: {
10704     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10705     SDValue TheChain = N->getOperand(0);
10706     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10707     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10708                                      rd.getValue(1));
10709     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10710                                      eax.getValue(2));
10711     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10712     SDValue Ops[] = { eax, edx };
10713     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10714     Results.push_back(edx.getValue(1));
10715     return;
10716   }
10717   case ISD::ATOMIC_CMP_SWAP: {
10718     EVT T = N->getValueType(0);
10719     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10720     bool Regs64bit = T == MVT::i128;
10721     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10722     SDValue cpInL, cpInH;
10723     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10724                         DAG.getConstant(0, HalfT));
10725     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10726                         DAG.getConstant(1, HalfT));
10727     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10728                              Regs64bit ? X86::RAX : X86::EAX,
10729                              cpInL, SDValue());
10730     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10731                              Regs64bit ? X86::RDX : X86::EDX,
10732                              cpInH, cpInL.getValue(1));
10733     SDValue swapInL, swapInH;
10734     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10735                           DAG.getConstant(0, HalfT));
10736     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10737                           DAG.getConstant(1, HalfT));
10738     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10739                                Regs64bit ? X86::RBX : X86::EBX,
10740                                swapInL, cpInH.getValue(1));
10741     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10742                                Regs64bit ? X86::RCX : X86::ECX, 
10743                                swapInH, swapInL.getValue(1));
10744     SDValue Ops[] = { swapInH.getValue(0),
10745                       N->getOperand(1),
10746                       swapInH.getValue(1) };
10747     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10748     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10749     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10750                                   X86ISD::LCMPXCHG8_DAG;
10751     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10752                                              Ops, 3, T, MMO);
10753     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10754                                         Regs64bit ? X86::RAX : X86::EAX,
10755                                         HalfT, Result.getValue(1));
10756     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10757                                         Regs64bit ? X86::RDX : X86::EDX,
10758                                         HalfT, cpOutL.getValue(2));
10759     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10760     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10761     Results.push_back(cpOutH.getValue(1));
10762     return;
10763   }
10764   case ISD::ATOMIC_LOAD_ADD:
10765     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10766     return;
10767   case ISD::ATOMIC_LOAD_AND:
10768     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10769     return;
10770   case ISD::ATOMIC_LOAD_NAND:
10771     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10772     return;
10773   case ISD::ATOMIC_LOAD_OR:
10774     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10775     return;
10776   case ISD::ATOMIC_LOAD_SUB:
10777     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10778     return;
10779   case ISD::ATOMIC_LOAD_XOR:
10780     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10781     return;
10782   case ISD::ATOMIC_SWAP:
10783     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10784     return;
10785   case ISD::ATOMIC_LOAD:
10786     ReplaceATOMIC_LOAD(N, Results, DAG);
10787   }
10788 }
10789
10790 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10791   switch (Opcode) {
10792   default: return NULL;
10793   case X86ISD::BSF:                return "X86ISD::BSF";
10794   case X86ISD::BSR:                return "X86ISD::BSR";
10795   case X86ISD::SHLD:               return "X86ISD::SHLD";
10796   case X86ISD::SHRD:               return "X86ISD::SHRD";
10797   case X86ISD::FAND:               return "X86ISD::FAND";
10798   case X86ISD::FOR:                return "X86ISD::FOR";
10799   case X86ISD::FXOR:               return "X86ISD::FXOR";
10800   case X86ISD::FSRL:               return "X86ISD::FSRL";
10801   case X86ISD::FILD:               return "X86ISD::FILD";
10802   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10803   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10804   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10805   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10806   case X86ISD::FLD:                return "X86ISD::FLD";
10807   case X86ISD::FST:                return "X86ISD::FST";
10808   case X86ISD::CALL:               return "X86ISD::CALL";
10809   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10810   case X86ISD::BT:                 return "X86ISD::BT";
10811   case X86ISD::CMP:                return "X86ISD::CMP";
10812   case X86ISD::COMI:               return "X86ISD::COMI";
10813   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10814   case X86ISD::SETCC:              return "X86ISD::SETCC";
10815   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10816   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10817   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10818   case X86ISD::CMOV:               return "X86ISD::CMOV";
10819   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10820   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10821   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10822   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10823   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10824   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10825   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10826   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10827   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10828   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10829   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10830   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10831   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10832   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10833   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10834   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10835   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10836   case X86ISD::FMAX:               return "X86ISD::FMAX";
10837   case X86ISD::FMIN:               return "X86ISD::FMIN";
10838   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10839   case X86ISD::FRCP:               return "X86ISD::FRCP";
10840   case X86ISD::FHADD:              return "X86ISD::FHADD";
10841   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10842   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10843   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10844   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10845   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10846   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10847   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10848   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10849   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10850   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10851   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10852   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10853   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10854   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10855   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10856   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10857   case X86ISD::VSHL:               return "X86ISD::VSHL";
10858   case X86ISD::VSRL:               return "X86ISD::VSRL";
10859   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10860   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10861   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10862   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10863   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10864   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10865   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10866   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10867   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10868   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10869   case X86ISD::ADD:                return "X86ISD::ADD";
10870   case X86ISD::SUB:                return "X86ISD::SUB";
10871   case X86ISD::ADC:                return "X86ISD::ADC";
10872   case X86ISD::SBB:                return "X86ISD::SBB";
10873   case X86ISD::SMUL:               return "X86ISD::SMUL";
10874   case X86ISD::UMUL:               return "X86ISD::UMUL";
10875   case X86ISD::INC:                return "X86ISD::INC";
10876   case X86ISD::DEC:                return "X86ISD::DEC";
10877   case X86ISD::OR:                 return "X86ISD::OR";
10878   case X86ISD::XOR:                return "X86ISD::XOR";
10879   case X86ISD::AND:                return "X86ISD::AND";
10880   case X86ISD::ANDN:               return "X86ISD::ANDN";
10881   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10882   case X86ISD::PTEST:              return "X86ISD::PTEST";
10883   case X86ISD::TESTP:              return "X86ISD::TESTP";
10884   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10885   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10886   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10887   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10888   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10889   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10890   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10891   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10892   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10893   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10894   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10895   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10896   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10897   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10898   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10899   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10900   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10901   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10902   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10903   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10904   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10905   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10906   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10907   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10908   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10909   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10910   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10911   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10912   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10913   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10914   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10915   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10916   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10917   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10918   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10919   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10920   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10921   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10922   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10923   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10924   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10925   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10926   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10927   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10928   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10929   }
10930 }
10931
10932 // isLegalAddressingMode - Return true if the addressing mode represented
10933 // by AM is legal for this target, for a load/store of the specified type.
10934 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10935                                               Type *Ty) const {
10936   // X86 supports extremely general addressing modes.
10937   CodeModel::Model M = getTargetMachine().getCodeModel();
10938   Reloc::Model R = getTargetMachine().getRelocationModel();
10939
10940   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10941   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10942     return false;
10943
10944   if (AM.BaseGV) {
10945     unsigned GVFlags =
10946       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10947
10948     // If a reference to this global requires an extra load, we can't fold it.
10949     if (isGlobalStubReference(GVFlags))
10950       return false;
10951
10952     // If BaseGV requires a register for the PIC base, we cannot also have a
10953     // BaseReg specified.
10954     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10955       return false;
10956
10957     // If lower 4G is not available, then we must use rip-relative addressing.
10958     if ((M != CodeModel::Small || R != Reloc::Static) &&
10959         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10960       return false;
10961   }
10962
10963   switch (AM.Scale) {
10964   case 0:
10965   case 1:
10966   case 2:
10967   case 4:
10968   case 8:
10969     // These scales always work.
10970     break;
10971   case 3:
10972   case 5:
10973   case 9:
10974     // These scales are formed with basereg+scalereg.  Only accept if there is
10975     // no basereg yet.
10976     if (AM.HasBaseReg)
10977       return false;
10978     break;
10979   default:  // Other stuff never works.
10980     return false;
10981   }
10982
10983   return true;
10984 }
10985
10986
10987 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10988   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10989     return false;
10990   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10991   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10992   if (NumBits1 <= NumBits2)
10993     return false;
10994   return true;
10995 }
10996
10997 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10998   if (!VT1.isInteger() || !VT2.isInteger())
10999     return false;
11000   unsigned NumBits1 = VT1.getSizeInBits();
11001   unsigned NumBits2 = VT2.getSizeInBits();
11002   if (NumBits1 <= NumBits2)
11003     return false;
11004   return true;
11005 }
11006
11007 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11008   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11009   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11010 }
11011
11012 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11013   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11014   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11015 }
11016
11017 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11018   // i16 instructions are longer (0x66 prefix) and potentially slower.
11019   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11020 }
11021
11022 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11023 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11024 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11025 /// are assumed to be legal.
11026 bool
11027 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11028                                       EVT VT) const {
11029   // Very little shuffling can be done for 64-bit vectors right now.
11030   if (VT.getSizeInBits() == 64)
11031     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11032
11033   // FIXME: pshufb, blends, shifts.
11034   return (VT.getVectorNumElements() == 2 ||
11035           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11036           isMOVLMask(M, VT) ||
11037           isSHUFPMask(M, VT) ||
11038           isPSHUFDMask(M, VT) ||
11039           isPSHUFHWMask(M, VT) ||
11040           isPSHUFLWMask(M, VT) ||
11041           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11042           isUNPCKLMask(M, VT) ||
11043           isUNPCKHMask(M, VT) ||
11044           isUNPCKL_v_undef_Mask(M, VT) ||
11045           isUNPCKH_v_undef_Mask(M, VT));
11046 }
11047
11048 bool
11049 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11050                                           EVT VT) const {
11051   unsigned NumElts = VT.getVectorNumElements();
11052   // FIXME: This collection of masks seems suspect.
11053   if (NumElts == 2)
11054     return true;
11055   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11056     return (isMOVLMask(Mask, VT)  ||
11057             isCommutedMOVLMask(Mask, VT, true) ||
11058             isSHUFPMask(Mask, VT) ||
11059             isCommutedSHUFPMask(Mask, VT));
11060   }
11061   return false;
11062 }
11063
11064 //===----------------------------------------------------------------------===//
11065 //                           X86 Scheduler Hooks
11066 //===----------------------------------------------------------------------===//
11067
11068 // private utility function
11069 MachineBasicBlock *
11070 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11071                                                        MachineBasicBlock *MBB,
11072                                                        unsigned regOpc,
11073                                                        unsigned immOpc,
11074                                                        unsigned LoadOpc,
11075                                                        unsigned CXchgOpc,
11076                                                        unsigned notOpc,
11077                                                        unsigned EAXreg,
11078                                                        TargetRegisterClass *RC,
11079                                                        bool invSrc) const {
11080   // For the atomic bitwise operator, we generate
11081   //   thisMBB:
11082   //   newMBB:
11083   //     ld  t1 = [bitinstr.addr]
11084   //     op  t2 = t1, [bitinstr.val]
11085   //     mov EAX = t1
11086   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11087   //     bz  newMBB
11088   //     fallthrough -->nextMBB
11089   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11090   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11091   MachineFunction::iterator MBBIter = MBB;
11092   ++MBBIter;
11093
11094   /// First build the CFG
11095   MachineFunction *F = MBB->getParent();
11096   MachineBasicBlock *thisMBB = MBB;
11097   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11098   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11099   F->insert(MBBIter, newMBB);
11100   F->insert(MBBIter, nextMBB);
11101
11102   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11103   nextMBB->splice(nextMBB->begin(), thisMBB,
11104                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11105                   thisMBB->end());
11106   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11107
11108   // Update thisMBB to fall through to newMBB
11109   thisMBB->addSuccessor(newMBB);
11110
11111   // newMBB jumps to itself and fall through to nextMBB
11112   newMBB->addSuccessor(nextMBB);
11113   newMBB->addSuccessor(newMBB);
11114
11115   // Insert instructions into newMBB based on incoming instruction
11116   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11117          "unexpected number of operands");
11118   DebugLoc dl = bInstr->getDebugLoc();
11119   MachineOperand& destOper = bInstr->getOperand(0);
11120   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11121   int numArgs = bInstr->getNumOperands() - 1;
11122   for (int i=0; i < numArgs; ++i)
11123     argOpers[i] = &bInstr->getOperand(i+1);
11124
11125   // x86 address has 4 operands: base, index, scale, and displacement
11126   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11127   int valArgIndx = lastAddrIndx + 1;
11128
11129   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11130   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11131   for (int i=0; i <= lastAddrIndx; ++i)
11132     (*MIB).addOperand(*argOpers[i]);
11133
11134   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11135   if (invSrc) {
11136     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11137   }
11138   else
11139     tt = t1;
11140
11141   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11142   assert((argOpers[valArgIndx]->isReg() ||
11143           argOpers[valArgIndx]->isImm()) &&
11144          "invalid operand");
11145   if (argOpers[valArgIndx]->isReg())
11146     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11147   else
11148     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11149   MIB.addReg(tt);
11150   (*MIB).addOperand(*argOpers[valArgIndx]);
11151
11152   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11153   MIB.addReg(t1);
11154
11155   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11156   for (int i=0; i <= lastAddrIndx; ++i)
11157     (*MIB).addOperand(*argOpers[i]);
11158   MIB.addReg(t2);
11159   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11160   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11161                     bInstr->memoperands_end());
11162
11163   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11164   MIB.addReg(EAXreg);
11165
11166   // insert branch
11167   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11168
11169   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11170   return nextMBB;
11171 }
11172
11173 // private utility function:  64 bit atomics on 32 bit host.
11174 MachineBasicBlock *
11175 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11176                                                        MachineBasicBlock *MBB,
11177                                                        unsigned regOpcL,
11178                                                        unsigned regOpcH,
11179                                                        unsigned immOpcL,
11180                                                        unsigned immOpcH,
11181                                                        bool invSrc) const {
11182   // For the atomic bitwise operator, we generate
11183   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11184   //     ld t1,t2 = [bitinstr.addr]
11185   //   newMBB:
11186   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11187   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11188   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11189   //     mov ECX, EBX <- t5, t6
11190   //     mov EAX, EDX <- t1, t2
11191   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11192   //     mov t3, t4 <- EAX, EDX
11193   //     bz  newMBB
11194   //     result in out1, out2
11195   //     fallthrough -->nextMBB
11196
11197   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11198   const unsigned LoadOpc = X86::MOV32rm;
11199   const unsigned NotOpc = X86::NOT32r;
11200   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11201   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11202   MachineFunction::iterator MBBIter = MBB;
11203   ++MBBIter;
11204
11205   /// First build the CFG
11206   MachineFunction *F = MBB->getParent();
11207   MachineBasicBlock *thisMBB = MBB;
11208   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11209   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11210   F->insert(MBBIter, newMBB);
11211   F->insert(MBBIter, nextMBB);
11212
11213   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11214   nextMBB->splice(nextMBB->begin(), thisMBB,
11215                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11216                   thisMBB->end());
11217   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11218
11219   // Update thisMBB to fall through to newMBB
11220   thisMBB->addSuccessor(newMBB);
11221
11222   // newMBB jumps to itself and fall through to nextMBB
11223   newMBB->addSuccessor(nextMBB);
11224   newMBB->addSuccessor(newMBB);
11225
11226   DebugLoc dl = bInstr->getDebugLoc();
11227   // Insert instructions into newMBB based on incoming instruction
11228   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11229   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11230          "unexpected number of operands");
11231   MachineOperand& dest1Oper = bInstr->getOperand(0);
11232   MachineOperand& dest2Oper = bInstr->getOperand(1);
11233   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11234   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11235     argOpers[i] = &bInstr->getOperand(i+2);
11236
11237     // We use some of the operands multiple times, so conservatively just
11238     // clear any kill flags that might be present.
11239     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11240       argOpers[i]->setIsKill(false);
11241   }
11242
11243   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11244   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11245
11246   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11247   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11248   for (int i=0; i <= lastAddrIndx; ++i)
11249     (*MIB).addOperand(*argOpers[i]);
11250   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11251   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11252   // add 4 to displacement.
11253   for (int i=0; i <= lastAddrIndx-2; ++i)
11254     (*MIB).addOperand(*argOpers[i]);
11255   MachineOperand newOp3 = *(argOpers[3]);
11256   if (newOp3.isImm())
11257     newOp3.setImm(newOp3.getImm()+4);
11258   else
11259     newOp3.setOffset(newOp3.getOffset()+4);
11260   (*MIB).addOperand(newOp3);
11261   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11262
11263   // t3/4 are defined later, at the bottom of the loop
11264   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11265   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11266   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11267     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11268   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11269     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11270
11271   // The subsequent operations should be using the destination registers of
11272   //the PHI instructions.
11273   if (invSrc) {
11274     t1 = F->getRegInfo().createVirtualRegister(RC);
11275     t2 = F->getRegInfo().createVirtualRegister(RC);
11276     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11277     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11278   } else {
11279     t1 = dest1Oper.getReg();
11280     t2 = dest2Oper.getReg();
11281   }
11282
11283   int valArgIndx = lastAddrIndx + 1;
11284   assert((argOpers[valArgIndx]->isReg() ||
11285           argOpers[valArgIndx]->isImm()) &&
11286          "invalid operand");
11287   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11288   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11289   if (argOpers[valArgIndx]->isReg())
11290     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11291   else
11292     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11293   if (regOpcL != X86::MOV32rr)
11294     MIB.addReg(t1);
11295   (*MIB).addOperand(*argOpers[valArgIndx]);
11296   assert(argOpers[valArgIndx + 1]->isReg() ==
11297          argOpers[valArgIndx]->isReg());
11298   assert(argOpers[valArgIndx + 1]->isImm() ==
11299          argOpers[valArgIndx]->isImm());
11300   if (argOpers[valArgIndx + 1]->isReg())
11301     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11302   else
11303     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11304   if (regOpcH != X86::MOV32rr)
11305     MIB.addReg(t2);
11306   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11307
11308   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11309   MIB.addReg(t1);
11310   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11311   MIB.addReg(t2);
11312
11313   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11314   MIB.addReg(t5);
11315   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11316   MIB.addReg(t6);
11317
11318   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11319   for (int i=0; i <= lastAddrIndx; ++i)
11320     (*MIB).addOperand(*argOpers[i]);
11321
11322   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11323   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11324                     bInstr->memoperands_end());
11325
11326   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11327   MIB.addReg(X86::EAX);
11328   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11329   MIB.addReg(X86::EDX);
11330
11331   // insert branch
11332   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11333
11334   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11335   return nextMBB;
11336 }
11337
11338 // private utility function
11339 MachineBasicBlock *
11340 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11341                                                       MachineBasicBlock *MBB,
11342                                                       unsigned cmovOpc) const {
11343   // For the atomic min/max operator, we generate
11344   //   thisMBB:
11345   //   newMBB:
11346   //     ld t1 = [min/max.addr]
11347   //     mov t2 = [min/max.val]
11348   //     cmp  t1, t2
11349   //     cmov[cond] t2 = t1
11350   //     mov EAX = t1
11351   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11352   //     bz   newMBB
11353   //     fallthrough -->nextMBB
11354   //
11355   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11356   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11357   MachineFunction::iterator MBBIter = MBB;
11358   ++MBBIter;
11359
11360   /// First build the CFG
11361   MachineFunction *F = MBB->getParent();
11362   MachineBasicBlock *thisMBB = MBB;
11363   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11364   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11365   F->insert(MBBIter, newMBB);
11366   F->insert(MBBIter, nextMBB);
11367
11368   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11369   nextMBB->splice(nextMBB->begin(), thisMBB,
11370                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11371                   thisMBB->end());
11372   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11373
11374   // Update thisMBB to fall through to newMBB
11375   thisMBB->addSuccessor(newMBB);
11376
11377   // newMBB jumps to newMBB and fall through to nextMBB
11378   newMBB->addSuccessor(nextMBB);
11379   newMBB->addSuccessor(newMBB);
11380
11381   DebugLoc dl = mInstr->getDebugLoc();
11382   // Insert instructions into newMBB based on incoming instruction
11383   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11384          "unexpected number of operands");
11385   MachineOperand& destOper = mInstr->getOperand(0);
11386   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11387   int numArgs = mInstr->getNumOperands() - 1;
11388   for (int i=0; i < numArgs; ++i)
11389     argOpers[i] = &mInstr->getOperand(i+1);
11390
11391   // x86 address has 4 operands: base, index, scale, and displacement
11392   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11393   int valArgIndx = lastAddrIndx + 1;
11394
11395   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11396   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11397   for (int i=0; i <= lastAddrIndx; ++i)
11398     (*MIB).addOperand(*argOpers[i]);
11399
11400   // We only support register and immediate values
11401   assert((argOpers[valArgIndx]->isReg() ||
11402           argOpers[valArgIndx]->isImm()) &&
11403          "invalid operand");
11404
11405   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11406   if (argOpers[valArgIndx]->isReg())
11407     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11408   else
11409     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11410   (*MIB).addOperand(*argOpers[valArgIndx]);
11411
11412   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11413   MIB.addReg(t1);
11414
11415   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11416   MIB.addReg(t1);
11417   MIB.addReg(t2);
11418
11419   // Generate movc
11420   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11421   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11422   MIB.addReg(t2);
11423   MIB.addReg(t1);
11424
11425   // Cmp and exchange if none has modified the memory location
11426   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11427   for (int i=0; i <= lastAddrIndx; ++i)
11428     (*MIB).addOperand(*argOpers[i]);
11429   MIB.addReg(t3);
11430   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11431   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11432                     mInstr->memoperands_end());
11433
11434   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11435   MIB.addReg(X86::EAX);
11436
11437   // insert branch
11438   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11439
11440   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11441   return nextMBB;
11442 }
11443
11444 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11445 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11446 // in the .td file.
11447 MachineBasicBlock *
11448 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11449                             unsigned numArgs, bool memArg) const {
11450   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11451          "Target must have SSE4.2 or AVX features enabled");
11452
11453   DebugLoc dl = MI->getDebugLoc();
11454   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11455   unsigned Opc;
11456   if (!Subtarget->hasAVX()) {
11457     if (memArg)
11458       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11459     else
11460       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11461   } else {
11462     if (memArg)
11463       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11464     else
11465       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11466   }
11467
11468   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11469   for (unsigned i = 0; i < numArgs; ++i) {
11470     MachineOperand &Op = MI->getOperand(i+1);
11471     if (!(Op.isReg() && Op.isImplicit()))
11472       MIB.addOperand(Op);
11473   }
11474   BuildMI(*BB, MI, dl,
11475     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11476              MI->getOperand(0).getReg())
11477     .addReg(X86::XMM0);
11478
11479   MI->eraseFromParent();
11480   return BB;
11481 }
11482
11483 MachineBasicBlock *
11484 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11485   DebugLoc dl = MI->getDebugLoc();
11486   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11487
11488   // Address into RAX/EAX, other two args into ECX, EDX.
11489   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11490   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11491   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11492   for (int i = 0; i < X86::AddrNumOperands; ++i)
11493     MIB.addOperand(MI->getOperand(i));
11494
11495   unsigned ValOps = X86::AddrNumOperands;
11496   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11497     .addReg(MI->getOperand(ValOps).getReg());
11498   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11499     .addReg(MI->getOperand(ValOps+1).getReg());
11500
11501   // The instruction doesn't actually take any operands though.
11502   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11503
11504   MI->eraseFromParent(); // The pseudo is gone now.
11505   return BB;
11506 }
11507
11508 MachineBasicBlock *
11509 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11510   DebugLoc dl = MI->getDebugLoc();
11511   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11512
11513   // First arg in ECX, the second in EAX.
11514   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11515     .addReg(MI->getOperand(0).getReg());
11516   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11517     .addReg(MI->getOperand(1).getReg());
11518
11519   // The instruction doesn't actually take any operands though.
11520   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11521
11522   MI->eraseFromParent(); // The pseudo is gone now.
11523   return BB;
11524 }
11525
11526 MachineBasicBlock *
11527 X86TargetLowering::EmitVAARG64WithCustomInserter(
11528                    MachineInstr *MI,
11529                    MachineBasicBlock *MBB) const {
11530   // Emit va_arg instruction on X86-64.
11531
11532   // Operands to this pseudo-instruction:
11533   // 0  ) Output        : destination address (reg)
11534   // 1-5) Input         : va_list address (addr, i64mem)
11535   // 6  ) ArgSize       : Size (in bytes) of vararg type
11536   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11537   // 8  ) Align         : Alignment of type
11538   // 9  ) EFLAGS (implicit-def)
11539
11540   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11541   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11542
11543   unsigned DestReg = MI->getOperand(0).getReg();
11544   MachineOperand &Base = MI->getOperand(1);
11545   MachineOperand &Scale = MI->getOperand(2);
11546   MachineOperand &Index = MI->getOperand(3);
11547   MachineOperand &Disp = MI->getOperand(4);
11548   MachineOperand &Segment = MI->getOperand(5);
11549   unsigned ArgSize = MI->getOperand(6).getImm();
11550   unsigned ArgMode = MI->getOperand(7).getImm();
11551   unsigned Align = MI->getOperand(8).getImm();
11552
11553   // Memory Reference
11554   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11555   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11556   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11557
11558   // Machine Information
11559   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11560   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11561   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11562   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11563   DebugLoc DL = MI->getDebugLoc();
11564
11565   // struct va_list {
11566   //   i32   gp_offset
11567   //   i32   fp_offset
11568   //   i64   overflow_area (address)
11569   //   i64   reg_save_area (address)
11570   // }
11571   // sizeof(va_list) = 24
11572   // alignment(va_list) = 8
11573
11574   unsigned TotalNumIntRegs = 6;
11575   unsigned TotalNumXMMRegs = 8;
11576   bool UseGPOffset = (ArgMode == 1);
11577   bool UseFPOffset = (ArgMode == 2);
11578   unsigned MaxOffset = TotalNumIntRegs * 8 +
11579                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11580
11581   /* Align ArgSize to a multiple of 8 */
11582   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11583   bool NeedsAlign = (Align > 8);
11584
11585   MachineBasicBlock *thisMBB = MBB;
11586   MachineBasicBlock *overflowMBB;
11587   MachineBasicBlock *offsetMBB;
11588   MachineBasicBlock *endMBB;
11589
11590   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11591   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11592   unsigned OffsetReg = 0;
11593
11594   if (!UseGPOffset && !UseFPOffset) {
11595     // If we only pull from the overflow region, we don't create a branch.
11596     // We don't need to alter control flow.
11597     OffsetDestReg = 0; // unused
11598     OverflowDestReg = DestReg;
11599
11600     offsetMBB = NULL;
11601     overflowMBB = thisMBB;
11602     endMBB = thisMBB;
11603   } else {
11604     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11605     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11606     // If not, pull from overflow_area. (branch to overflowMBB)
11607     //
11608     //       thisMBB
11609     //         |     .
11610     //         |        .
11611     //     offsetMBB   overflowMBB
11612     //         |        .
11613     //         |     .
11614     //        endMBB
11615
11616     // Registers for the PHI in endMBB
11617     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11618     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11619
11620     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11621     MachineFunction *MF = MBB->getParent();
11622     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11623     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11624     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11625
11626     MachineFunction::iterator MBBIter = MBB;
11627     ++MBBIter;
11628
11629     // Insert the new basic blocks
11630     MF->insert(MBBIter, offsetMBB);
11631     MF->insert(MBBIter, overflowMBB);
11632     MF->insert(MBBIter, endMBB);
11633
11634     // Transfer the remainder of MBB and its successor edges to endMBB.
11635     endMBB->splice(endMBB->begin(), thisMBB,
11636                     llvm::next(MachineBasicBlock::iterator(MI)),
11637                     thisMBB->end());
11638     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11639
11640     // Make offsetMBB and overflowMBB successors of thisMBB
11641     thisMBB->addSuccessor(offsetMBB);
11642     thisMBB->addSuccessor(overflowMBB);
11643
11644     // endMBB is a successor of both offsetMBB and overflowMBB
11645     offsetMBB->addSuccessor(endMBB);
11646     overflowMBB->addSuccessor(endMBB);
11647
11648     // Load the offset value into a register
11649     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11650     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11651       .addOperand(Base)
11652       .addOperand(Scale)
11653       .addOperand(Index)
11654       .addDisp(Disp, UseFPOffset ? 4 : 0)
11655       .addOperand(Segment)
11656       .setMemRefs(MMOBegin, MMOEnd);
11657
11658     // Check if there is enough room left to pull this argument.
11659     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11660       .addReg(OffsetReg)
11661       .addImm(MaxOffset + 8 - ArgSizeA8);
11662
11663     // Branch to "overflowMBB" if offset >= max
11664     // Fall through to "offsetMBB" otherwise
11665     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11666       .addMBB(overflowMBB);
11667   }
11668
11669   // In offsetMBB, emit code to use the reg_save_area.
11670   if (offsetMBB) {
11671     assert(OffsetReg != 0);
11672
11673     // Read the reg_save_area address.
11674     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11675     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11676       .addOperand(Base)
11677       .addOperand(Scale)
11678       .addOperand(Index)
11679       .addDisp(Disp, 16)
11680       .addOperand(Segment)
11681       .setMemRefs(MMOBegin, MMOEnd);
11682
11683     // Zero-extend the offset
11684     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11685       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11686         .addImm(0)
11687         .addReg(OffsetReg)
11688         .addImm(X86::sub_32bit);
11689
11690     // Add the offset to the reg_save_area to get the final address.
11691     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11692       .addReg(OffsetReg64)
11693       .addReg(RegSaveReg);
11694
11695     // Compute the offset for the next argument
11696     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11697     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11698       .addReg(OffsetReg)
11699       .addImm(UseFPOffset ? 16 : 8);
11700
11701     // Store it back into the va_list.
11702     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11703       .addOperand(Base)
11704       .addOperand(Scale)
11705       .addOperand(Index)
11706       .addDisp(Disp, UseFPOffset ? 4 : 0)
11707       .addOperand(Segment)
11708       .addReg(NextOffsetReg)
11709       .setMemRefs(MMOBegin, MMOEnd);
11710
11711     // Jump to endMBB
11712     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11713       .addMBB(endMBB);
11714   }
11715
11716   //
11717   // Emit code to use overflow area
11718   //
11719
11720   // Load the overflow_area address into a register.
11721   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11722   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11723     .addOperand(Base)
11724     .addOperand(Scale)
11725     .addOperand(Index)
11726     .addDisp(Disp, 8)
11727     .addOperand(Segment)
11728     .setMemRefs(MMOBegin, MMOEnd);
11729
11730   // If we need to align it, do so. Otherwise, just copy the address
11731   // to OverflowDestReg.
11732   if (NeedsAlign) {
11733     // Align the overflow address
11734     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11735     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11736
11737     // aligned_addr = (addr + (align-1)) & ~(align-1)
11738     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11739       .addReg(OverflowAddrReg)
11740       .addImm(Align-1);
11741
11742     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11743       .addReg(TmpReg)
11744       .addImm(~(uint64_t)(Align-1));
11745   } else {
11746     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11747       .addReg(OverflowAddrReg);
11748   }
11749
11750   // Compute the next overflow address after this argument.
11751   // (the overflow address should be kept 8-byte aligned)
11752   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11753   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11754     .addReg(OverflowDestReg)
11755     .addImm(ArgSizeA8);
11756
11757   // Store the new overflow address.
11758   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11759     .addOperand(Base)
11760     .addOperand(Scale)
11761     .addOperand(Index)
11762     .addDisp(Disp, 8)
11763     .addOperand(Segment)
11764     .addReg(NextAddrReg)
11765     .setMemRefs(MMOBegin, MMOEnd);
11766
11767   // If we branched, emit the PHI to the front of endMBB.
11768   if (offsetMBB) {
11769     BuildMI(*endMBB, endMBB->begin(), DL,
11770             TII->get(X86::PHI), DestReg)
11771       .addReg(OffsetDestReg).addMBB(offsetMBB)
11772       .addReg(OverflowDestReg).addMBB(overflowMBB);
11773   }
11774
11775   // Erase the pseudo instruction
11776   MI->eraseFromParent();
11777
11778   return endMBB;
11779 }
11780
11781 MachineBasicBlock *
11782 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11783                                                  MachineInstr *MI,
11784                                                  MachineBasicBlock *MBB) const {
11785   // Emit code to save XMM registers to the stack. The ABI says that the
11786   // number of registers to save is given in %al, so it's theoretically
11787   // possible to do an indirect jump trick to avoid saving all of them,
11788   // however this code takes a simpler approach and just executes all
11789   // of the stores if %al is non-zero. It's less code, and it's probably
11790   // easier on the hardware branch predictor, and stores aren't all that
11791   // expensive anyway.
11792
11793   // Create the new basic blocks. One block contains all the XMM stores,
11794   // and one block is the final destination regardless of whether any
11795   // stores were performed.
11796   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11797   MachineFunction *F = MBB->getParent();
11798   MachineFunction::iterator MBBIter = MBB;
11799   ++MBBIter;
11800   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11801   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11802   F->insert(MBBIter, XMMSaveMBB);
11803   F->insert(MBBIter, EndMBB);
11804
11805   // Transfer the remainder of MBB and its successor edges to EndMBB.
11806   EndMBB->splice(EndMBB->begin(), MBB,
11807                  llvm::next(MachineBasicBlock::iterator(MI)),
11808                  MBB->end());
11809   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11810
11811   // The original block will now fall through to the XMM save block.
11812   MBB->addSuccessor(XMMSaveMBB);
11813   // The XMMSaveMBB will fall through to the end block.
11814   XMMSaveMBB->addSuccessor(EndMBB);
11815
11816   // Now add the instructions.
11817   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11818   DebugLoc DL = MI->getDebugLoc();
11819
11820   unsigned CountReg = MI->getOperand(0).getReg();
11821   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11822   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11823
11824   if (!Subtarget->isTargetWin64()) {
11825     // If %al is 0, branch around the XMM save block.
11826     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11827     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11828     MBB->addSuccessor(EndMBB);
11829   }
11830
11831   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11832   // In the XMM save block, save all the XMM argument registers.
11833   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11834     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11835     MachineMemOperand *MMO =
11836       F->getMachineMemOperand(
11837           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11838         MachineMemOperand::MOStore,
11839         /*Size=*/16, /*Align=*/16);
11840     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11841       .addFrameIndex(RegSaveFrameIndex)
11842       .addImm(/*Scale=*/1)
11843       .addReg(/*IndexReg=*/0)
11844       .addImm(/*Disp=*/Offset)
11845       .addReg(/*Segment=*/0)
11846       .addReg(MI->getOperand(i).getReg())
11847       .addMemOperand(MMO);
11848   }
11849
11850   MI->eraseFromParent();   // The pseudo instruction is gone now.
11851
11852   return EndMBB;
11853 }
11854
11855 MachineBasicBlock *
11856 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11857                                      MachineBasicBlock *BB) const {
11858   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11859   DebugLoc DL = MI->getDebugLoc();
11860
11861   // To "insert" a SELECT_CC instruction, we actually have to insert the
11862   // diamond control-flow pattern.  The incoming instruction knows the
11863   // destination vreg to set, the condition code register to branch on, the
11864   // true/false values to select between, and a branch opcode to use.
11865   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11866   MachineFunction::iterator It = BB;
11867   ++It;
11868
11869   //  thisMBB:
11870   //  ...
11871   //   TrueVal = ...
11872   //   cmpTY ccX, r1, r2
11873   //   bCC copy1MBB
11874   //   fallthrough --> copy0MBB
11875   MachineBasicBlock *thisMBB = BB;
11876   MachineFunction *F = BB->getParent();
11877   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11878   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11879   F->insert(It, copy0MBB);
11880   F->insert(It, sinkMBB);
11881
11882   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11883   // live into the sink and copy blocks.
11884   if (!MI->killsRegister(X86::EFLAGS)) {
11885     copy0MBB->addLiveIn(X86::EFLAGS);
11886     sinkMBB->addLiveIn(X86::EFLAGS);
11887   }
11888
11889   // Transfer the remainder of BB and its successor edges to sinkMBB.
11890   sinkMBB->splice(sinkMBB->begin(), BB,
11891                   llvm::next(MachineBasicBlock::iterator(MI)),
11892                   BB->end());
11893   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11894
11895   // Add the true and fallthrough blocks as its successors.
11896   BB->addSuccessor(copy0MBB);
11897   BB->addSuccessor(sinkMBB);
11898
11899   // Create the conditional branch instruction.
11900   unsigned Opc =
11901     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11902   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11903
11904   //  copy0MBB:
11905   //   %FalseValue = ...
11906   //   # fallthrough to sinkMBB
11907   copy0MBB->addSuccessor(sinkMBB);
11908
11909   //  sinkMBB:
11910   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11911   //  ...
11912   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11913           TII->get(X86::PHI), MI->getOperand(0).getReg())
11914     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11915     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11916
11917   MI->eraseFromParent();   // The pseudo instruction is gone now.
11918   return sinkMBB;
11919 }
11920
11921 MachineBasicBlock *
11922 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11923                                         bool Is64Bit) const {
11924   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11925   DebugLoc DL = MI->getDebugLoc();
11926   MachineFunction *MF = BB->getParent();
11927   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11928
11929   assert(EnableSegmentedStacks);
11930
11931   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11932   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11933
11934   // BB:
11935   //  ... [Till the alloca]
11936   // If stacklet is not large enough, jump to mallocMBB
11937   //
11938   // bumpMBB:
11939   //  Allocate by subtracting from RSP
11940   //  Jump to continueMBB
11941   //
11942   // mallocMBB:
11943   //  Allocate by call to runtime
11944   //
11945   // continueMBB:
11946   //  ...
11947   //  [rest of original BB]
11948   //
11949
11950   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11951   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11952   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11953
11954   MachineRegisterInfo &MRI = MF->getRegInfo();
11955   const TargetRegisterClass *AddrRegClass =
11956     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11957
11958   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11959     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11960     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11961     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
11962     sizeVReg = MI->getOperand(1).getReg(),
11963     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11964
11965   MachineFunction::iterator MBBIter = BB;
11966   ++MBBIter;
11967
11968   MF->insert(MBBIter, bumpMBB);
11969   MF->insert(MBBIter, mallocMBB);
11970   MF->insert(MBBIter, continueMBB);
11971
11972   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11973                       (MachineBasicBlock::iterator(MI)), BB->end());
11974   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11975
11976   // Add code to the main basic block to check if the stack limit has been hit,
11977   // and if so, jump to mallocMBB otherwise to bumpMBB.
11978   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11979   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
11980     .addReg(tmpSPVReg).addReg(sizeVReg);
11981   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11982     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11983     .addReg(SPLimitVReg);
11984   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11985
11986   // bumpMBB simply decreases the stack pointer, since we know the current
11987   // stacklet has enough space.
11988   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11989     .addReg(SPLimitVReg);
11990   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11991     .addReg(SPLimitVReg);
11992   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11993
11994   // Calls into a routine in libgcc to allocate more space from the heap.
11995   if (Is64Bit) {
11996     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11997       .addReg(sizeVReg);
11998     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11999     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12000   } else {
12001     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12002       .addImm(12);
12003     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12004     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12005       .addExternalSymbol("__morestack_allocate_stack_space");
12006   }
12007
12008   if (!Is64Bit)
12009     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12010       .addImm(16);
12011
12012   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12013     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12014   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12015
12016   // Set up the CFG correctly.
12017   BB->addSuccessor(bumpMBB);
12018   BB->addSuccessor(mallocMBB);
12019   mallocMBB->addSuccessor(continueMBB);
12020   bumpMBB->addSuccessor(continueMBB);
12021
12022   // Take care of the PHI nodes.
12023   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12024           MI->getOperand(0).getReg())
12025     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12026     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12027
12028   // Delete the original pseudo instruction.
12029   MI->eraseFromParent();
12030
12031   // And we're done.
12032   return continueMBB;
12033 }
12034
12035 MachineBasicBlock *
12036 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12037                                           MachineBasicBlock *BB) const {
12038   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12039   DebugLoc DL = MI->getDebugLoc();
12040
12041   assert(!Subtarget->isTargetEnvMacho());
12042
12043   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12044   // non-trivial part is impdef of ESP.
12045
12046   if (Subtarget->isTargetWin64()) {
12047     if (Subtarget->isTargetCygMing()) {
12048       // ___chkstk(Mingw64):
12049       // Clobbers R10, R11, RAX and EFLAGS.
12050       // Updates RSP.
12051       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12052         .addExternalSymbol("___chkstk")
12053         .addReg(X86::RAX, RegState::Implicit)
12054         .addReg(X86::RSP, RegState::Implicit)
12055         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12056         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12057         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12058     } else {
12059       // __chkstk(MSVCRT): does not update stack pointer.
12060       // Clobbers R10, R11 and EFLAGS.
12061       // FIXME: RAX(allocated size) might be reused and not killed.
12062       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12063         .addExternalSymbol("__chkstk")
12064         .addReg(X86::RAX, RegState::Implicit)
12065         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12066       // RAX has the offset to subtracted from RSP.
12067       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12068         .addReg(X86::RSP)
12069         .addReg(X86::RAX);
12070     }
12071   } else {
12072     const char *StackProbeSymbol =
12073       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12074
12075     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12076       .addExternalSymbol(StackProbeSymbol)
12077       .addReg(X86::EAX, RegState::Implicit)
12078       .addReg(X86::ESP, RegState::Implicit)
12079       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12080       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12081       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12082   }
12083
12084   MI->eraseFromParent();   // The pseudo instruction is gone now.
12085   return BB;
12086 }
12087
12088 MachineBasicBlock *
12089 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12090                                       MachineBasicBlock *BB) const {
12091   // This is pretty easy.  We're taking the value that we received from
12092   // our load from the relocation, sticking it in either RDI (x86-64)
12093   // or EAX and doing an indirect call.  The return value will then
12094   // be in the normal return register.
12095   const X86InstrInfo *TII
12096     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12097   DebugLoc DL = MI->getDebugLoc();
12098   MachineFunction *F = BB->getParent();
12099
12100   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12101   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12102
12103   if (Subtarget->is64Bit()) {
12104     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12105                                       TII->get(X86::MOV64rm), X86::RDI)
12106     .addReg(X86::RIP)
12107     .addImm(0).addReg(0)
12108     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12109                       MI->getOperand(3).getTargetFlags())
12110     .addReg(0);
12111     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12112     addDirectMem(MIB, X86::RDI);
12113   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12114     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12115                                       TII->get(X86::MOV32rm), X86::EAX)
12116     .addReg(0)
12117     .addImm(0).addReg(0)
12118     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12119                       MI->getOperand(3).getTargetFlags())
12120     .addReg(0);
12121     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12122     addDirectMem(MIB, X86::EAX);
12123   } else {
12124     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12125                                       TII->get(X86::MOV32rm), X86::EAX)
12126     .addReg(TII->getGlobalBaseReg(F))
12127     .addImm(0).addReg(0)
12128     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12129                       MI->getOperand(3).getTargetFlags())
12130     .addReg(0);
12131     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12132     addDirectMem(MIB, X86::EAX);
12133   }
12134
12135   MI->eraseFromParent(); // The pseudo instruction is gone now.
12136   return BB;
12137 }
12138
12139 MachineBasicBlock *
12140 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12141                                                MachineBasicBlock *BB) const {
12142   switch (MI->getOpcode()) {
12143   default: assert(0 && "Unexpected instr type to insert");
12144   case X86::TAILJMPd64:
12145   case X86::TAILJMPr64:
12146   case X86::TAILJMPm64:
12147     assert(0 && "TAILJMP64 would not be touched here.");
12148   case X86::TCRETURNdi64:
12149   case X86::TCRETURNri64:
12150   case X86::TCRETURNmi64:
12151     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12152     // On AMD64, additional defs should be added before register allocation.
12153     if (!Subtarget->isTargetWin64()) {
12154       MI->addRegisterDefined(X86::RSI);
12155       MI->addRegisterDefined(X86::RDI);
12156       MI->addRegisterDefined(X86::XMM6);
12157       MI->addRegisterDefined(X86::XMM7);
12158       MI->addRegisterDefined(X86::XMM8);
12159       MI->addRegisterDefined(X86::XMM9);
12160       MI->addRegisterDefined(X86::XMM10);
12161       MI->addRegisterDefined(X86::XMM11);
12162       MI->addRegisterDefined(X86::XMM12);
12163       MI->addRegisterDefined(X86::XMM13);
12164       MI->addRegisterDefined(X86::XMM14);
12165       MI->addRegisterDefined(X86::XMM15);
12166     }
12167     return BB;
12168   case X86::WIN_ALLOCA:
12169     return EmitLoweredWinAlloca(MI, BB);
12170   case X86::SEG_ALLOCA_32:
12171     return EmitLoweredSegAlloca(MI, BB, false);
12172   case X86::SEG_ALLOCA_64:
12173     return EmitLoweredSegAlloca(MI, BB, true);
12174   case X86::TLSCall_32:
12175   case X86::TLSCall_64:
12176     return EmitLoweredTLSCall(MI, BB);
12177   case X86::CMOV_GR8:
12178   case X86::CMOV_FR32:
12179   case X86::CMOV_FR64:
12180   case X86::CMOV_V4F32:
12181   case X86::CMOV_V2F64:
12182   case X86::CMOV_V2I64:
12183   case X86::CMOV_V8F32:
12184   case X86::CMOV_V4F64:
12185   case X86::CMOV_V4I64:
12186   case X86::CMOV_GR16:
12187   case X86::CMOV_GR32:
12188   case X86::CMOV_RFP32:
12189   case X86::CMOV_RFP64:
12190   case X86::CMOV_RFP80:
12191     return EmitLoweredSelect(MI, BB);
12192
12193   case X86::FP32_TO_INT16_IN_MEM:
12194   case X86::FP32_TO_INT32_IN_MEM:
12195   case X86::FP32_TO_INT64_IN_MEM:
12196   case X86::FP64_TO_INT16_IN_MEM:
12197   case X86::FP64_TO_INT32_IN_MEM:
12198   case X86::FP64_TO_INT64_IN_MEM:
12199   case X86::FP80_TO_INT16_IN_MEM:
12200   case X86::FP80_TO_INT32_IN_MEM:
12201   case X86::FP80_TO_INT64_IN_MEM: {
12202     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12203     DebugLoc DL = MI->getDebugLoc();
12204
12205     // Change the floating point control register to use "round towards zero"
12206     // mode when truncating to an integer value.
12207     MachineFunction *F = BB->getParent();
12208     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12209     addFrameReference(BuildMI(*BB, MI, DL,
12210                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12211
12212     // Load the old value of the high byte of the control word...
12213     unsigned OldCW =
12214       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12215     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12216                       CWFrameIdx);
12217
12218     // Set the high part to be round to zero...
12219     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12220       .addImm(0xC7F);
12221
12222     // Reload the modified control word now...
12223     addFrameReference(BuildMI(*BB, MI, DL,
12224                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12225
12226     // Restore the memory image of control word to original value
12227     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12228       .addReg(OldCW);
12229
12230     // Get the X86 opcode to use.
12231     unsigned Opc;
12232     switch (MI->getOpcode()) {
12233     default: llvm_unreachable("illegal opcode!");
12234     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12235     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12236     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12237     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12238     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12239     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12240     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12241     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12242     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12243     }
12244
12245     X86AddressMode AM;
12246     MachineOperand &Op = MI->getOperand(0);
12247     if (Op.isReg()) {
12248       AM.BaseType = X86AddressMode::RegBase;
12249       AM.Base.Reg = Op.getReg();
12250     } else {
12251       AM.BaseType = X86AddressMode::FrameIndexBase;
12252       AM.Base.FrameIndex = Op.getIndex();
12253     }
12254     Op = MI->getOperand(1);
12255     if (Op.isImm())
12256       AM.Scale = Op.getImm();
12257     Op = MI->getOperand(2);
12258     if (Op.isImm())
12259       AM.IndexReg = Op.getImm();
12260     Op = MI->getOperand(3);
12261     if (Op.isGlobal()) {
12262       AM.GV = Op.getGlobal();
12263     } else {
12264       AM.Disp = Op.getImm();
12265     }
12266     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12267                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12268
12269     // Reload the original control word now.
12270     addFrameReference(BuildMI(*BB, MI, DL,
12271                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12272
12273     MI->eraseFromParent();   // The pseudo instruction is gone now.
12274     return BB;
12275   }
12276     // String/text processing lowering.
12277   case X86::PCMPISTRM128REG:
12278   case X86::VPCMPISTRM128REG:
12279     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12280   case X86::PCMPISTRM128MEM:
12281   case X86::VPCMPISTRM128MEM:
12282     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12283   case X86::PCMPESTRM128REG:
12284   case X86::VPCMPESTRM128REG:
12285     return EmitPCMP(MI, BB, 5, false /* in mem */);
12286   case X86::PCMPESTRM128MEM:
12287   case X86::VPCMPESTRM128MEM:
12288     return EmitPCMP(MI, BB, 5, true /* in mem */);
12289
12290     // Thread synchronization.
12291   case X86::MONITOR:
12292     return EmitMonitor(MI, BB);
12293   case X86::MWAIT:
12294     return EmitMwait(MI, BB);
12295
12296     // Atomic Lowering.
12297   case X86::ATOMAND32:
12298     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12299                                                X86::AND32ri, X86::MOV32rm,
12300                                                X86::LCMPXCHG32,
12301                                                X86::NOT32r, X86::EAX,
12302                                                X86::GR32RegisterClass);
12303   case X86::ATOMOR32:
12304     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12305                                                X86::OR32ri, X86::MOV32rm,
12306                                                X86::LCMPXCHG32,
12307                                                X86::NOT32r, X86::EAX,
12308                                                X86::GR32RegisterClass);
12309   case X86::ATOMXOR32:
12310     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12311                                                X86::XOR32ri, X86::MOV32rm,
12312                                                X86::LCMPXCHG32,
12313                                                X86::NOT32r, X86::EAX,
12314                                                X86::GR32RegisterClass);
12315   case X86::ATOMNAND32:
12316     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12317                                                X86::AND32ri, X86::MOV32rm,
12318                                                X86::LCMPXCHG32,
12319                                                X86::NOT32r, X86::EAX,
12320                                                X86::GR32RegisterClass, true);
12321   case X86::ATOMMIN32:
12322     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12323   case X86::ATOMMAX32:
12324     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12325   case X86::ATOMUMIN32:
12326     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12327   case X86::ATOMUMAX32:
12328     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12329
12330   case X86::ATOMAND16:
12331     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12332                                                X86::AND16ri, X86::MOV16rm,
12333                                                X86::LCMPXCHG16,
12334                                                X86::NOT16r, X86::AX,
12335                                                X86::GR16RegisterClass);
12336   case X86::ATOMOR16:
12337     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12338                                                X86::OR16ri, X86::MOV16rm,
12339                                                X86::LCMPXCHG16,
12340                                                X86::NOT16r, X86::AX,
12341                                                X86::GR16RegisterClass);
12342   case X86::ATOMXOR16:
12343     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12344                                                X86::XOR16ri, X86::MOV16rm,
12345                                                X86::LCMPXCHG16,
12346                                                X86::NOT16r, X86::AX,
12347                                                X86::GR16RegisterClass);
12348   case X86::ATOMNAND16:
12349     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12350                                                X86::AND16ri, X86::MOV16rm,
12351                                                X86::LCMPXCHG16,
12352                                                X86::NOT16r, X86::AX,
12353                                                X86::GR16RegisterClass, true);
12354   case X86::ATOMMIN16:
12355     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12356   case X86::ATOMMAX16:
12357     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12358   case X86::ATOMUMIN16:
12359     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12360   case X86::ATOMUMAX16:
12361     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12362
12363   case X86::ATOMAND8:
12364     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12365                                                X86::AND8ri, X86::MOV8rm,
12366                                                X86::LCMPXCHG8,
12367                                                X86::NOT8r, X86::AL,
12368                                                X86::GR8RegisterClass);
12369   case X86::ATOMOR8:
12370     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12371                                                X86::OR8ri, X86::MOV8rm,
12372                                                X86::LCMPXCHG8,
12373                                                X86::NOT8r, X86::AL,
12374                                                X86::GR8RegisterClass);
12375   case X86::ATOMXOR8:
12376     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12377                                                X86::XOR8ri, X86::MOV8rm,
12378                                                X86::LCMPXCHG8,
12379                                                X86::NOT8r, X86::AL,
12380                                                X86::GR8RegisterClass);
12381   case X86::ATOMNAND8:
12382     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12383                                                X86::AND8ri, X86::MOV8rm,
12384                                                X86::LCMPXCHG8,
12385                                                X86::NOT8r, X86::AL,
12386                                                X86::GR8RegisterClass, true);
12387   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12388   // This group is for 64-bit host.
12389   case X86::ATOMAND64:
12390     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12391                                                X86::AND64ri32, X86::MOV64rm,
12392                                                X86::LCMPXCHG64,
12393                                                X86::NOT64r, X86::RAX,
12394                                                X86::GR64RegisterClass);
12395   case X86::ATOMOR64:
12396     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12397                                                X86::OR64ri32, X86::MOV64rm,
12398                                                X86::LCMPXCHG64,
12399                                                X86::NOT64r, X86::RAX,
12400                                                X86::GR64RegisterClass);
12401   case X86::ATOMXOR64:
12402     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12403                                                X86::XOR64ri32, X86::MOV64rm,
12404                                                X86::LCMPXCHG64,
12405                                                X86::NOT64r, X86::RAX,
12406                                                X86::GR64RegisterClass);
12407   case X86::ATOMNAND64:
12408     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12409                                                X86::AND64ri32, X86::MOV64rm,
12410                                                X86::LCMPXCHG64,
12411                                                X86::NOT64r, X86::RAX,
12412                                                X86::GR64RegisterClass, true);
12413   case X86::ATOMMIN64:
12414     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12415   case X86::ATOMMAX64:
12416     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12417   case X86::ATOMUMIN64:
12418     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12419   case X86::ATOMUMAX64:
12420     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12421
12422   // This group does 64-bit operations on a 32-bit host.
12423   case X86::ATOMAND6432:
12424     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12425                                                X86::AND32rr, X86::AND32rr,
12426                                                X86::AND32ri, X86::AND32ri,
12427                                                false);
12428   case X86::ATOMOR6432:
12429     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12430                                                X86::OR32rr, X86::OR32rr,
12431                                                X86::OR32ri, X86::OR32ri,
12432                                                false);
12433   case X86::ATOMXOR6432:
12434     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12435                                                X86::XOR32rr, X86::XOR32rr,
12436                                                X86::XOR32ri, X86::XOR32ri,
12437                                                false);
12438   case X86::ATOMNAND6432:
12439     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12440                                                X86::AND32rr, X86::AND32rr,
12441                                                X86::AND32ri, X86::AND32ri,
12442                                                true);
12443   case X86::ATOMADD6432:
12444     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12445                                                X86::ADD32rr, X86::ADC32rr,
12446                                                X86::ADD32ri, X86::ADC32ri,
12447                                                false);
12448   case X86::ATOMSUB6432:
12449     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12450                                                X86::SUB32rr, X86::SBB32rr,
12451                                                X86::SUB32ri, X86::SBB32ri,
12452                                                false);
12453   case X86::ATOMSWAP6432:
12454     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12455                                                X86::MOV32rr, X86::MOV32rr,
12456                                                X86::MOV32ri, X86::MOV32ri,
12457                                                false);
12458   case X86::VASTART_SAVE_XMM_REGS:
12459     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12460
12461   case X86::VAARG_64:
12462     return EmitVAARG64WithCustomInserter(MI, BB);
12463   }
12464 }
12465
12466 //===----------------------------------------------------------------------===//
12467 //                           X86 Optimization Hooks
12468 //===----------------------------------------------------------------------===//
12469
12470 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12471                                                        const APInt &Mask,
12472                                                        APInt &KnownZero,
12473                                                        APInt &KnownOne,
12474                                                        const SelectionDAG &DAG,
12475                                                        unsigned Depth) const {
12476   unsigned Opc = Op.getOpcode();
12477   assert((Opc >= ISD::BUILTIN_OP_END ||
12478           Opc == ISD::INTRINSIC_WO_CHAIN ||
12479           Opc == ISD::INTRINSIC_W_CHAIN ||
12480           Opc == ISD::INTRINSIC_VOID) &&
12481          "Should use MaskedValueIsZero if you don't know whether Op"
12482          " is a target node!");
12483
12484   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12485   switch (Opc) {
12486   default: break;
12487   case X86ISD::ADD:
12488   case X86ISD::SUB:
12489   case X86ISD::ADC:
12490   case X86ISD::SBB:
12491   case X86ISD::SMUL:
12492   case X86ISD::UMUL:
12493   case X86ISD::INC:
12494   case X86ISD::DEC:
12495   case X86ISD::OR:
12496   case X86ISD::XOR:
12497   case X86ISD::AND:
12498     // These nodes' second result is a boolean.
12499     if (Op.getResNo() == 0)
12500       break;
12501     // Fallthrough
12502   case X86ISD::SETCC:
12503     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12504                                        Mask.getBitWidth() - 1);
12505     break;
12506   case ISD::INTRINSIC_WO_CHAIN: {
12507     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12508     unsigned NumLoBits = 0;
12509     switch (IntId) {
12510     default: break;
12511     case Intrinsic::x86_sse_movmsk_ps:
12512     case Intrinsic::x86_avx_movmsk_ps_256:
12513     case Intrinsic::x86_sse2_movmsk_pd:
12514     case Intrinsic::x86_avx_movmsk_pd_256:
12515     case Intrinsic::x86_mmx_pmovmskb:
12516     case Intrinsic::x86_sse2_pmovmskb_128: {
12517       // High bits of movmskp{s|d}, pmovmskb are known zero.
12518       switch (IntId) {
12519         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12520         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12521         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12522         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12523         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12524         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12525       }
12526       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12527                                         Mask.getBitWidth() - NumLoBits);
12528       break;
12529     }
12530     }
12531     break;
12532   }
12533   }
12534 }
12535
12536 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12537                                                          unsigned Depth) const {
12538   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12539   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12540     return Op.getValueType().getScalarType().getSizeInBits();
12541
12542   // Fallback case.
12543   return 1;
12544 }
12545
12546 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12547 /// node is a GlobalAddress + offset.
12548 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12549                                        const GlobalValue* &GA,
12550                                        int64_t &Offset) const {
12551   if (N->getOpcode() == X86ISD::Wrapper) {
12552     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12553       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12554       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12555       return true;
12556     }
12557   }
12558   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12559 }
12560
12561 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12562 /// same as extracting the high 128-bit part of 256-bit vector and then
12563 /// inserting the result into the low part of a new 256-bit vector
12564 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12565   EVT VT = SVOp->getValueType(0);
12566   int NumElems = VT.getVectorNumElements();
12567
12568   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12569   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12570     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12571         SVOp->getMaskElt(j) >= 0)
12572       return false;
12573
12574   return true;
12575 }
12576
12577 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12578 /// same as extracting the low 128-bit part of 256-bit vector and then
12579 /// inserting the result into the high part of a new 256-bit vector
12580 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12581   EVT VT = SVOp->getValueType(0);
12582   int NumElems = VT.getVectorNumElements();
12583
12584   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12585   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12586     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12587         SVOp->getMaskElt(j) >= 0)
12588       return false;
12589
12590   return true;
12591 }
12592
12593 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12594 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12595                                         TargetLowering::DAGCombinerInfo &DCI) {
12596   DebugLoc dl = N->getDebugLoc();
12597   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12598   SDValue V1 = SVOp->getOperand(0);
12599   SDValue V2 = SVOp->getOperand(1);
12600   EVT VT = SVOp->getValueType(0);
12601   int NumElems = VT.getVectorNumElements();
12602
12603   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12604       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12605     //
12606     //                   0,0,0,...
12607     //                      |
12608     //    V      UNDEF    BUILD_VECTOR    UNDEF
12609     //     \      /           \           /
12610     //  CONCAT_VECTOR         CONCAT_VECTOR
12611     //         \                  /
12612     //          \                /
12613     //          RESULT: V + zero extended
12614     //
12615     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12616         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12617         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12618       return SDValue();
12619
12620     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12621       return SDValue();
12622
12623     // To match the shuffle mask, the first half of the mask should
12624     // be exactly the first vector, and all the rest a splat with the
12625     // first element of the second one.
12626     for (int i = 0; i < NumElems/2; ++i)
12627       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12628           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12629         return SDValue();
12630
12631     // Emit a zeroed vector and insert the desired subvector on its
12632     // first half.
12633     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12634     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12635                          DAG.getConstant(0, MVT::i32), DAG, dl);
12636     return DCI.CombineTo(N, InsV);
12637   }
12638
12639   //===--------------------------------------------------------------------===//
12640   // Combine some shuffles into subvector extracts and inserts:
12641   //
12642
12643   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12644   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12645     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12646                                     DAG, dl);
12647     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12648                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12649     return DCI.CombineTo(N, InsV);
12650   }
12651
12652   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12653   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12654     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12655     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12656                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12657     return DCI.CombineTo(N, InsV);
12658   }
12659
12660   return SDValue();
12661 }
12662
12663 /// PerformShuffleCombine - Performs several different shuffle combines.
12664 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12665                                      TargetLowering::DAGCombinerInfo &DCI,
12666                                      const X86Subtarget *Subtarget) {
12667   DebugLoc dl = N->getDebugLoc();
12668   EVT VT = N->getValueType(0);
12669
12670   // Don't create instructions with illegal types after legalize types has run.
12671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12672   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12673     return SDValue();
12674
12675   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12676   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12677       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12678     return PerformShuffleCombine256(N, DAG, DCI);
12679
12680   // Only handle 128 wide vector from here on.
12681   if (VT.getSizeInBits() != 128)
12682     return SDValue();
12683
12684   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12685   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12686   // consecutive, non-overlapping, and in the right order.
12687   SmallVector<SDValue, 16> Elts;
12688   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12689     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12690
12691   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12692 }
12693
12694 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12695 /// generation and convert it from being a bunch of shuffles and extracts
12696 /// to a simple store and scalar loads to extract the elements.
12697 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12698                                                 const TargetLowering &TLI) {
12699   SDValue InputVector = N->getOperand(0);
12700
12701   // Only operate on vectors of 4 elements, where the alternative shuffling
12702   // gets to be more expensive.
12703   if (InputVector.getValueType() != MVT::v4i32)
12704     return SDValue();
12705
12706   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12707   // single use which is a sign-extend or zero-extend, and all elements are
12708   // used.
12709   SmallVector<SDNode *, 4> Uses;
12710   unsigned ExtractedElements = 0;
12711   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12712        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12713     if (UI.getUse().getResNo() != InputVector.getResNo())
12714       return SDValue();
12715
12716     SDNode *Extract = *UI;
12717     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12718       return SDValue();
12719
12720     if (Extract->getValueType(0) != MVT::i32)
12721       return SDValue();
12722     if (!Extract->hasOneUse())
12723       return SDValue();
12724     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12725         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12726       return SDValue();
12727     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12728       return SDValue();
12729
12730     // Record which element was extracted.
12731     ExtractedElements |=
12732       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12733
12734     Uses.push_back(Extract);
12735   }
12736
12737   // If not all the elements were used, this may not be worthwhile.
12738   if (ExtractedElements != 15)
12739     return SDValue();
12740
12741   // Ok, we've now decided to do the transformation.
12742   DebugLoc dl = InputVector.getDebugLoc();
12743
12744   // Store the value to a temporary stack slot.
12745   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12746   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12747                             MachinePointerInfo(), false, false, 0);
12748
12749   // Replace each use (extract) with a load of the appropriate element.
12750   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12751        UE = Uses.end(); UI != UE; ++UI) {
12752     SDNode *Extract = *UI;
12753
12754     // cOMpute the element's address.
12755     SDValue Idx = Extract->getOperand(1);
12756     unsigned EltSize =
12757         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12758     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12759     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12760
12761     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12762                                      StackPtr, OffsetVal);
12763
12764     // Load the scalar.
12765     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12766                                      ScalarAddr, MachinePointerInfo(),
12767                                      false, false, 0);
12768
12769     // Replace the exact with the load.
12770     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12771   }
12772
12773   // The replacement was made in place; don't return anything.
12774   return SDValue();
12775 }
12776
12777 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12778 /// nodes.
12779 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12780                                     const X86Subtarget *Subtarget) {
12781   DebugLoc DL = N->getDebugLoc();
12782   SDValue Cond = N->getOperand(0);
12783   // Get the LHS/RHS of the select.
12784   SDValue LHS = N->getOperand(1);
12785   SDValue RHS = N->getOperand(2);
12786   EVT VT = LHS.getValueType();
12787
12788   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12789   // instructions match the semantics of the common C idiom x<y?x:y but not
12790   // x<=y?x:y, because of how they handle negative zero (which can be
12791   // ignored in unsafe-math mode).
12792   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12793       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12794       (Subtarget->hasXMMInt() ||
12795        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12796     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12797
12798     unsigned Opcode = 0;
12799     // Check for x CC y ? x : y.
12800     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12801         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12802       switch (CC) {
12803       default: break;
12804       case ISD::SETULT:
12805         // Converting this to a min would handle NaNs incorrectly, and swapping
12806         // the operands would cause it to handle comparisons between positive
12807         // and negative zero incorrectly.
12808         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12809           if (!UnsafeFPMath &&
12810               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12811             break;
12812           std::swap(LHS, RHS);
12813         }
12814         Opcode = X86ISD::FMIN;
12815         break;
12816       case ISD::SETOLE:
12817         // Converting this to a min would handle comparisons between positive
12818         // and negative zero incorrectly.
12819         if (!UnsafeFPMath &&
12820             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12821           break;
12822         Opcode = X86ISD::FMIN;
12823         break;
12824       case ISD::SETULE:
12825         // Converting this to a min would handle both negative zeros and NaNs
12826         // incorrectly, but we can swap the operands to fix both.
12827         std::swap(LHS, RHS);
12828       case ISD::SETOLT:
12829       case ISD::SETLT:
12830       case ISD::SETLE:
12831         Opcode = X86ISD::FMIN;
12832         break;
12833
12834       case ISD::SETOGE:
12835         // Converting this to a max would handle comparisons between positive
12836         // and negative zero incorrectly.
12837         if (!UnsafeFPMath &&
12838             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12839           break;
12840         Opcode = X86ISD::FMAX;
12841         break;
12842       case ISD::SETUGT:
12843         // Converting this to a max would handle NaNs incorrectly, and swapping
12844         // the operands would cause it to handle comparisons between positive
12845         // and negative zero incorrectly.
12846         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12847           if (!UnsafeFPMath &&
12848               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12849             break;
12850           std::swap(LHS, RHS);
12851         }
12852         Opcode = X86ISD::FMAX;
12853         break;
12854       case ISD::SETUGE:
12855         // Converting this to a max would handle both negative zeros and NaNs
12856         // incorrectly, but we can swap the operands to fix both.
12857         std::swap(LHS, RHS);
12858       case ISD::SETOGT:
12859       case ISD::SETGT:
12860       case ISD::SETGE:
12861         Opcode = X86ISD::FMAX;
12862         break;
12863       }
12864     // Check for x CC y ? y : x -- a min/max with reversed arms.
12865     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12866                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12867       switch (CC) {
12868       default: break;
12869       case ISD::SETOGE:
12870         // Converting this to a min would handle comparisons between positive
12871         // and negative zero incorrectly, and swapping the operands would
12872         // cause it to handle NaNs incorrectly.
12873         if (!UnsafeFPMath &&
12874             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12875           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12876             break;
12877           std::swap(LHS, RHS);
12878         }
12879         Opcode = X86ISD::FMIN;
12880         break;
12881       case ISD::SETUGT:
12882         // Converting this to a min would handle NaNs incorrectly.
12883         if (!UnsafeFPMath &&
12884             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12885           break;
12886         Opcode = X86ISD::FMIN;
12887         break;
12888       case ISD::SETUGE:
12889         // Converting this to a min would handle both negative zeros and NaNs
12890         // incorrectly, but we can swap the operands to fix both.
12891         std::swap(LHS, RHS);
12892       case ISD::SETOGT:
12893       case ISD::SETGT:
12894       case ISD::SETGE:
12895         Opcode = X86ISD::FMIN;
12896         break;
12897
12898       case ISD::SETULT:
12899         // Converting this to a max would handle NaNs incorrectly.
12900         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12901           break;
12902         Opcode = X86ISD::FMAX;
12903         break;
12904       case ISD::SETOLE:
12905         // Converting this to a max would handle comparisons between positive
12906         // and negative zero incorrectly, and swapping the operands would
12907         // cause it to handle NaNs incorrectly.
12908         if (!UnsafeFPMath &&
12909             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12910           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12911             break;
12912           std::swap(LHS, RHS);
12913         }
12914         Opcode = X86ISD::FMAX;
12915         break;
12916       case ISD::SETULE:
12917         // Converting this to a max would handle both negative zeros and NaNs
12918         // incorrectly, but we can swap the operands to fix both.
12919         std::swap(LHS, RHS);
12920       case ISD::SETOLT:
12921       case ISD::SETLT:
12922       case ISD::SETLE:
12923         Opcode = X86ISD::FMAX;
12924         break;
12925       }
12926     }
12927
12928     if (Opcode)
12929       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12930   }
12931
12932   // If this is a select between two integer constants, try to do some
12933   // optimizations.
12934   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12935     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12936       // Don't do this for crazy integer types.
12937       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12938         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12939         // so that TrueC (the true value) is larger than FalseC.
12940         bool NeedsCondInvert = false;
12941
12942         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12943             // Efficiently invertible.
12944             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12945              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12946               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12947           NeedsCondInvert = true;
12948           std::swap(TrueC, FalseC);
12949         }
12950
12951         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12952         if (FalseC->getAPIntValue() == 0 &&
12953             TrueC->getAPIntValue().isPowerOf2()) {
12954           if (NeedsCondInvert) // Invert the condition if needed.
12955             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12956                                DAG.getConstant(1, Cond.getValueType()));
12957
12958           // Zero extend the condition if needed.
12959           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12960
12961           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12962           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12963                              DAG.getConstant(ShAmt, MVT::i8));
12964         }
12965
12966         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12967         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12968           if (NeedsCondInvert) // Invert the condition if needed.
12969             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12970                                DAG.getConstant(1, Cond.getValueType()));
12971
12972           // Zero extend the condition if needed.
12973           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12974                              FalseC->getValueType(0), Cond);
12975           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12976                              SDValue(FalseC, 0));
12977         }
12978
12979         // Optimize cases that will turn into an LEA instruction.  This requires
12980         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12981         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12982           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12983           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12984
12985           bool isFastMultiplier = false;
12986           if (Diff < 10) {
12987             switch ((unsigned char)Diff) {
12988               default: break;
12989               case 1:  // result = add base, cond
12990               case 2:  // result = lea base(    , cond*2)
12991               case 3:  // result = lea base(cond, cond*2)
12992               case 4:  // result = lea base(    , cond*4)
12993               case 5:  // result = lea base(cond, cond*4)
12994               case 8:  // result = lea base(    , cond*8)
12995               case 9:  // result = lea base(cond, cond*8)
12996                 isFastMultiplier = true;
12997                 break;
12998             }
12999           }
13000
13001           if (isFastMultiplier) {
13002             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13003             if (NeedsCondInvert) // Invert the condition if needed.
13004               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13005                                  DAG.getConstant(1, Cond.getValueType()));
13006
13007             // Zero extend the condition if needed.
13008             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13009                                Cond);
13010             // Scale the condition by the difference.
13011             if (Diff != 1)
13012               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13013                                  DAG.getConstant(Diff, Cond.getValueType()));
13014
13015             // Add the base if non-zero.
13016             if (FalseC->getAPIntValue() != 0)
13017               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13018                                  SDValue(FalseC, 0));
13019             return Cond;
13020           }
13021         }
13022       }
13023   }
13024
13025   return SDValue();
13026 }
13027
13028 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13029 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13030                                   TargetLowering::DAGCombinerInfo &DCI) {
13031   DebugLoc DL = N->getDebugLoc();
13032
13033   // If the flag operand isn't dead, don't touch this CMOV.
13034   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13035     return SDValue();
13036
13037   SDValue FalseOp = N->getOperand(0);
13038   SDValue TrueOp = N->getOperand(1);
13039   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13040   SDValue Cond = N->getOperand(3);
13041   if (CC == X86::COND_E || CC == X86::COND_NE) {
13042     switch (Cond.getOpcode()) {
13043     default: break;
13044     case X86ISD::BSR:
13045     case X86ISD::BSF:
13046       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13047       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13048         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13049     }
13050   }
13051
13052   // If this is a select between two integer constants, try to do some
13053   // optimizations.  Note that the operands are ordered the opposite of SELECT
13054   // operands.
13055   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13056     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13057       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13058       // larger than FalseC (the false value).
13059       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13060         CC = X86::GetOppositeBranchCondition(CC);
13061         std::swap(TrueC, FalseC);
13062       }
13063
13064       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13065       // This is efficient for any integer data type (including i8/i16) and
13066       // shift amount.
13067       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13068         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13069                            DAG.getConstant(CC, MVT::i8), Cond);
13070
13071         // Zero extend the condition if needed.
13072         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13073
13074         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13075         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13076                            DAG.getConstant(ShAmt, MVT::i8));
13077         if (N->getNumValues() == 2)  // Dead flag value?
13078           return DCI.CombineTo(N, Cond, SDValue());
13079         return Cond;
13080       }
13081
13082       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13083       // for any integer data type, including i8/i16.
13084       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13085         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13086                            DAG.getConstant(CC, MVT::i8), Cond);
13087
13088         // Zero extend the condition if needed.
13089         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13090                            FalseC->getValueType(0), Cond);
13091         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13092                            SDValue(FalseC, 0));
13093
13094         if (N->getNumValues() == 2)  // Dead flag value?
13095           return DCI.CombineTo(N, Cond, SDValue());
13096         return Cond;
13097       }
13098
13099       // Optimize cases that will turn into an LEA instruction.  This requires
13100       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13101       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13102         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13103         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13104
13105         bool isFastMultiplier = false;
13106         if (Diff < 10) {
13107           switch ((unsigned char)Diff) {
13108           default: break;
13109           case 1:  // result = add base, cond
13110           case 2:  // result = lea base(    , cond*2)
13111           case 3:  // result = lea base(cond, cond*2)
13112           case 4:  // result = lea base(    , cond*4)
13113           case 5:  // result = lea base(cond, cond*4)
13114           case 8:  // result = lea base(    , cond*8)
13115           case 9:  // result = lea base(cond, cond*8)
13116             isFastMultiplier = true;
13117             break;
13118           }
13119         }
13120
13121         if (isFastMultiplier) {
13122           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13123           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13124                              DAG.getConstant(CC, MVT::i8), Cond);
13125           // Zero extend the condition if needed.
13126           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13127                              Cond);
13128           // Scale the condition by the difference.
13129           if (Diff != 1)
13130             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13131                                DAG.getConstant(Diff, Cond.getValueType()));
13132
13133           // Add the base if non-zero.
13134           if (FalseC->getAPIntValue() != 0)
13135             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13136                                SDValue(FalseC, 0));
13137           if (N->getNumValues() == 2)  // Dead flag value?
13138             return DCI.CombineTo(N, Cond, SDValue());
13139           return Cond;
13140         }
13141       }
13142     }
13143   }
13144   return SDValue();
13145 }
13146
13147
13148 /// PerformMulCombine - Optimize a single multiply with constant into two
13149 /// in order to implement it with two cheaper instructions, e.g.
13150 /// LEA + SHL, LEA + LEA.
13151 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13152                                  TargetLowering::DAGCombinerInfo &DCI) {
13153   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13154     return SDValue();
13155
13156   EVT VT = N->getValueType(0);
13157   if (VT != MVT::i64)
13158     return SDValue();
13159
13160   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13161   if (!C)
13162     return SDValue();
13163   uint64_t MulAmt = C->getZExtValue();
13164   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13165     return SDValue();
13166
13167   uint64_t MulAmt1 = 0;
13168   uint64_t MulAmt2 = 0;
13169   if ((MulAmt % 9) == 0) {
13170     MulAmt1 = 9;
13171     MulAmt2 = MulAmt / 9;
13172   } else if ((MulAmt % 5) == 0) {
13173     MulAmt1 = 5;
13174     MulAmt2 = MulAmt / 5;
13175   } else if ((MulAmt % 3) == 0) {
13176     MulAmt1 = 3;
13177     MulAmt2 = MulAmt / 3;
13178   }
13179   if (MulAmt2 &&
13180       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13181     DebugLoc DL = N->getDebugLoc();
13182
13183     if (isPowerOf2_64(MulAmt2) &&
13184         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13185       // If second multiplifer is pow2, issue it first. We want the multiply by
13186       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13187       // is an add.
13188       std::swap(MulAmt1, MulAmt2);
13189
13190     SDValue NewMul;
13191     if (isPowerOf2_64(MulAmt1))
13192       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13193                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13194     else
13195       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13196                            DAG.getConstant(MulAmt1, VT));
13197
13198     if (isPowerOf2_64(MulAmt2))
13199       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13200                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13201     else
13202       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13203                            DAG.getConstant(MulAmt2, VT));
13204
13205     // Do not add new nodes to DAG combiner worklist.
13206     DCI.CombineTo(N, NewMul, false);
13207   }
13208   return SDValue();
13209 }
13210
13211 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13212   SDValue N0 = N->getOperand(0);
13213   SDValue N1 = N->getOperand(1);
13214   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13215   EVT VT = N0.getValueType();
13216
13217   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13218   // since the result of setcc_c is all zero's or all ones.
13219   if (N1C && N0.getOpcode() == ISD::AND &&
13220       N0.getOperand(1).getOpcode() == ISD::Constant) {
13221     SDValue N00 = N0.getOperand(0);
13222     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13223         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13224           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13225          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13226       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13227       APInt ShAmt = N1C->getAPIntValue();
13228       Mask = Mask.shl(ShAmt);
13229       if (Mask != 0)
13230         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13231                            N00, DAG.getConstant(Mask, VT));
13232     }
13233   }
13234
13235   return SDValue();
13236 }
13237
13238 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13239 ///                       when possible.
13240 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13241                                    const X86Subtarget *Subtarget) {
13242   EVT VT = N->getValueType(0);
13243   if (!VT.isVector() && VT.isInteger() &&
13244       N->getOpcode() == ISD::SHL)
13245     return PerformSHLCombine(N, DAG);
13246
13247   // On X86 with SSE2 support, we can transform this to a vector shift if
13248   // all elements are shifted by the same amount.  We can't do this in legalize
13249   // because the a constant vector is typically transformed to a constant pool
13250   // so we have no knowledge of the shift amount.
13251   if (!Subtarget->hasXMMInt())
13252     return SDValue();
13253
13254   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13255     return SDValue();
13256
13257   SDValue ShAmtOp = N->getOperand(1);
13258   EVT EltVT = VT.getVectorElementType();
13259   DebugLoc DL = N->getDebugLoc();
13260   SDValue BaseShAmt = SDValue();
13261   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13262     unsigned NumElts = VT.getVectorNumElements();
13263     unsigned i = 0;
13264     for (; i != NumElts; ++i) {
13265       SDValue Arg = ShAmtOp.getOperand(i);
13266       if (Arg.getOpcode() == ISD::UNDEF) continue;
13267       BaseShAmt = Arg;
13268       break;
13269     }
13270     for (; i != NumElts; ++i) {
13271       SDValue Arg = ShAmtOp.getOperand(i);
13272       if (Arg.getOpcode() == ISD::UNDEF) continue;
13273       if (Arg != BaseShAmt) {
13274         return SDValue();
13275       }
13276     }
13277   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13278              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13279     SDValue InVec = ShAmtOp.getOperand(0);
13280     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13281       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13282       unsigned i = 0;
13283       for (; i != NumElts; ++i) {
13284         SDValue Arg = InVec.getOperand(i);
13285         if (Arg.getOpcode() == ISD::UNDEF) continue;
13286         BaseShAmt = Arg;
13287         break;
13288       }
13289     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13290        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13291          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13292          if (C->getZExtValue() == SplatIdx)
13293            BaseShAmt = InVec.getOperand(1);
13294        }
13295     }
13296     if (BaseShAmt.getNode() == 0)
13297       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13298                               DAG.getIntPtrConstant(0));
13299   } else
13300     return SDValue();
13301
13302   // The shift amount is an i32.
13303   if (EltVT.bitsGT(MVT::i32))
13304     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13305   else if (EltVT.bitsLT(MVT::i32))
13306     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13307
13308   // The shift amount is identical so we can do a vector shift.
13309   SDValue  ValOp = N->getOperand(0);
13310   switch (N->getOpcode()) {
13311   default:
13312     llvm_unreachable("Unknown shift opcode!");
13313     break;
13314   case ISD::SHL:
13315     if (VT == MVT::v2i64)
13316       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13317                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13318                          ValOp, BaseShAmt);
13319     if (VT == MVT::v4i32)
13320       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13321                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13322                          ValOp, BaseShAmt);
13323     if (VT == MVT::v8i16)
13324       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13325                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13326                          ValOp, BaseShAmt);
13327     break;
13328   case ISD::SRA:
13329     if (VT == MVT::v4i32)
13330       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13331                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13332                          ValOp, BaseShAmt);
13333     if (VT == MVT::v8i16)
13334       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13335                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13336                          ValOp, BaseShAmt);
13337     break;
13338   case ISD::SRL:
13339     if (VT == MVT::v2i64)
13340       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13341                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13342                          ValOp, BaseShAmt);
13343     if (VT == MVT::v4i32)
13344       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13345                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13346                          ValOp, BaseShAmt);
13347     if (VT ==  MVT::v8i16)
13348       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13349                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13350                          ValOp, BaseShAmt);
13351     break;
13352   }
13353   return SDValue();
13354 }
13355
13356
13357 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13358 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13359 // and friends.  Likewise for OR -> CMPNEQSS.
13360 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13361                             TargetLowering::DAGCombinerInfo &DCI,
13362                             const X86Subtarget *Subtarget) {
13363   unsigned opcode;
13364
13365   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13366   // we're requiring SSE2 for both.
13367   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13368     SDValue N0 = N->getOperand(0);
13369     SDValue N1 = N->getOperand(1);
13370     SDValue CMP0 = N0->getOperand(1);
13371     SDValue CMP1 = N1->getOperand(1);
13372     DebugLoc DL = N->getDebugLoc();
13373
13374     // The SETCCs should both refer to the same CMP.
13375     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13376       return SDValue();
13377
13378     SDValue CMP00 = CMP0->getOperand(0);
13379     SDValue CMP01 = CMP0->getOperand(1);
13380     EVT     VT    = CMP00.getValueType();
13381
13382     if (VT == MVT::f32 || VT == MVT::f64) {
13383       bool ExpectingFlags = false;
13384       // Check for any users that want flags:
13385       for (SDNode::use_iterator UI = N->use_begin(),
13386              UE = N->use_end();
13387            !ExpectingFlags && UI != UE; ++UI)
13388         switch (UI->getOpcode()) {
13389         default:
13390         case ISD::BR_CC:
13391         case ISD::BRCOND:
13392         case ISD::SELECT:
13393           ExpectingFlags = true;
13394           break;
13395         case ISD::CopyToReg:
13396         case ISD::SIGN_EXTEND:
13397         case ISD::ZERO_EXTEND:
13398         case ISD::ANY_EXTEND:
13399           break;
13400         }
13401
13402       if (!ExpectingFlags) {
13403         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13404         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13405
13406         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13407           X86::CondCode tmp = cc0;
13408           cc0 = cc1;
13409           cc1 = tmp;
13410         }
13411
13412         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13413             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13414           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13415           X86ISD::NodeType NTOperator = is64BitFP ?
13416             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13417           // FIXME: need symbolic constants for these magic numbers.
13418           // See X86ATTInstPrinter.cpp:printSSECC().
13419           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13420           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13421                                               DAG.getConstant(x86cc, MVT::i8));
13422           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13423                                               OnesOrZeroesF);
13424           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13425                                       DAG.getConstant(1, MVT::i32));
13426           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13427           return OneBitOfTruth;
13428         }
13429       }
13430     }
13431   }
13432   return SDValue();
13433 }
13434
13435 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13436 /// so it can be folded inside ANDNP.
13437 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13438   EVT VT = N->getValueType(0);
13439
13440   // Match direct AllOnes for 128 and 256-bit vectors
13441   if (ISD::isBuildVectorAllOnes(N))
13442     return true;
13443
13444   // Look through a bit convert.
13445   if (N->getOpcode() == ISD::BITCAST)
13446     N = N->getOperand(0).getNode();
13447
13448   // Sometimes the operand may come from a insert_subvector building a 256-bit
13449   // allones vector
13450   if (VT.getSizeInBits() == 256 &&
13451       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13452     SDValue V1 = N->getOperand(0);
13453     SDValue V2 = N->getOperand(1);
13454
13455     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13456         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13457         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13458         ISD::isBuildVectorAllOnes(V2.getNode()))
13459       return true;
13460   }
13461
13462   return false;
13463 }
13464
13465 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13466                                  TargetLowering::DAGCombinerInfo &DCI,
13467                                  const X86Subtarget *Subtarget) {
13468   if (DCI.isBeforeLegalizeOps())
13469     return SDValue();
13470
13471   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13472   if (R.getNode())
13473     return R;
13474
13475   EVT VT = N->getValueType(0);
13476
13477   // Create ANDN, BLSI, and BLSR instructions
13478   // BLSI is X & (-X)
13479   // BLSR is X & (X-1)
13480   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13481     SDValue N0 = N->getOperand(0);
13482     SDValue N1 = N->getOperand(1);
13483     DebugLoc DL = N->getDebugLoc();
13484
13485     // Check LHS for not
13486     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13487       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13488     // Check RHS for not
13489     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13490       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13491
13492     // Check LHS for neg
13493     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13494         isZero(N0.getOperand(0)))
13495       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13496
13497     // Check RHS for neg
13498     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13499         isZero(N1.getOperand(0)))
13500       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13501
13502     // Check LHS for X-1
13503     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13504         isAllOnes(N0.getOperand(1)))
13505       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13506
13507     // Check RHS for X-1
13508     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13509         isAllOnes(N1.getOperand(1)))
13510       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13511
13512     return SDValue();
13513   }
13514
13515   // Want to form ANDNP nodes:
13516   // 1) In the hopes of then easily combining them with OR and AND nodes
13517   //    to form PBLEND/PSIGN.
13518   // 2) To match ANDN packed intrinsics
13519   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13520     return SDValue();
13521
13522   SDValue N0 = N->getOperand(0);
13523   SDValue N1 = N->getOperand(1);
13524   DebugLoc DL = N->getDebugLoc();
13525
13526   // Check LHS for vnot
13527   if (N0.getOpcode() == ISD::XOR &&
13528       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13529       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13530     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13531
13532   // Check RHS for vnot
13533   if (N1.getOpcode() == ISD::XOR &&
13534       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13535       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13536     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13537
13538   return SDValue();
13539 }
13540
13541 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13542                                 TargetLowering::DAGCombinerInfo &DCI,
13543                                 const X86Subtarget *Subtarget) {
13544   if (DCI.isBeforeLegalizeOps())
13545     return SDValue();
13546
13547   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13548   if (R.getNode())
13549     return R;
13550
13551   EVT VT = N->getValueType(0);
13552   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13553     return SDValue();
13554
13555   SDValue N0 = N->getOperand(0);
13556   SDValue N1 = N->getOperand(1);
13557
13558   // look for psign/blend
13559   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13560     if (VT == MVT::v2i64) {
13561       // Canonicalize pandn to RHS
13562       if (N0.getOpcode() == X86ISD::ANDNP)
13563         std::swap(N0, N1);
13564       // or (and (m, x), (pandn m, y))
13565       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13566         SDValue Mask = N1.getOperand(0);
13567         SDValue X    = N1.getOperand(1);
13568         SDValue Y;
13569         if (N0.getOperand(0) == Mask)
13570           Y = N0.getOperand(1);
13571         if (N0.getOperand(1) == Mask)
13572           Y = N0.getOperand(0);
13573
13574         // Check to see if the mask appeared in both the AND and ANDNP and
13575         if (!Y.getNode())
13576           return SDValue();
13577
13578         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13579         if (Mask.getOpcode() != ISD::BITCAST ||
13580             X.getOpcode() != ISD::BITCAST ||
13581             Y.getOpcode() != ISD::BITCAST)
13582           return SDValue();
13583
13584         // Look through mask bitcast.
13585         Mask = Mask.getOperand(0);
13586         EVT MaskVT = Mask.getValueType();
13587
13588         // Validate that the Mask operand is a vector sra node.  The sra node
13589         // will be an intrinsic.
13590         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13591           return SDValue();
13592
13593         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13594         // there is no psrai.b
13595         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13596         case Intrinsic::x86_sse2_psrai_w:
13597         case Intrinsic::x86_sse2_psrai_d:
13598           break;
13599         default: return SDValue();
13600         }
13601
13602         // Check that the SRA is all signbits.
13603         SDValue SraC = Mask.getOperand(2);
13604         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13605         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13606         if ((SraAmt + 1) != EltBits)
13607           return SDValue();
13608
13609         DebugLoc DL = N->getDebugLoc();
13610
13611         // Now we know we at least have a plendvb with the mask val.  See if
13612         // we can form a psignb/w/d.
13613         // psign = x.type == y.type == mask.type && y = sub(0, x);
13614         X = X.getOperand(0);
13615         Y = Y.getOperand(0);
13616         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13617             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13618             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13619           unsigned Opc = 0;
13620           switch (EltBits) {
13621           case 8: Opc = X86ISD::PSIGNB; break;
13622           case 16: Opc = X86ISD::PSIGNW; break;
13623           case 32: Opc = X86ISD::PSIGND; break;
13624           default: break;
13625           }
13626           if (Opc) {
13627             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13628             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13629           }
13630         }
13631         // PBLENDVB only available on SSE 4.1
13632         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13633           return SDValue();
13634
13635         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13636         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13637         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13638         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13639         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13640       }
13641     }
13642   }
13643
13644   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13645   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13646     std::swap(N0, N1);
13647   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13648     return SDValue();
13649   if (!N0.hasOneUse() || !N1.hasOneUse())
13650     return SDValue();
13651
13652   SDValue ShAmt0 = N0.getOperand(1);
13653   if (ShAmt0.getValueType() != MVT::i8)
13654     return SDValue();
13655   SDValue ShAmt1 = N1.getOperand(1);
13656   if (ShAmt1.getValueType() != MVT::i8)
13657     return SDValue();
13658   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13659     ShAmt0 = ShAmt0.getOperand(0);
13660   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13661     ShAmt1 = ShAmt1.getOperand(0);
13662
13663   DebugLoc DL = N->getDebugLoc();
13664   unsigned Opc = X86ISD::SHLD;
13665   SDValue Op0 = N0.getOperand(0);
13666   SDValue Op1 = N1.getOperand(0);
13667   if (ShAmt0.getOpcode() == ISD::SUB) {
13668     Opc = X86ISD::SHRD;
13669     std::swap(Op0, Op1);
13670     std::swap(ShAmt0, ShAmt1);
13671   }
13672
13673   unsigned Bits = VT.getSizeInBits();
13674   if (ShAmt1.getOpcode() == ISD::SUB) {
13675     SDValue Sum = ShAmt1.getOperand(0);
13676     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13677       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13678       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13679         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13680       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13681         return DAG.getNode(Opc, DL, VT,
13682                            Op0, Op1,
13683                            DAG.getNode(ISD::TRUNCATE, DL,
13684                                        MVT::i8, ShAmt0));
13685     }
13686   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13687     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13688     if (ShAmt0C &&
13689         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13690       return DAG.getNode(Opc, DL, VT,
13691                          N0.getOperand(0), N1.getOperand(0),
13692                          DAG.getNode(ISD::TRUNCATE, DL,
13693                                        MVT::i8, ShAmt0));
13694   }
13695
13696   return SDValue();
13697 }
13698
13699 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13700                                  TargetLowering::DAGCombinerInfo &DCI,
13701                                  const X86Subtarget *Subtarget) {
13702   if (DCI.isBeforeLegalizeOps())
13703     return SDValue();
13704
13705   EVT VT = N->getValueType(0);
13706
13707   if (VT != MVT::i32 && VT != MVT::i64)
13708     return SDValue();
13709
13710   // Create BLSMSK instructions by finding X ^ (X-1)
13711   SDValue N0 = N->getOperand(0);
13712   SDValue N1 = N->getOperand(1);
13713   DebugLoc DL = N->getDebugLoc();
13714
13715   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13716       isAllOnes(N0.getOperand(1)))
13717     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13718
13719   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13720       isAllOnes(N1.getOperand(1)))
13721     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13722
13723   return SDValue();
13724 }
13725
13726 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13727 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13728                                    const X86Subtarget *Subtarget) {
13729   LoadSDNode *Ld = cast<LoadSDNode>(N);
13730   EVT RegVT = Ld->getValueType(0);
13731   EVT MemVT = Ld->getMemoryVT();
13732   DebugLoc dl = Ld->getDebugLoc();
13733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13734
13735   ISD::LoadExtType Ext = Ld->getExtensionType();
13736
13737   // If this is a vector EXT Load then attempt to optimize it using a
13738   // shuffle. We need SSE4 for the shuffles.
13739   // TODO: It is possible to support ZExt by zeroing the undef values
13740   // during the shuffle phase or after the shuffle.
13741   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13742     assert(MemVT != RegVT && "Cannot extend to the same type");
13743     assert(MemVT.isVector() && "Must load a vector from memory");
13744
13745     unsigned NumElems = RegVT.getVectorNumElements();
13746     unsigned RegSz = RegVT.getSizeInBits();
13747     unsigned MemSz = MemVT.getSizeInBits();
13748     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13749     // All sizes must be a power of two
13750     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13751
13752     // Attempt to load the original value using a single load op.
13753     // Find a scalar type which is equal to the loaded word size.
13754     MVT SclrLoadTy = MVT::i8;
13755     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13756          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13757       MVT Tp = (MVT::SimpleValueType)tp;
13758       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13759         SclrLoadTy = Tp;
13760         break;
13761       }
13762     }
13763
13764     // Proceed if a load word is found.
13765     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13766
13767     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13768       RegSz/SclrLoadTy.getSizeInBits());
13769
13770     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13771                                   RegSz/MemVT.getScalarType().getSizeInBits());
13772     // Can't shuffle using an illegal type.
13773     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13774
13775     // Perform a single load.
13776     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13777                                   Ld->getBasePtr(),
13778                                   Ld->getPointerInfo(), Ld->isVolatile(),
13779                                   Ld->isNonTemporal(), Ld->getAlignment());
13780
13781     // Insert the word loaded into a vector.
13782     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13783       LoadUnitVecVT, ScalarLoad);
13784
13785     // Bitcast the loaded value to a vector of the original element type, in
13786     // the size of the target vector type.
13787     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13788     unsigned SizeRatio = RegSz/MemSz;
13789
13790     // Redistribute the loaded elements into the different locations.
13791     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13792     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13793
13794     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13795                                 DAG.getUNDEF(SlicedVec.getValueType()),
13796                                 ShuffleVec.data());
13797
13798     // Bitcast to the requested type.
13799     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13800     // Replace the original load with the new sequence
13801     // and return the new chain.
13802     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13803     return SDValue(ScalarLoad.getNode(), 1);
13804   }
13805
13806   return SDValue();
13807 }
13808
13809 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13810 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13811                                    const X86Subtarget *Subtarget) {
13812   StoreSDNode *St = cast<StoreSDNode>(N);
13813   EVT VT = St->getValue().getValueType();
13814   EVT StVT = St->getMemoryVT();
13815   DebugLoc dl = St->getDebugLoc();
13816   SDValue StoredVal = St->getOperand(1);
13817   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13818
13819   // If we are saving a concatination of two XMM registers, perform two stores.
13820   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13821   // 128-bit ones. If in the future the cost becomes only one memory access the
13822   // first version would be better.
13823   if (VT.getSizeInBits() == 256 &&
13824     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13825     StoredVal.getNumOperands() == 2) {
13826
13827     SDValue Value0 = StoredVal.getOperand(0);
13828     SDValue Value1 = StoredVal.getOperand(1);
13829
13830     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13831     SDValue Ptr0 = St->getBasePtr();
13832     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13833
13834     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13835                                 St->getPointerInfo(), St->isVolatile(),
13836                                 St->isNonTemporal(), St->getAlignment());
13837     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13838                                 St->getPointerInfo(), St->isVolatile(),
13839                                 St->isNonTemporal(), St->getAlignment());
13840     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13841   }
13842
13843   // Optimize trunc store (of multiple scalars) to shuffle and store.
13844   // First, pack all of the elements in one place. Next, store to memory
13845   // in fewer chunks.
13846   if (St->isTruncatingStore() && VT.isVector()) {
13847     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13848     unsigned NumElems = VT.getVectorNumElements();
13849     assert(StVT != VT && "Cannot truncate to the same type");
13850     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13851     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13852
13853     // From, To sizes and ElemCount must be pow of two
13854     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13855     // We are going to use the original vector elt for storing.
13856     // Accumulated smaller vector elements must be a multiple of the store size.
13857     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13858
13859     unsigned SizeRatio  = FromSz / ToSz;
13860
13861     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13862
13863     // Create a type on which we perform the shuffle
13864     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13865             StVT.getScalarType(), NumElems*SizeRatio);
13866
13867     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13868
13869     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13870     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13871     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13872
13873     // Can't shuffle using an illegal type
13874     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13875
13876     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13877                                 DAG.getUNDEF(WideVec.getValueType()),
13878                                 ShuffleVec.data());
13879     // At this point all of the data is stored at the bottom of the
13880     // register. We now need to save it to mem.
13881
13882     // Find the largest store unit
13883     MVT StoreType = MVT::i8;
13884     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13885          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13886       MVT Tp = (MVT::SimpleValueType)tp;
13887       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13888         StoreType = Tp;
13889     }
13890
13891     // Bitcast the original vector into a vector of store-size units
13892     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13893             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13894     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13895     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13896     SmallVector<SDValue, 8> Chains;
13897     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13898                                         TLI.getPointerTy());
13899     SDValue Ptr = St->getBasePtr();
13900
13901     // Perform one or more big stores into memory.
13902     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13903       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13904                                    StoreType, ShuffWide,
13905                                    DAG.getIntPtrConstant(i));
13906       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13907                                 St->getPointerInfo(), St->isVolatile(),
13908                                 St->isNonTemporal(), St->getAlignment());
13909       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13910       Chains.push_back(Ch);
13911     }
13912
13913     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13914                                Chains.size());
13915   }
13916
13917
13918   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13919   // the FP state in cases where an emms may be missing.
13920   // A preferable solution to the general problem is to figure out the right
13921   // places to insert EMMS.  This qualifies as a quick hack.
13922
13923   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13924   if (VT.getSizeInBits() != 64)
13925     return SDValue();
13926
13927   const Function *F = DAG.getMachineFunction().getFunction();
13928   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13929   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13930                      && Subtarget->hasXMMInt();
13931   if ((VT.isVector() ||
13932        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13933       isa<LoadSDNode>(St->getValue()) &&
13934       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13935       St->getChain().hasOneUse() && !St->isVolatile()) {
13936     SDNode* LdVal = St->getValue().getNode();
13937     LoadSDNode *Ld = 0;
13938     int TokenFactorIndex = -1;
13939     SmallVector<SDValue, 8> Ops;
13940     SDNode* ChainVal = St->getChain().getNode();
13941     // Must be a store of a load.  We currently handle two cases:  the load
13942     // is a direct child, and it's under an intervening TokenFactor.  It is
13943     // possible to dig deeper under nested TokenFactors.
13944     if (ChainVal == LdVal)
13945       Ld = cast<LoadSDNode>(St->getChain());
13946     else if (St->getValue().hasOneUse() &&
13947              ChainVal->getOpcode() == ISD::TokenFactor) {
13948       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13949         if (ChainVal->getOperand(i).getNode() == LdVal) {
13950           TokenFactorIndex = i;
13951           Ld = cast<LoadSDNode>(St->getValue());
13952         } else
13953           Ops.push_back(ChainVal->getOperand(i));
13954       }
13955     }
13956
13957     if (!Ld || !ISD::isNormalLoad(Ld))
13958       return SDValue();
13959
13960     // If this is not the MMX case, i.e. we are just turning i64 load/store
13961     // into f64 load/store, avoid the transformation if there are multiple
13962     // uses of the loaded value.
13963     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13964       return SDValue();
13965
13966     DebugLoc LdDL = Ld->getDebugLoc();
13967     DebugLoc StDL = N->getDebugLoc();
13968     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13969     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13970     // pair instead.
13971     if (Subtarget->is64Bit() || F64IsLegal) {
13972       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13973       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13974                                   Ld->getPointerInfo(), Ld->isVolatile(),
13975                                   Ld->isNonTemporal(), Ld->getAlignment());
13976       SDValue NewChain = NewLd.getValue(1);
13977       if (TokenFactorIndex != -1) {
13978         Ops.push_back(NewChain);
13979         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13980                                Ops.size());
13981       }
13982       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13983                           St->getPointerInfo(),
13984                           St->isVolatile(), St->isNonTemporal(),
13985                           St->getAlignment());
13986     }
13987
13988     // Otherwise, lower to two pairs of 32-bit loads / stores.
13989     SDValue LoAddr = Ld->getBasePtr();
13990     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13991                                  DAG.getConstant(4, MVT::i32));
13992
13993     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13994                                Ld->getPointerInfo(),
13995                                Ld->isVolatile(), Ld->isNonTemporal(),
13996                                Ld->getAlignment());
13997     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13998                                Ld->getPointerInfo().getWithOffset(4),
13999                                Ld->isVolatile(), Ld->isNonTemporal(),
14000                                MinAlign(Ld->getAlignment(), 4));
14001
14002     SDValue NewChain = LoLd.getValue(1);
14003     if (TokenFactorIndex != -1) {
14004       Ops.push_back(LoLd);
14005       Ops.push_back(HiLd);
14006       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14007                              Ops.size());
14008     }
14009
14010     LoAddr = St->getBasePtr();
14011     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14012                          DAG.getConstant(4, MVT::i32));
14013
14014     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14015                                 St->getPointerInfo(),
14016                                 St->isVolatile(), St->isNonTemporal(),
14017                                 St->getAlignment());
14018     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14019                                 St->getPointerInfo().getWithOffset(4),
14020                                 St->isVolatile(),
14021                                 St->isNonTemporal(),
14022                                 MinAlign(St->getAlignment(), 4));
14023     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14024   }
14025   return SDValue();
14026 }
14027
14028 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14029 /// and return the operands for the horizontal operation in LHS and RHS.  A
14030 /// horizontal operation performs the binary operation on successive elements
14031 /// of its first operand, then on successive elements of its second operand,
14032 /// returning the resulting values in a vector.  For example, if
14033 ///   A = < float a0, float a1, float a2, float a3 >
14034 /// and
14035 ///   B = < float b0, float b1, float b2, float b3 >
14036 /// then the result of doing a horizontal operation on A and B is
14037 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14038 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14039 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14040 /// set to A, RHS to B, and the routine returns 'true'.
14041 /// Note that the binary operation should have the property that if one of the
14042 /// operands is UNDEF then the result is UNDEF.
14043 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14044   // Look for the following pattern: if
14045   //   A = < float a0, float a1, float a2, float a3 >
14046   //   B = < float b0, float b1, float b2, float b3 >
14047   // and
14048   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14049   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14050   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14051   // which is A horizontal-op B.
14052
14053   // At least one of the operands should be a vector shuffle.
14054   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14055       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14056     return false;
14057
14058   EVT VT = LHS.getValueType();
14059   unsigned N = VT.getVectorNumElements();
14060
14061   // View LHS in the form
14062   //   LHS = VECTOR_SHUFFLE A, B, LMask
14063   // If LHS is not a shuffle then pretend it is the shuffle
14064   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14065   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14066   // type VT.
14067   SDValue A, B;
14068   SmallVector<int, 8> LMask(N);
14069   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14070     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14071       A = LHS.getOperand(0);
14072     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14073       B = LHS.getOperand(1);
14074     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14075   } else {
14076     if (LHS.getOpcode() != ISD::UNDEF)
14077       A = LHS;
14078     for (unsigned i = 0; i != N; ++i)
14079       LMask[i] = i;
14080   }
14081
14082   // Likewise, view RHS in the form
14083   //   RHS = VECTOR_SHUFFLE C, D, RMask
14084   SDValue C, D;
14085   SmallVector<int, 8> RMask(N);
14086   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14087     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14088       C = RHS.getOperand(0);
14089     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14090       D = RHS.getOperand(1);
14091     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14092   } else {
14093     if (RHS.getOpcode() != ISD::UNDEF)
14094       C = RHS;
14095     for (unsigned i = 0; i != N; ++i)
14096       RMask[i] = i;
14097   }
14098
14099   // Check that the shuffles are both shuffling the same vectors.
14100   if (!(A == C && B == D) && !(A == D && B == C))
14101     return false;
14102
14103   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14104   if (!A.getNode() && !B.getNode())
14105     return false;
14106
14107   // If A and B occur in reverse order in RHS, then "swap" them (which means
14108   // rewriting the mask).
14109   if (A != C)
14110     for (unsigned i = 0; i != N; ++i) {
14111       unsigned Idx = RMask[i];
14112       if (Idx < N)
14113         RMask[i] += N;
14114       else if (Idx < 2*N)
14115         RMask[i] -= N;
14116     }
14117
14118   // At this point LHS and RHS are equivalent to
14119   //   LHS = VECTOR_SHUFFLE A, B, LMask
14120   //   RHS = VECTOR_SHUFFLE A, B, RMask
14121   // Check that the masks correspond to performing a horizontal operation.
14122   for (unsigned i = 0; i != N; ++i) {
14123     unsigned LIdx = LMask[i], RIdx = RMask[i];
14124
14125     // Ignore any UNDEF components.
14126     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14127         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14128       continue;
14129
14130     // Check that successive elements are being operated on.  If not, this is
14131     // not a horizontal operation.
14132     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14133         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14134       return false;
14135   }
14136
14137   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14138   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14139   return true;
14140 }
14141
14142 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14143 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14144                                   const X86Subtarget *Subtarget) {
14145   EVT VT = N->getValueType(0);
14146   SDValue LHS = N->getOperand(0);
14147   SDValue RHS = N->getOperand(1);
14148
14149   // Try to synthesize horizontal adds from adds of shuffles.
14150   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14151       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14152       isHorizontalBinOp(LHS, RHS, true))
14153     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14154   return SDValue();
14155 }
14156
14157 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14158 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14159                                   const X86Subtarget *Subtarget) {
14160   EVT VT = N->getValueType(0);
14161   SDValue LHS = N->getOperand(0);
14162   SDValue RHS = N->getOperand(1);
14163
14164   // Try to synthesize horizontal subs from subs of shuffles.
14165   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14166       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14167       isHorizontalBinOp(LHS, RHS, false))
14168     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14169   return SDValue();
14170 }
14171
14172 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14173 /// X86ISD::FXOR nodes.
14174 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14175   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14176   // F[X]OR(0.0, x) -> x
14177   // F[X]OR(x, 0.0) -> x
14178   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14179     if (C->getValueAPF().isPosZero())
14180       return N->getOperand(1);
14181   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14182     if (C->getValueAPF().isPosZero())
14183       return N->getOperand(0);
14184   return SDValue();
14185 }
14186
14187 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14188 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14189   // FAND(0.0, x) -> 0.0
14190   // FAND(x, 0.0) -> 0.0
14191   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14192     if (C->getValueAPF().isPosZero())
14193       return N->getOperand(0);
14194   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14195     if (C->getValueAPF().isPosZero())
14196       return N->getOperand(1);
14197   return SDValue();
14198 }
14199
14200 static SDValue PerformBTCombine(SDNode *N,
14201                                 SelectionDAG &DAG,
14202                                 TargetLowering::DAGCombinerInfo &DCI) {
14203   // BT ignores high bits in the bit index operand.
14204   SDValue Op1 = N->getOperand(1);
14205   if (Op1.hasOneUse()) {
14206     unsigned BitWidth = Op1.getValueSizeInBits();
14207     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14208     APInt KnownZero, KnownOne;
14209     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14210                                           !DCI.isBeforeLegalizeOps());
14211     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14212     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14213         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14214       DCI.CommitTargetLoweringOpt(TLO);
14215   }
14216   return SDValue();
14217 }
14218
14219 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14220   SDValue Op = N->getOperand(0);
14221   if (Op.getOpcode() == ISD::BITCAST)
14222     Op = Op.getOperand(0);
14223   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14224   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14225       VT.getVectorElementType().getSizeInBits() ==
14226       OpVT.getVectorElementType().getSizeInBits()) {
14227     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14228   }
14229   return SDValue();
14230 }
14231
14232 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14233   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14234   //           (and (i32 x86isd::setcc_carry), 1)
14235   // This eliminates the zext. This transformation is necessary because
14236   // ISD::SETCC is always legalized to i8.
14237   DebugLoc dl = N->getDebugLoc();
14238   SDValue N0 = N->getOperand(0);
14239   EVT VT = N->getValueType(0);
14240   if (N0.getOpcode() == ISD::AND &&
14241       N0.hasOneUse() &&
14242       N0.getOperand(0).hasOneUse()) {
14243     SDValue N00 = N0.getOperand(0);
14244     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14245       return SDValue();
14246     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14247     if (!C || C->getZExtValue() != 1)
14248       return SDValue();
14249     return DAG.getNode(ISD::AND, dl, VT,
14250                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14251                                    N00.getOperand(0), N00.getOperand(1)),
14252                        DAG.getConstant(1, VT));
14253   }
14254
14255   return SDValue();
14256 }
14257
14258 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14259 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14260   unsigned X86CC = N->getConstantOperandVal(0);
14261   SDValue EFLAG = N->getOperand(1);
14262   DebugLoc DL = N->getDebugLoc();
14263
14264   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14265   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14266   // cases.
14267   if (X86CC == X86::COND_B)
14268     return DAG.getNode(ISD::AND, DL, MVT::i8,
14269                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14270                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14271                        DAG.getConstant(1, MVT::i8));
14272
14273   return SDValue();
14274 }
14275
14276 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14277                                         const X86TargetLowering *XTLI) {
14278   SDValue Op0 = N->getOperand(0);
14279   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14280   // a 32-bit target where SSE doesn't support i64->FP operations.
14281   if (Op0.getOpcode() == ISD::LOAD) {
14282     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14283     EVT VT = Ld->getValueType(0);
14284     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14285         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14286         !XTLI->getSubtarget()->is64Bit() &&
14287         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14288       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14289                                           Ld->getChain(), Op0, DAG);
14290       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14291       return FILDChain;
14292     }
14293   }
14294   return SDValue();
14295 }
14296
14297 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14298 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14299                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14300   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14301   // the result is either zero or one (depending on the input carry bit).
14302   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14303   if (X86::isZeroNode(N->getOperand(0)) &&
14304       X86::isZeroNode(N->getOperand(1)) &&
14305       // We don't have a good way to replace an EFLAGS use, so only do this when
14306       // dead right now.
14307       SDValue(N, 1).use_empty()) {
14308     DebugLoc DL = N->getDebugLoc();
14309     EVT VT = N->getValueType(0);
14310     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14311     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14312                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14313                                            DAG.getConstant(X86::COND_B,MVT::i8),
14314                                            N->getOperand(2)),
14315                                DAG.getConstant(1, VT));
14316     return DCI.CombineTo(N, Res1, CarryOut);
14317   }
14318
14319   return SDValue();
14320 }
14321
14322 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14323 //      (add Y, (setne X, 0)) -> sbb -1, Y
14324 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14325 //      (sub (setne X, 0), Y) -> adc -1, Y
14326 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14327   DebugLoc DL = N->getDebugLoc();
14328
14329   // Look through ZExts.
14330   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14331   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14332     return SDValue();
14333
14334   SDValue SetCC = Ext.getOperand(0);
14335   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14336     return SDValue();
14337
14338   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14339   if (CC != X86::COND_E && CC != X86::COND_NE)
14340     return SDValue();
14341
14342   SDValue Cmp = SetCC.getOperand(1);
14343   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14344       !X86::isZeroNode(Cmp.getOperand(1)) ||
14345       !Cmp.getOperand(0).getValueType().isInteger())
14346     return SDValue();
14347
14348   SDValue CmpOp0 = Cmp.getOperand(0);
14349   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14350                                DAG.getConstant(1, CmpOp0.getValueType()));
14351
14352   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14353   if (CC == X86::COND_NE)
14354     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14355                        DL, OtherVal.getValueType(), OtherVal,
14356                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14357   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14358                      DL, OtherVal.getValueType(), OtherVal,
14359                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14360 }
14361
14362 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14363   SDValue Op0 = N->getOperand(0);
14364   SDValue Op1 = N->getOperand(1);
14365
14366   // X86 can't encode an immediate LHS of a sub. See if we can push the
14367   // negation into a preceding instruction.
14368   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14369     // If the RHS of the sub is a XOR with one use and a constant, invert the
14370     // immediate. Then add one to the LHS of the sub so we can turn
14371     // X-Y -> X+~Y+1, saving one register.
14372     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14373         isa<ConstantSDNode>(Op1.getOperand(1))) {
14374       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14375       EVT VT = Op0.getValueType();
14376       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14377                                    Op1.getOperand(0),
14378                                    DAG.getConstant(~XorC, VT));
14379       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14380                          DAG.getConstant(C->getAPIntValue()+1, VT));
14381     }
14382   }
14383
14384   return OptimizeConditionalInDecrement(N, DAG);
14385 }
14386
14387 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14388                                              DAGCombinerInfo &DCI) const {
14389   SelectionDAG &DAG = DCI.DAG;
14390   switch (N->getOpcode()) {
14391   default: break;
14392   case ISD::EXTRACT_VECTOR_ELT:
14393     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14394   case ISD::VSELECT:
14395   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14396   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14397   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14398   case ISD::SUB:            return PerformSubCombine(N, DAG);
14399   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14400   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14401   case ISD::SHL:
14402   case ISD::SRA:
14403   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14404   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14405   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14406   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14407   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14408   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14409   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14410   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14411   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14412   case X86ISD::FXOR:
14413   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14414   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14415   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14416   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14417   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14418   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14419   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14420   case X86ISD::SHUFPD:
14421   case X86ISD::PALIGN:
14422   case X86ISD::PUNPCKHBW:
14423   case X86ISD::PUNPCKHWD:
14424   case X86ISD::PUNPCKHDQ:
14425   case X86ISD::PUNPCKHQDQ:
14426   case X86ISD::UNPCKHPS:
14427   case X86ISD::UNPCKHPD:
14428   case X86ISD::VUNPCKHPSY:
14429   case X86ISD::VUNPCKHPDY:
14430   case X86ISD::PUNPCKLBW:
14431   case X86ISD::PUNPCKLWD:
14432   case X86ISD::PUNPCKLDQ:
14433   case X86ISD::PUNPCKLQDQ:
14434   case X86ISD::UNPCKLPS:
14435   case X86ISD::UNPCKLPD:
14436   case X86ISD::VUNPCKLPSY:
14437   case X86ISD::VUNPCKLPDY:
14438   case X86ISD::MOVHLPS:
14439   case X86ISD::MOVLHPS:
14440   case X86ISD::PSHUFD:
14441   case X86ISD::PSHUFHW:
14442   case X86ISD::PSHUFLW:
14443   case X86ISD::MOVSS:
14444   case X86ISD::MOVSD:
14445   case X86ISD::VPERMILPS:
14446   case X86ISD::VPERMILPSY:
14447   case X86ISD::VPERMILPD:
14448   case X86ISD::VPERMILPDY:
14449   case X86ISD::VPERM2F128:
14450   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14451   }
14452
14453   return SDValue();
14454 }
14455
14456 /// isTypeDesirableForOp - Return true if the target has native support for
14457 /// the specified value type and it is 'desirable' to use the type for the
14458 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14459 /// instruction encodings are longer and some i16 instructions are slow.
14460 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14461   if (!isTypeLegal(VT))
14462     return false;
14463   if (VT != MVT::i16)
14464     return true;
14465
14466   switch (Opc) {
14467   default:
14468     return true;
14469   case ISD::LOAD:
14470   case ISD::SIGN_EXTEND:
14471   case ISD::ZERO_EXTEND:
14472   case ISD::ANY_EXTEND:
14473   case ISD::SHL:
14474   case ISD::SRL:
14475   case ISD::SUB:
14476   case ISD::ADD:
14477   case ISD::MUL:
14478   case ISD::AND:
14479   case ISD::OR:
14480   case ISD::XOR:
14481     return false;
14482   }
14483 }
14484
14485 /// IsDesirableToPromoteOp - This method query the target whether it is
14486 /// beneficial for dag combiner to promote the specified node. If true, it
14487 /// should return the desired promotion type by reference.
14488 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14489   EVT VT = Op.getValueType();
14490   if (VT != MVT::i16)
14491     return false;
14492
14493   bool Promote = false;
14494   bool Commute = false;
14495   switch (Op.getOpcode()) {
14496   default: break;
14497   case ISD::LOAD: {
14498     LoadSDNode *LD = cast<LoadSDNode>(Op);
14499     // If the non-extending load has a single use and it's not live out, then it
14500     // might be folded.
14501     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14502                                                      Op.hasOneUse()*/) {
14503       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14504              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14505         // The only case where we'd want to promote LOAD (rather then it being
14506         // promoted as an operand is when it's only use is liveout.
14507         if (UI->getOpcode() != ISD::CopyToReg)
14508           return false;
14509       }
14510     }
14511     Promote = true;
14512     break;
14513   }
14514   case ISD::SIGN_EXTEND:
14515   case ISD::ZERO_EXTEND:
14516   case ISD::ANY_EXTEND:
14517     Promote = true;
14518     break;
14519   case ISD::SHL:
14520   case ISD::SRL: {
14521     SDValue N0 = Op.getOperand(0);
14522     // Look out for (store (shl (load), x)).
14523     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14524       return false;
14525     Promote = true;
14526     break;
14527   }
14528   case ISD::ADD:
14529   case ISD::MUL:
14530   case ISD::AND:
14531   case ISD::OR:
14532   case ISD::XOR:
14533     Commute = true;
14534     // fallthrough
14535   case ISD::SUB: {
14536     SDValue N0 = Op.getOperand(0);
14537     SDValue N1 = Op.getOperand(1);
14538     if (!Commute && MayFoldLoad(N1))
14539       return false;
14540     // Avoid disabling potential load folding opportunities.
14541     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14542       return false;
14543     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14544       return false;
14545     Promote = true;
14546   }
14547   }
14548
14549   PVT = MVT::i32;
14550   return Promote;
14551 }
14552
14553 //===----------------------------------------------------------------------===//
14554 //                           X86 Inline Assembly Support
14555 //===----------------------------------------------------------------------===//
14556
14557 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14558   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14559
14560   std::string AsmStr = IA->getAsmString();
14561
14562   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14563   SmallVector<StringRef, 4> AsmPieces;
14564   SplitString(AsmStr, AsmPieces, ";\n");
14565
14566   switch (AsmPieces.size()) {
14567   default: return false;
14568   case 1:
14569     AsmStr = AsmPieces[0];
14570     AsmPieces.clear();
14571     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14572
14573     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14574     // we will turn this bswap into something that will be lowered to logical ops
14575     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14576     // so don't worry about this.
14577     // bswap $0
14578     if (AsmPieces.size() == 2 &&
14579         (AsmPieces[0] == "bswap" ||
14580          AsmPieces[0] == "bswapq" ||
14581          AsmPieces[0] == "bswapl") &&
14582         (AsmPieces[1] == "$0" ||
14583          AsmPieces[1] == "${0:q}")) {
14584       // No need to check constraints, nothing other than the equivalent of
14585       // "=r,0" would be valid here.
14586       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14587       if (!Ty || Ty->getBitWidth() % 16 != 0)
14588         return false;
14589       return IntrinsicLowering::LowerToByteSwap(CI);
14590     }
14591     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14592     if (CI->getType()->isIntegerTy(16) &&
14593         AsmPieces.size() == 3 &&
14594         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14595         AsmPieces[1] == "$$8," &&
14596         AsmPieces[2] == "${0:w}" &&
14597         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14598       AsmPieces.clear();
14599       const std::string &ConstraintsStr = IA->getConstraintString();
14600       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14601       std::sort(AsmPieces.begin(), AsmPieces.end());
14602       if (AsmPieces.size() == 4 &&
14603           AsmPieces[0] == "~{cc}" &&
14604           AsmPieces[1] == "~{dirflag}" &&
14605           AsmPieces[2] == "~{flags}" &&
14606           AsmPieces[3] == "~{fpsr}") {
14607         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14608         if (!Ty || Ty->getBitWidth() % 16 != 0)
14609           return false;
14610         return IntrinsicLowering::LowerToByteSwap(CI);
14611       }
14612     }
14613     break;
14614   case 3:
14615     if (CI->getType()->isIntegerTy(32) &&
14616         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14617       SmallVector<StringRef, 4> Words;
14618       SplitString(AsmPieces[0], Words, " \t,");
14619       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14620           Words[2] == "${0:w}") {
14621         Words.clear();
14622         SplitString(AsmPieces[1], Words, " \t,");
14623         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14624             Words[2] == "$0") {
14625           Words.clear();
14626           SplitString(AsmPieces[2], Words, " \t,");
14627           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14628               Words[2] == "${0:w}") {
14629             AsmPieces.clear();
14630             const std::string &ConstraintsStr = IA->getConstraintString();
14631             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14632             std::sort(AsmPieces.begin(), AsmPieces.end());
14633             if (AsmPieces.size() == 4 &&
14634                 AsmPieces[0] == "~{cc}" &&
14635                 AsmPieces[1] == "~{dirflag}" &&
14636                 AsmPieces[2] == "~{flags}" &&
14637                 AsmPieces[3] == "~{fpsr}") {
14638               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14639               if (!Ty || Ty->getBitWidth() % 16 != 0)
14640                 return false;
14641               return IntrinsicLowering::LowerToByteSwap(CI);
14642             }
14643           }
14644         }
14645       }
14646     }
14647
14648     if (CI->getType()->isIntegerTy(64)) {
14649       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14650       if (Constraints.size() >= 2 &&
14651           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14652           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14653         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14654         SmallVector<StringRef, 4> Words;
14655         SplitString(AsmPieces[0], Words, " \t");
14656         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14657           Words.clear();
14658           SplitString(AsmPieces[1], Words, " \t");
14659           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14660             Words.clear();
14661             SplitString(AsmPieces[2], Words, " \t,");
14662             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14663                 Words[2] == "%edx") {
14664               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14665               if (!Ty || Ty->getBitWidth() % 16 != 0)
14666                 return false;
14667               return IntrinsicLowering::LowerToByteSwap(CI);
14668             }
14669           }
14670         }
14671       }
14672     }
14673     break;
14674   }
14675   return false;
14676 }
14677
14678
14679
14680 /// getConstraintType - Given a constraint letter, return the type of
14681 /// constraint it is for this target.
14682 X86TargetLowering::ConstraintType
14683 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14684   if (Constraint.size() == 1) {
14685     switch (Constraint[0]) {
14686     case 'R':
14687     case 'q':
14688     case 'Q':
14689     case 'f':
14690     case 't':
14691     case 'u':
14692     case 'y':
14693     case 'x':
14694     case 'Y':
14695     case 'l':
14696       return C_RegisterClass;
14697     case 'a':
14698     case 'b':
14699     case 'c':
14700     case 'd':
14701     case 'S':
14702     case 'D':
14703     case 'A':
14704       return C_Register;
14705     case 'I':
14706     case 'J':
14707     case 'K':
14708     case 'L':
14709     case 'M':
14710     case 'N':
14711     case 'G':
14712     case 'C':
14713     case 'e':
14714     case 'Z':
14715       return C_Other;
14716     default:
14717       break;
14718     }
14719   }
14720   return TargetLowering::getConstraintType(Constraint);
14721 }
14722
14723 /// Examine constraint type and operand type and determine a weight value.
14724 /// This object must already have been set up with the operand type
14725 /// and the current alternative constraint selected.
14726 TargetLowering::ConstraintWeight
14727   X86TargetLowering::getSingleConstraintMatchWeight(
14728     AsmOperandInfo &info, const char *constraint) const {
14729   ConstraintWeight weight = CW_Invalid;
14730   Value *CallOperandVal = info.CallOperandVal;
14731     // If we don't have a value, we can't do a match,
14732     // but allow it at the lowest weight.
14733   if (CallOperandVal == NULL)
14734     return CW_Default;
14735   Type *type = CallOperandVal->getType();
14736   // Look at the constraint type.
14737   switch (*constraint) {
14738   default:
14739     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14740   case 'R':
14741   case 'q':
14742   case 'Q':
14743   case 'a':
14744   case 'b':
14745   case 'c':
14746   case 'd':
14747   case 'S':
14748   case 'D':
14749   case 'A':
14750     if (CallOperandVal->getType()->isIntegerTy())
14751       weight = CW_SpecificReg;
14752     break;
14753   case 'f':
14754   case 't':
14755   case 'u':
14756       if (type->isFloatingPointTy())
14757         weight = CW_SpecificReg;
14758       break;
14759   case 'y':
14760       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14761         weight = CW_SpecificReg;
14762       break;
14763   case 'x':
14764   case 'Y':
14765     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14766       weight = CW_Register;
14767     break;
14768   case 'I':
14769     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14770       if (C->getZExtValue() <= 31)
14771         weight = CW_Constant;
14772     }
14773     break;
14774   case 'J':
14775     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14776       if (C->getZExtValue() <= 63)
14777         weight = CW_Constant;
14778     }
14779     break;
14780   case 'K':
14781     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14782       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14783         weight = CW_Constant;
14784     }
14785     break;
14786   case 'L':
14787     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14788       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14789         weight = CW_Constant;
14790     }
14791     break;
14792   case 'M':
14793     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14794       if (C->getZExtValue() <= 3)
14795         weight = CW_Constant;
14796     }
14797     break;
14798   case 'N':
14799     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14800       if (C->getZExtValue() <= 0xff)
14801         weight = CW_Constant;
14802     }
14803     break;
14804   case 'G':
14805   case 'C':
14806     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14807       weight = CW_Constant;
14808     }
14809     break;
14810   case 'e':
14811     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14812       if ((C->getSExtValue() >= -0x80000000LL) &&
14813           (C->getSExtValue() <= 0x7fffffffLL))
14814         weight = CW_Constant;
14815     }
14816     break;
14817   case 'Z':
14818     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14819       if (C->getZExtValue() <= 0xffffffff)
14820         weight = CW_Constant;
14821     }
14822     break;
14823   }
14824   return weight;
14825 }
14826
14827 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14828 /// with another that has more specific requirements based on the type of the
14829 /// corresponding operand.
14830 const char *X86TargetLowering::
14831 LowerXConstraint(EVT ConstraintVT) const {
14832   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14833   // 'f' like normal targets.
14834   if (ConstraintVT.isFloatingPoint()) {
14835     if (Subtarget->hasXMMInt())
14836       return "Y";
14837     if (Subtarget->hasXMM())
14838       return "x";
14839   }
14840
14841   return TargetLowering::LowerXConstraint(ConstraintVT);
14842 }
14843
14844 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14845 /// vector.  If it is invalid, don't add anything to Ops.
14846 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14847                                                      std::string &Constraint,
14848                                                      std::vector<SDValue>&Ops,
14849                                                      SelectionDAG &DAG) const {
14850   SDValue Result(0, 0);
14851
14852   // Only support length 1 constraints for now.
14853   if (Constraint.length() > 1) return;
14854
14855   char ConstraintLetter = Constraint[0];
14856   switch (ConstraintLetter) {
14857   default: break;
14858   case 'I':
14859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14860       if (C->getZExtValue() <= 31) {
14861         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14862         break;
14863       }
14864     }
14865     return;
14866   case 'J':
14867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14868       if (C->getZExtValue() <= 63) {
14869         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14870         break;
14871       }
14872     }
14873     return;
14874   case 'K':
14875     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14876       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14877         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14878         break;
14879       }
14880     }
14881     return;
14882   case 'N':
14883     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14884       if (C->getZExtValue() <= 255) {
14885         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14886         break;
14887       }
14888     }
14889     return;
14890   case 'e': {
14891     // 32-bit signed value
14892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14893       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14894                                            C->getSExtValue())) {
14895         // Widen to 64 bits here to get it sign extended.
14896         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14897         break;
14898       }
14899     // FIXME gcc accepts some relocatable values here too, but only in certain
14900     // memory models; it's complicated.
14901     }
14902     return;
14903   }
14904   case 'Z': {
14905     // 32-bit unsigned value
14906     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14907       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14908                                            C->getZExtValue())) {
14909         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14910         break;
14911       }
14912     }
14913     // FIXME gcc accepts some relocatable values here too, but only in certain
14914     // memory models; it's complicated.
14915     return;
14916   }
14917   case 'i': {
14918     // Literal immediates are always ok.
14919     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14920       // Widen to 64 bits here to get it sign extended.
14921       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14922       break;
14923     }
14924
14925     // In any sort of PIC mode addresses need to be computed at runtime by
14926     // adding in a register or some sort of table lookup.  These can't
14927     // be used as immediates.
14928     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14929       return;
14930
14931     // If we are in non-pic codegen mode, we allow the address of a global (with
14932     // an optional displacement) to be used with 'i'.
14933     GlobalAddressSDNode *GA = 0;
14934     int64_t Offset = 0;
14935
14936     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14937     while (1) {
14938       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14939         Offset += GA->getOffset();
14940         break;
14941       } else if (Op.getOpcode() == ISD::ADD) {
14942         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14943           Offset += C->getZExtValue();
14944           Op = Op.getOperand(0);
14945           continue;
14946         }
14947       } else if (Op.getOpcode() == ISD::SUB) {
14948         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14949           Offset += -C->getZExtValue();
14950           Op = Op.getOperand(0);
14951           continue;
14952         }
14953       }
14954
14955       // Otherwise, this isn't something we can handle, reject it.
14956       return;
14957     }
14958
14959     const GlobalValue *GV = GA->getGlobal();
14960     // If we require an extra load to get this address, as in PIC mode, we
14961     // can't accept it.
14962     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14963                                                         getTargetMachine())))
14964       return;
14965
14966     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14967                                         GA->getValueType(0), Offset);
14968     break;
14969   }
14970   }
14971
14972   if (Result.getNode()) {
14973     Ops.push_back(Result);
14974     return;
14975   }
14976   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14977 }
14978
14979 std::pair<unsigned, const TargetRegisterClass*>
14980 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14981                                                 EVT VT) const {
14982   // First, see if this is a constraint that directly corresponds to an LLVM
14983   // register class.
14984   if (Constraint.size() == 1) {
14985     // GCC Constraint Letters
14986     switch (Constraint[0]) {
14987     default: break;
14988       // TODO: Slight differences here in allocation order and leaving
14989       // RIP in the class. Do they matter any more here than they do
14990       // in the normal allocation?
14991     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14992       if (Subtarget->is64Bit()) {
14993         if (VT == MVT::i32 || VT == MVT::f32)
14994           return std::make_pair(0U, X86::GR32RegisterClass);
14995         else if (VT == MVT::i16)
14996           return std::make_pair(0U, X86::GR16RegisterClass);
14997         else if (VT == MVT::i8 || VT == MVT::i1)
14998           return std::make_pair(0U, X86::GR8RegisterClass);
14999         else if (VT == MVT::i64 || VT == MVT::f64)
15000           return std::make_pair(0U, X86::GR64RegisterClass);
15001         break;
15002       }
15003       // 32-bit fallthrough
15004     case 'Q':   // Q_REGS
15005       if (VT == MVT::i32 || VT == MVT::f32)
15006         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15007       else if (VT == MVT::i16)
15008         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15009       else if (VT == MVT::i8 || VT == MVT::i1)
15010         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15011       else if (VT == MVT::i64)
15012         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15013       break;
15014     case 'r':   // GENERAL_REGS
15015     case 'l':   // INDEX_REGS
15016       if (VT == MVT::i8 || VT == MVT::i1)
15017         return std::make_pair(0U, X86::GR8RegisterClass);
15018       if (VT == MVT::i16)
15019         return std::make_pair(0U, X86::GR16RegisterClass);
15020       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15021         return std::make_pair(0U, X86::GR32RegisterClass);
15022       return std::make_pair(0U, X86::GR64RegisterClass);
15023     case 'R':   // LEGACY_REGS
15024       if (VT == MVT::i8 || VT == MVT::i1)
15025         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15026       if (VT == MVT::i16)
15027         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15028       if (VT == MVT::i32 || !Subtarget->is64Bit())
15029         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15030       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15031     case 'f':  // FP Stack registers.
15032       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15033       // value to the correct fpstack register class.
15034       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15035         return std::make_pair(0U, X86::RFP32RegisterClass);
15036       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15037         return std::make_pair(0U, X86::RFP64RegisterClass);
15038       return std::make_pair(0U, X86::RFP80RegisterClass);
15039     case 'y':   // MMX_REGS if MMX allowed.
15040       if (!Subtarget->hasMMX()) break;
15041       return std::make_pair(0U, X86::VR64RegisterClass);
15042     case 'Y':   // SSE_REGS if SSE2 allowed
15043       if (!Subtarget->hasXMMInt()) break;
15044       // FALL THROUGH.
15045     case 'x':   // SSE_REGS if SSE1 allowed
15046       if (!Subtarget->hasXMM()) break;
15047
15048       switch (VT.getSimpleVT().SimpleTy) {
15049       default: break;
15050       // Scalar SSE types.
15051       case MVT::f32:
15052       case MVT::i32:
15053         return std::make_pair(0U, X86::FR32RegisterClass);
15054       case MVT::f64:
15055       case MVT::i64:
15056         return std::make_pair(0U, X86::FR64RegisterClass);
15057       // Vector types.
15058       case MVT::v16i8:
15059       case MVT::v8i16:
15060       case MVT::v4i32:
15061       case MVT::v2i64:
15062       case MVT::v4f32:
15063       case MVT::v2f64:
15064         return std::make_pair(0U, X86::VR128RegisterClass);
15065       }
15066       break;
15067     }
15068   }
15069
15070   // Use the default implementation in TargetLowering to convert the register
15071   // constraint into a member of a register class.
15072   std::pair<unsigned, const TargetRegisterClass*> Res;
15073   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15074
15075   // Not found as a standard register?
15076   if (Res.second == 0) {
15077     // Map st(0) -> st(7) -> ST0
15078     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15079         tolower(Constraint[1]) == 's' &&
15080         tolower(Constraint[2]) == 't' &&
15081         Constraint[3] == '(' &&
15082         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15083         Constraint[5] == ')' &&
15084         Constraint[6] == '}') {
15085
15086       Res.first = X86::ST0+Constraint[4]-'0';
15087       Res.second = X86::RFP80RegisterClass;
15088       return Res;
15089     }
15090
15091     // GCC allows "st(0)" to be called just plain "st".
15092     if (StringRef("{st}").equals_lower(Constraint)) {
15093       Res.first = X86::ST0;
15094       Res.second = X86::RFP80RegisterClass;
15095       return Res;
15096     }
15097
15098     // flags -> EFLAGS
15099     if (StringRef("{flags}").equals_lower(Constraint)) {
15100       Res.first = X86::EFLAGS;
15101       Res.second = X86::CCRRegisterClass;
15102       return Res;
15103     }
15104
15105     // 'A' means EAX + EDX.
15106     if (Constraint == "A") {
15107       Res.first = X86::EAX;
15108       Res.second = X86::GR32_ADRegisterClass;
15109       return Res;
15110     }
15111     return Res;
15112   }
15113
15114   // Otherwise, check to see if this is a register class of the wrong value
15115   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15116   // turn into {ax},{dx}.
15117   if (Res.second->hasType(VT))
15118     return Res;   // Correct type already, nothing to do.
15119
15120   // All of the single-register GCC register classes map their values onto
15121   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15122   // really want an 8-bit or 32-bit register, map to the appropriate register
15123   // class and return the appropriate register.
15124   if (Res.second == X86::GR16RegisterClass) {
15125     if (VT == MVT::i8) {
15126       unsigned DestReg = 0;
15127       switch (Res.first) {
15128       default: break;
15129       case X86::AX: DestReg = X86::AL; break;
15130       case X86::DX: DestReg = X86::DL; break;
15131       case X86::CX: DestReg = X86::CL; break;
15132       case X86::BX: DestReg = X86::BL; break;
15133       }
15134       if (DestReg) {
15135         Res.first = DestReg;
15136         Res.second = X86::GR8RegisterClass;
15137       }
15138     } else if (VT == MVT::i32) {
15139       unsigned DestReg = 0;
15140       switch (Res.first) {
15141       default: break;
15142       case X86::AX: DestReg = X86::EAX; break;
15143       case X86::DX: DestReg = X86::EDX; break;
15144       case X86::CX: DestReg = X86::ECX; break;
15145       case X86::BX: DestReg = X86::EBX; break;
15146       case X86::SI: DestReg = X86::ESI; break;
15147       case X86::DI: DestReg = X86::EDI; break;
15148       case X86::BP: DestReg = X86::EBP; break;
15149       case X86::SP: DestReg = X86::ESP; break;
15150       }
15151       if (DestReg) {
15152         Res.first = DestReg;
15153         Res.second = X86::GR32RegisterClass;
15154       }
15155     } else if (VT == MVT::i64) {
15156       unsigned DestReg = 0;
15157       switch (Res.first) {
15158       default: break;
15159       case X86::AX: DestReg = X86::RAX; break;
15160       case X86::DX: DestReg = X86::RDX; break;
15161       case X86::CX: DestReg = X86::RCX; break;
15162       case X86::BX: DestReg = X86::RBX; break;
15163       case X86::SI: DestReg = X86::RSI; break;
15164       case X86::DI: DestReg = X86::RDI; break;
15165       case X86::BP: DestReg = X86::RBP; break;
15166       case X86::SP: DestReg = X86::RSP; break;
15167       }
15168       if (DestReg) {
15169         Res.first = DestReg;
15170         Res.second = X86::GR64RegisterClass;
15171       }
15172     }
15173   } else if (Res.second == X86::FR32RegisterClass ||
15174              Res.second == X86::FR64RegisterClass ||
15175              Res.second == X86::VR128RegisterClass) {
15176     // Handle references to XMM physical registers that got mapped into the
15177     // wrong class.  This can happen with constraints like {xmm0} where the
15178     // target independent register mapper will just pick the first match it can
15179     // find, ignoring the required type.
15180     if (VT == MVT::f32)
15181       Res.second = X86::FR32RegisterClass;
15182     else if (VT == MVT::f64)
15183       Res.second = X86::FR64RegisterClass;
15184     else if (X86::VR128RegisterClass->hasType(VT))
15185       Res.second = X86::VR128RegisterClass;
15186   }
15187
15188   return Res;
15189 }