Revert r133435 and r133449 to appease buildbots.
[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 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // Lower this to FGETSIGNx86 plus an AND.
578     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f64, Expand);
583     setOperationAction(ISD::FCOS , MVT::f64, Expand);
584     setOperationAction(ISD::FSIN , MVT::f32, Expand);
585     setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587     // Expand FP immediates into loads from the stack, except for the special
588     // cases we handle.
589     addLegalFPImmediate(APFloat(+0.0)); // xorpd
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591   } else if (!UseSoftFloat && X86ScalarSSEf32) {
592     // Use SSE for f32, x87 for f64.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597     // Use ANDPS to simulate FABS.
598     setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600     // Use XORP to simulate FNEG.
601     setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605     // Use ANDPS and ORPS to simulate FCOPYSIGN.
606     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609     // We don't support sin/cos/fmod
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Special cases we handle for FP constants.
614     addLegalFPImmediate(APFloat(+0.0f)); // xorps
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624   } else if (!UseSoftFloat) {
625     // f32 and f64 in x87.
626     // Set up the FP register classes.
627     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635     if (!UnsafeFPMath) {
636       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638     }
639     addLegalFPImmediate(APFloat(+0.0)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647   }
648
649   // Long double always uses X87.
650   if (!UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673   }
674
675   // Always use a library call for pow.
676   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
677   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
679
680   setOperationAction(ISD::FLOG, MVT::f80, Expand);
681   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683   setOperationAction(ISD::FEXP, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685
686   // First set operation action for all vector types to either promote
687   // (for widening) or expand (for scalarization). Then we will selectively
688   // turn on ones that can be effectively codegen'd.
689   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747       setTruncStoreAction((MVT::SimpleValueType)VT,
748                           (MVT::SimpleValueType)InnerVT, Expand);
749     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
752   }
753
754   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755   // with -msoft-float, disable use of MMX as well.
756   if (!UseSoftFloat && Subtarget->hasMMX()) {
757     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758     // No operations on x86mmx supported, everything uses intrinsics.
759   }
760
761   // MMX-sized vectors (other than x86mmx) are expected to be expanded
762   // into smaller operations.
763   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
764   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
765   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
767   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
769   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
770   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
771   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
772   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
773   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
774   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
775   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
776   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
777   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
778   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
779   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
783   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
784   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
785   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
786   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
788   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
792
793   if (!UseSoftFloat && Subtarget->hasXMM()) {
794     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
803     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
804     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
807     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
808   }
809
810   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
812
813     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814     // registers cannot be used even for integer operations.
815     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
819
820     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
821     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
822     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
823     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
825     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
826     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
827     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
828     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
830     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
831     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
835     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
836
837     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
838     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
841
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
847
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856       EVT VT = (MVT::SimpleValueType)i;
857       // Do not attempt to custom lower non-power-of-2 vectors
858       if (!isPowerOf2_32(VT.getVectorNumElements()))
859         continue;
860       // Do not attempt to custom lower non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863       setOperationAction(ISD::BUILD_VECTOR,
864                          VT.getSimpleVT().SimpleTy, Custom);
865       setOperationAction(ISD::VECTOR_SHUFFLE,
866                          VT.getSimpleVT().SimpleTy, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868                          VT.getSimpleVT().SimpleTy, Custom);
869     }
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
877
878     if (Subtarget->is64Bit()) {
879       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
881     }
882
883     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
886       EVT VT = SVT;
887
888       // Do not attempt to promote non-128-bit vectors
889       if (!VT.is128BitVector())
890         continue;
891
892       setOperationAction(ISD::AND,    SVT, Promote);
893       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
894       setOperationAction(ISD::OR,     SVT, Promote);
895       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
896       setOperationAction(ISD::XOR,    SVT, Promote);
897       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
898       setOperationAction(ISD::LOAD,   SVT, Promote);
899       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
900       setOperationAction(ISD::SELECT, SVT, Promote);
901       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
902     }
903
904     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914   }
915
916   if (Subtarget->hasSSE41()) {
917     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
922     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
927
928     // FIXME: Do we need to handle scalar-to-vector here?
929     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
930
931     // Can turn SHL into an integer multiply.
932     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
934
935     // i8 and i16 vectors are custom , because the source register and source
936     // source memory operand types are not the same width.  f32 vectors are
937     // custom since the immediate controlling the insert encodes additional
938     // information.
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
943
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948
949     if (Subtarget->is64Bit()) {
950       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952     }
953   }
954
955   if (Subtarget->hasSSE2()) {
956     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
959
960     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
961     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
962     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
963
964     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
966   }
967
968   if (Subtarget->hasSSE42())
969     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
970
971   if (!UseSoftFloat && Subtarget->hasAVX()) {
972     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998     // insert_vector_elt extract_subvector and extract_vector_elt for
999     // 256-bit types.
1000     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002          ++i) {
1003       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004       // Do not attempt to custom lower non-256-bit vectors
1005       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006           || (MVT(VT).getSizeInBits() < 256))
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1013     }
1014     // Custom-lower insert_subvector and extract_subvector based on
1015     // the result type.
1016     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1018          ++i) {
1019       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020       // Do not attempt to custom lower non-256-bit vectors
1021       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1022         continue;
1023
1024       if (MVT(VT).getSizeInBits() == 128) {
1025         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1026       }
1027       else if (MVT(VT).getSizeInBits() == 256) {
1028         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1029       }
1030     }
1031
1032     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033     // Don't promote loads because we need them for VPERM vector index versions.
1034
1035     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1037          VT++) {
1038       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1040         continue;
1041       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1044       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1047       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1048       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1049       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1051     }
1052   }
1053
1054   // We want to custom lower some of our intrinsics.
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056
1057
1058   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059   // handle type legalization for these operations here.
1060   //
1061   // FIXME: We really should do custom legalization for addition and
1062   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1063   // than generic legalization for 64-bit multiplication-with-overflow, though.
1064   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065     // Add/Sub/Mul with overflow operations are custom lowered.
1066     MVT VT = IntVTs[i];
1067     setOperationAction(ISD::SADDO, VT, Custom);
1068     setOperationAction(ISD::UADDO, VT, Custom);
1069     setOperationAction(ISD::SSUBO, VT, Custom);
1070     setOperationAction(ISD::USUBO, VT, Custom);
1071     setOperationAction(ISD::SMULO, VT, Custom);
1072     setOperationAction(ISD::UMULO, VT, Custom);
1073   }
1074
1075   // There are no 8-bit 3-address imul/mul instructions
1076   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1078
1079   if (!Subtarget->is64Bit()) {
1080     // These libcalls are not available in 32-bit.
1081     setLibcallName(RTLIB::SHL_I128, 0);
1082     setLibcallName(RTLIB::SRL_I128, 0);
1083     setLibcallName(RTLIB::SRA_I128, 0);
1084   }
1085
1086   // We have target-specific dag combine patterns for the following nodes:
1087   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089   setTargetDAGCombine(ISD::BUILD_VECTOR);
1090   setTargetDAGCombine(ISD::SELECT);
1091   setTargetDAGCombine(ISD::SHL);
1092   setTargetDAGCombine(ISD::SRA);
1093   setTargetDAGCombine(ISD::SRL);
1094   setTargetDAGCombine(ISD::OR);
1095   setTargetDAGCombine(ISD::AND);
1096   setTargetDAGCombine(ISD::ADD);
1097   setTargetDAGCombine(ISD::SUB);
1098   setTargetDAGCombine(ISD::STORE);
1099   setTargetDAGCombine(ISD::ZERO_EXTEND);
1100   setTargetDAGCombine(ISD::SINT_TO_FP);
1101   if (Subtarget->is64Bit())
1102     setTargetDAGCombine(ISD::MUL);
1103
1104   computeRegisterProperties();
1105
1106   // On Darwin, -Os means optimize for size without hurting performance,
1107   // do not reduce the limit.
1108   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1109   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1110   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1111   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1112   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1113   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1114   setPrefLoopAlignment(16);
1115   benefitFromCodePlacementOpt = true;
1116
1117   setPrefFunctionAlignment(4);
1118 }
1119
1120
1121 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1122   return MVT::i8;
1123 }
1124
1125
1126 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1127 /// the desired ByVal argument alignment.
1128 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1129   if (MaxAlign == 16)
1130     return;
1131   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1132     if (VTy->getBitWidth() == 128)
1133       MaxAlign = 16;
1134   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1135     unsigned EltAlign = 0;
1136     getMaxByValAlign(ATy->getElementType(), EltAlign);
1137     if (EltAlign > MaxAlign)
1138       MaxAlign = EltAlign;
1139   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1140     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1141       unsigned EltAlign = 0;
1142       getMaxByValAlign(STy->getElementType(i), EltAlign);
1143       if (EltAlign > MaxAlign)
1144         MaxAlign = EltAlign;
1145       if (MaxAlign == 16)
1146         break;
1147     }
1148   }
1149   return;
1150 }
1151
1152 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1153 /// function arguments in the caller parameter area. For X86, aggregates
1154 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1155 /// are at 4-byte boundaries.
1156 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1157   if (Subtarget->is64Bit()) {
1158     // Max of 8 and alignment of type.
1159     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1160     if (TyAlign > 8)
1161       return TyAlign;
1162     return 8;
1163   }
1164
1165   unsigned Align = 4;
1166   if (Subtarget->hasXMM())
1167     getMaxByValAlign(Ty, Align);
1168   return Align;
1169 }
1170
1171 /// getOptimalMemOpType - Returns the target specific optimal type for load
1172 /// and store operations as a result of memset, memcpy, and memmove
1173 /// lowering. If DstAlign is zero that means it's safe to destination
1174 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1175 /// means there isn't a need to check it against alignment requirement,
1176 /// probably because the source does not need to be loaded. If
1177 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1178 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1179 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1180 /// constant so it does not need to be loaded.
1181 /// It returns EVT::Other if the type should be determined using generic
1182 /// target-independent logic.
1183 EVT
1184 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1185                                        unsigned DstAlign, unsigned SrcAlign,
1186                                        bool NonScalarIntSafe,
1187                                        bool MemcpyStrSrc,
1188                                        MachineFunction &MF) const {
1189   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1190   // linux.  This is because the stack realignment code can't handle certain
1191   // cases like PR2962.  This should be removed when PR2962 is fixed.
1192   const Function *F = MF.getFunction();
1193   if (NonScalarIntSafe &&
1194       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1195     if (Size >= 16 &&
1196         (Subtarget->isUnalignedMemAccessFast() ||
1197          ((DstAlign == 0 || DstAlign >= 16) &&
1198           (SrcAlign == 0 || SrcAlign >= 16))) &&
1199         Subtarget->getStackAlignment() >= 16) {
1200       if (Subtarget->hasSSE2())
1201         return MVT::v4i32;
1202       if (Subtarget->hasSSE1())
1203         return MVT::v4f32;
1204     } else if (!MemcpyStrSrc && Size >= 8 &&
1205                !Subtarget->is64Bit() &&
1206                Subtarget->getStackAlignment() >= 8 &&
1207                Subtarget->hasXMMInt()) {
1208       // Do not use f64 to lower memcpy if source is string constant. It's
1209       // better to use i32 to avoid the loads.
1210       return MVT::f64;
1211     }
1212   }
1213   if (Subtarget->is64Bit() && Size >= 8)
1214     return MVT::i64;
1215   return MVT::i32;
1216 }
1217
1218 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1219 /// current function.  The returned value is a member of the
1220 /// MachineJumpTableInfo::JTEntryKind enum.
1221 unsigned X86TargetLowering::getJumpTableEncoding() const {
1222   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1223   // symbol.
1224   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1225       Subtarget->isPICStyleGOT())
1226     return MachineJumpTableInfo::EK_Custom32;
1227
1228   // Otherwise, use the normal jump table encoding heuristics.
1229   return TargetLowering::getJumpTableEncoding();
1230 }
1231
1232 const MCExpr *
1233 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1234                                              const MachineBasicBlock *MBB,
1235                                              unsigned uid,MCContext &Ctx) const{
1236   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237          Subtarget->isPICStyleGOT());
1238   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1239   // entries.
1240   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1241                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1242 }
1243
1244 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1245 /// jumptable.
1246 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1247                                                     SelectionDAG &DAG) const {
1248   if (!Subtarget->is64Bit())
1249     // This doesn't have DebugLoc associated with it, but is not really the
1250     // same as a Register.
1251     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1252   return Table;
1253 }
1254
1255 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1256 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1257 /// MCExpr.
1258 const MCExpr *X86TargetLowering::
1259 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1260                              MCContext &Ctx) const {
1261   // X86-64 uses RIP relative addressing based on the jump table label.
1262   if (Subtarget->isPICStyleRIPRel())
1263     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1264
1265   // Otherwise, the reference is relative to the PIC base.
1266   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1267 }
1268
1269 // FIXME: Why this routine is here? Move to RegInfo!
1270 std::pair<const TargetRegisterClass*, uint8_t>
1271 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1272   const TargetRegisterClass *RRC = 0;
1273   uint8_t Cost = 1;
1274   switch (VT.getSimpleVT().SimpleTy) {
1275   default:
1276     return TargetLowering::findRepresentativeClass(VT);
1277   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1278     RRC = (Subtarget->is64Bit()
1279            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1280     break;
1281   case MVT::x86mmx:
1282     RRC = X86::VR64RegisterClass;
1283     break;
1284   case MVT::f32: case MVT::f64:
1285   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1286   case MVT::v4f32: case MVT::v2f64:
1287   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1288   case MVT::v4f64:
1289     RRC = X86::VR128RegisterClass;
1290     break;
1291   }
1292   return std::make_pair(RRC, Cost);
1293 }
1294
1295 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1296                                                unsigned &Offset) const {
1297   if (!Subtarget->isTargetLinux())
1298     return false;
1299
1300   if (Subtarget->is64Bit()) {
1301     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1302     Offset = 0x28;
1303     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1304       AddressSpace = 256;
1305     else
1306       AddressSpace = 257;
1307   } else {
1308     // %gs:0x14 on i386
1309     Offset = 0x14;
1310     AddressSpace = 256;
1311   }
1312   return true;
1313 }
1314
1315
1316 //===----------------------------------------------------------------------===//
1317 //               Return Value Calling Convention Implementation
1318 //===----------------------------------------------------------------------===//
1319
1320 #include "X86GenCallingConv.inc"
1321
1322 bool
1323 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1324                                   MachineFunction &MF, bool isVarArg,
1325                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1326                         LLVMContext &Context) const {
1327   SmallVector<CCValAssign, 16> RVLocs;
1328   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1329                  RVLocs, Context);
1330   return CCInfo.CheckReturn(Outs, RetCC_X86);
1331 }
1332
1333 SDValue
1334 X86TargetLowering::LowerReturn(SDValue Chain,
1335                                CallingConv::ID CallConv, bool isVarArg,
1336                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1337                                const SmallVectorImpl<SDValue> &OutVals,
1338                                DebugLoc dl, SelectionDAG &DAG) const {
1339   MachineFunction &MF = DAG.getMachineFunction();
1340   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1341
1342   SmallVector<CCValAssign, 16> RVLocs;
1343   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1344                  RVLocs, *DAG.getContext());
1345   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1346
1347   // Add the regs to the liveout set for the function.
1348   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1349   for (unsigned i = 0; i != RVLocs.size(); ++i)
1350     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1351       MRI.addLiveOut(RVLocs[i].getLocReg());
1352
1353   SDValue Flag;
1354
1355   SmallVector<SDValue, 6> RetOps;
1356   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1357   // Operand #1 = Bytes To Pop
1358   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1359                    MVT::i16));
1360
1361   // Copy the result values into the output registers.
1362   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1363     CCValAssign &VA = RVLocs[i];
1364     assert(VA.isRegLoc() && "Can only return in registers!");
1365     SDValue ValToCopy = OutVals[i];
1366     EVT ValVT = ValToCopy.getValueType();
1367
1368     // If this is x86-64, and we disabled SSE, we can't return FP values,
1369     // or SSE or MMX vectors.
1370     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1371          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1372           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1373       report_fatal_error("SSE register return with SSE disabled");
1374     }
1375     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1376     // llvm-gcc has never done it right and no one has noticed, so this
1377     // should be OK for now.
1378     if (ValVT == MVT::f64 &&
1379         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1380       report_fatal_error("SSE2 register return with SSE2 disabled");
1381
1382     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1383     // the RET instruction and handled by the FP Stackifier.
1384     if (VA.getLocReg() == X86::ST0 ||
1385         VA.getLocReg() == X86::ST1) {
1386       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1387       // change the value to the FP stack register class.
1388       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1389         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1390       RetOps.push_back(ValToCopy);
1391       // Don't emit a copytoreg.
1392       continue;
1393     }
1394
1395     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1396     // which is returned in RAX / RDX.
1397     if (Subtarget->is64Bit()) {
1398       if (ValVT == MVT::x86mmx) {
1399         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1400           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1401           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1402                                   ValToCopy);
1403           // If we don't have SSE2 available, convert to v4f32 so the generated
1404           // register is legal.
1405           if (!Subtarget->hasSSE2())
1406             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1407         }
1408       }
1409     }
1410
1411     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1412     Flag = Chain.getValue(1);
1413   }
1414
1415   // The x86-64 ABI for returning structs by value requires that we copy
1416   // the sret argument into %rax for the return. We saved the argument into
1417   // a virtual register in the entry block, so now we copy the value out
1418   // and into %rax.
1419   if (Subtarget->is64Bit() &&
1420       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1421     MachineFunction &MF = DAG.getMachineFunction();
1422     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1423     unsigned Reg = FuncInfo->getSRetReturnReg();
1424     assert(Reg &&
1425            "SRetReturnReg should have been set in LowerFormalArguments().");
1426     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1427
1428     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1429     Flag = Chain.getValue(1);
1430
1431     // RAX now acts like a return value.
1432     MRI.addLiveOut(X86::RAX);
1433   }
1434
1435   RetOps[0] = Chain;  // Update chain.
1436
1437   // Add the flag if we have it.
1438   if (Flag.getNode())
1439     RetOps.push_back(Flag);
1440
1441   return DAG.getNode(X86ISD::RET_FLAG, dl,
1442                      MVT::Other, &RetOps[0], RetOps.size());
1443 }
1444
1445 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1446   if (N->getNumValues() != 1)
1447     return false;
1448   if (!N->hasNUsesOfValue(1, 0))
1449     return false;
1450
1451   SDNode *Copy = *N->use_begin();
1452   if (Copy->getOpcode() != ISD::CopyToReg &&
1453       Copy->getOpcode() != ISD::FP_EXTEND)
1454     return false;
1455
1456   bool HasRet = false;
1457   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1458        UI != UE; ++UI) {
1459     if (UI->getOpcode() != X86ISD::RET_FLAG)
1460       return false;
1461     HasRet = true;
1462   }
1463
1464   return HasRet;
1465 }
1466
1467 EVT
1468 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1469                                             ISD::NodeType ExtendKind) const {
1470   MVT ReturnMVT;
1471   // TODO: Is this also valid on 32-bit?
1472   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1473     ReturnMVT = MVT::i8;
1474   else
1475     ReturnMVT = MVT::i32;
1476
1477   EVT MinVT = getRegisterType(Context, ReturnMVT);
1478   return VT.bitsLT(MinVT) ? MinVT : VT;
1479 }
1480
1481 /// LowerCallResult - Lower the result values of a call into the
1482 /// appropriate copies out of appropriate physical registers.
1483 ///
1484 SDValue
1485 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1486                                    CallingConv::ID CallConv, bool isVarArg,
1487                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1488                                    DebugLoc dl, SelectionDAG &DAG,
1489                                    SmallVectorImpl<SDValue> &InVals) const {
1490
1491   // Assign locations to each value returned by this call.
1492   SmallVector<CCValAssign, 16> RVLocs;
1493   bool Is64Bit = Subtarget->is64Bit();
1494   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1495                  getTargetMachine(), RVLocs, *DAG.getContext());
1496   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1497
1498   // Copy all of the result registers out of their specified physreg.
1499   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1500     CCValAssign &VA = RVLocs[i];
1501     EVT CopyVT = VA.getValVT();
1502
1503     // If this is x86-64, and we disabled SSE, we can't return FP values
1504     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1505         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1506       report_fatal_error("SSE register return with SSE disabled");
1507     }
1508
1509     SDValue Val;
1510
1511     // If this is a call to a function that returns an fp value on the floating
1512     // point stack, we must guarantee the the value is popped from the stack, so
1513     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1514     // if the return value is not used. We use the FpGET_ST0 instructions
1515     // instead.
1516     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1517       // If we prefer to use the value in xmm registers, copy it out as f80 and
1518       // use a truncate to move it from fp stack reg to xmm reg.
1519       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1520       bool isST0 = VA.getLocReg() == X86::ST0;
1521       unsigned Opc = 0;
1522       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1523       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1524       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1525       SDValue Ops[] = { Chain, InFlag };
1526       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1527                                          Ops, 2), 1);
1528       Val = Chain.getValue(0);
1529
1530       // Round the f80 to the right size, which also moves it to the appropriate
1531       // xmm register.
1532       if (CopyVT != VA.getValVT())
1533         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1534                           // This truncation won't change the value.
1535                           DAG.getIntPtrConstant(1));
1536     } else {
1537       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1538                                  CopyVT, InFlag).getValue(1);
1539       Val = Chain.getValue(0);
1540     }
1541     InFlag = Chain.getValue(2);
1542     InVals.push_back(Val);
1543   }
1544
1545   return Chain;
1546 }
1547
1548
1549 //===----------------------------------------------------------------------===//
1550 //                C & StdCall & Fast Calling Convention implementation
1551 //===----------------------------------------------------------------------===//
1552 //  StdCall calling convention seems to be standard for many Windows' API
1553 //  routines and around. It differs from C calling convention just a little:
1554 //  callee should clean up the stack, not caller. Symbols should be also
1555 //  decorated in some fancy way :) It doesn't support any vector arguments.
1556 //  For info on fast calling convention see Fast Calling Convention (tail call)
1557 //  implementation LowerX86_32FastCCCallTo.
1558
1559 /// CallIsStructReturn - Determines whether a call uses struct return
1560 /// semantics.
1561 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1562   if (Outs.empty())
1563     return false;
1564
1565   return Outs[0].Flags.isSRet();
1566 }
1567
1568 /// ArgsAreStructReturn - Determines whether a function uses struct
1569 /// return semantics.
1570 static bool
1571 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1572   if (Ins.empty())
1573     return false;
1574
1575   return Ins[0].Flags.isSRet();
1576 }
1577
1578 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1579 /// by "Src" to address "Dst" with size and alignment information specified by
1580 /// the specific parameter attribute. The copy will be passed as a byval
1581 /// function parameter.
1582 static SDValue
1583 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1584                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1585                           DebugLoc dl) {
1586   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1587
1588   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1589                        /*isVolatile*/false, /*AlwaysInline=*/true,
1590                        MachinePointerInfo(), MachinePointerInfo());
1591 }
1592
1593 /// IsTailCallConvention - Return true if the calling convention is one that
1594 /// supports tail call optimization.
1595 static bool IsTailCallConvention(CallingConv::ID CC) {
1596   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1597 }
1598
1599 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1600   if (!CI->isTailCall())
1601     return false;
1602
1603   CallSite CS(CI);
1604   CallingConv::ID CalleeCC = CS.getCallingConv();
1605   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1606     return false;
1607
1608   return true;
1609 }
1610
1611 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1612 /// a tailcall target by changing its ABI.
1613 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1614   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1615 }
1616
1617 SDValue
1618 X86TargetLowering::LowerMemArgument(SDValue Chain,
1619                                     CallingConv::ID CallConv,
1620                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1621                                     DebugLoc dl, SelectionDAG &DAG,
1622                                     const CCValAssign &VA,
1623                                     MachineFrameInfo *MFI,
1624                                     unsigned i) const {
1625   // Create the nodes corresponding to a load from this parameter slot.
1626   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1627   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1628   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1629   EVT ValVT;
1630
1631   // If value is passed by pointer we have address passed instead of the value
1632   // itself.
1633   if (VA.getLocInfo() == CCValAssign::Indirect)
1634     ValVT = VA.getLocVT();
1635   else
1636     ValVT = VA.getValVT();
1637
1638   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1639   // changed with more analysis.
1640   // In case of tail call optimization mark all arguments mutable. Since they
1641   // could be overwritten by lowering of arguments in case of a tail call.
1642   if (Flags.isByVal()) {
1643     unsigned Bytes = Flags.getByValSize();
1644     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1645     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1646     return DAG.getFrameIndex(FI, getPointerTy());
1647   } else {
1648     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1649                                     VA.getLocMemOffset(), isImmutable);
1650     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1651     return DAG.getLoad(ValVT, dl, Chain, FIN,
1652                        MachinePointerInfo::getFixedStack(FI),
1653                        false, false, 0);
1654   }
1655 }
1656
1657 SDValue
1658 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1659                                         CallingConv::ID CallConv,
1660                                         bool isVarArg,
1661                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1662                                         DebugLoc dl,
1663                                         SelectionDAG &DAG,
1664                                         SmallVectorImpl<SDValue> &InVals)
1665                                           const {
1666   MachineFunction &MF = DAG.getMachineFunction();
1667   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1668
1669   const Function* Fn = MF.getFunction();
1670   if (Fn->hasExternalLinkage() &&
1671       Subtarget->isTargetCygMing() &&
1672       Fn->getName() == "main")
1673     FuncInfo->setForceFramePointer(true);
1674
1675   MachineFrameInfo *MFI = MF.getFrameInfo();
1676   bool Is64Bit = Subtarget->is64Bit();
1677   bool IsWin64 = Subtarget->isTargetWin64();
1678
1679   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1680          "Var args not supported with calling convention fastcc or ghc");
1681
1682   // Assign locations to all of the incoming arguments.
1683   SmallVector<CCValAssign, 16> ArgLocs;
1684   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1685                  ArgLocs, *DAG.getContext());
1686
1687   // Allocate shadow area for Win64
1688   if (IsWin64) {
1689     CCInfo.AllocateStack(32, 8);
1690   }
1691
1692   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1693
1694   unsigned LastVal = ~0U;
1695   SDValue ArgValue;
1696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1697     CCValAssign &VA = ArgLocs[i];
1698     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1699     // places.
1700     assert(VA.getValNo() != LastVal &&
1701            "Don't support value assigned to multiple locs yet");
1702     LastVal = VA.getValNo();
1703
1704     if (VA.isRegLoc()) {
1705       EVT RegVT = VA.getLocVT();
1706       TargetRegisterClass *RC = NULL;
1707       if (RegVT == MVT::i32)
1708         RC = X86::GR32RegisterClass;
1709       else if (Is64Bit && RegVT == MVT::i64)
1710         RC = X86::GR64RegisterClass;
1711       else if (RegVT == MVT::f32)
1712         RC = X86::FR32RegisterClass;
1713       else if (RegVT == MVT::f64)
1714         RC = X86::FR64RegisterClass;
1715       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1716         RC = X86::VR256RegisterClass;
1717       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1718         RC = X86::VR128RegisterClass;
1719       else if (RegVT == MVT::x86mmx)
1720         RC = X86::VR64RegisterClass;
1721       else
1722         llvm_unreachable("Unknown argument type!");
1723
1724       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1725       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1726
1727       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1728       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1729       // right size.
1730       if (VA.getLocInfo() == CCValAssign::SExt)
1731         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1732                                DAG.getValueType(VA.getValVT()));
1733       else if (VA.getLocInfo() == CCValAssign::ZExt)
1734         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1735                                DAG.getValueType(VA.getValVT()));
1736       else if (VA.getLocInfo() == CCValAssign::BCvt)
1737         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1738
1739       if (VA.isExtInLoc()) {
1740         // Handle MMX values passed in XMM regs.
1741         if (RegVT.isVector()) {
1742           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1743                                  ArgValue);
1744         } else
1745           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1746       }
1747     } else {
1748       assert(VA.isMemLoc());
1749       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1750     }
1751
1752     // If value is passed via pointer - do a load.
1753     if (VA.getLocInfo() == CCValAssign::Indirect)
1754       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1755                              MachinePointerInfo(), false, false, 0);
1756
1757     InVals.push_back(ArgValue);
1758   }
1759
1760   // The x86-64 ABI for returning structs by value requires that we copy
1761   // the sret argument into %rax for the return. Save the argument into
1762   // a virtual register so that we can access it from the return points.
1763   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1764     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1765     unsigned Reg = FuncInfo->getSRetReturnReg();
1766     if (!Reg) {
1767       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1768       FuncInfo->setSRetReturnReg(Reg);
1769     }
1770     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1771     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1772   }
1773
1774   unsigned StackSize = CCInfo.getNextStackOffset();
1775   // Align stack specially for tail calls.
1776   if (FuncIsMadeTailCallSafe(CallConv))
1777     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1778
1779   // If the function takes variable number of arguments, make a frame index for
1780   // the start of the first vararg value... for expansion of llvm.va_start.
1781   if (isVarArg) {
1782     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1783                     CallConv != CallingConv::X86_ThisCall)) {
1784       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1785     }
1786     if (Is64Bit) {
1787       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1788
1789       // FIXME: We should really autogenerate these arrays
1790       static const unsigned GPR64ArgRegsWin64[] = {
1791         X86::RCX, X86::RDX, X86::R8,  X86::R9
1792       };
1793       static const unsigned GPR64ArgRegs64Bit[] = {
1794         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1795       };
1796       static const unsigned XMMArgRegs64Bit[] = {
1797         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1798         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1799       };
1800       const unsigned *GPR64ArgRegs;
1801       unsigned NumXMMRegs = 0;
1802
1803       if (IsWin64) {
1804         // The XMM registers which might contain var arg parameters are shadowed
1805         // in their paired GPR.  So we only need to save the GPR to their home
1806         // slots.
1807         TotalNumIntRegs = 4;
1808         GPR64ArgRegs = GPR64ArgRegsWin64;
1809       } else {
1810         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1811         GPR64ArgRegs = GPR64ArgRegs64Bit;
1812
1813         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1814       }
1815       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1816                                                        TotalNumIntRegs);
1817
1818       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1819       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1820              "SSE register cannot be used when SSE is disabled!");
1821       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1822              "SSE register cannot be used when SSE is disabled!");
1823       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1824         // Kernel mode asks for SSE to be disabled, so don't push them
1825         // on the stack.
1826         TotalNumXMMRegs = 0;
1827
1828       if (IsWin64) {
1829         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1830         // Get to the caller-allocated home save location.  Add 8 to account
1831         // for the return address.
1832         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1833         FuncInfo->setRegSaveFrameIndex(
1834           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1835         // Fixup to set vararg frame on shadow area (4 x i64).
1836         if (NumIntRegs < 4)
1837           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1838       } else {
1839         // For X86-64, if there are vararg parameters that are passed via
1840         // registers, then we must store them to their spots on the stack so they
1841         // may be loaded by deferencing the result of va_next.
1842         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1843         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1844         FuncInfo->setRegSaveFrameIndex(
1845           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1846                                false));
1847       }
1848
1849       // Store the integer parameter registers.
1850       SmallVector<SDValue, 8> MemOps;
1851       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1852                                         getPointerTy());
1853       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1854       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1855         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1856                                   DAG.getIntPtrConstant(Offset));
1857         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1858                                      X86::GR64RegisterClass);
1859         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1860         SDValue Store =
1861           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1862                        MachinePointerInfo::getFixedStack(
1863                          FuncInfo->getRegSaveFrameIndex(), Offset),
1864                        false, false, 0);
1865         MemOps.push_back(Store);
1866         Offset += 8;
1867       }
1868
1869       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1870         // Now store the XMM (fp + vector) parameter registers.
1871         SmallVector<SDValue, 11> SaveXMMOps;
1872         SaveXMMOps.push_back(Chain);
1873
1874         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1875         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1876         SaveXMMOps.push_back(ALVal);
1877
1878         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879                                FuncInfo->getRegSaveFrameIndex()));
1880         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1881                                FuncInfo->getVarArgsFPOffset()));
1882
1883         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1884           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1885                                        X86::VR128RegisterClass);
1886           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1887           SaveXMMOps.push_back(Val);
1888         }
1889         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1890                                      MVT::Other,
1891                                      &SaveXMMOps[0], SaveXMMOps.size()));
1892       }
1893
1894       if (!MemOps.empty())
1895         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1896                             &MemOps[0], MemOps.size());
1897     }
1898   }
1899
1900   // Some CCs need callee pop.
1901   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1902     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1903   } else {
1904     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1905     // If this is an sret function, the return should pop the hidden pointer.
1906     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1907       FuncInfo->setBytesToPopOnReturn(4);
1908   }
1909
1910   if (!Is64Bit) {
1911     // RegSaveFrameIndex is X86-64 only.
1912     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1913     if (CallConv == CallingConv::X86_FastCall ||
1914         CallConv == CallingConv::X86_ThisCall)
1915       // fastcc functions can't have varargs.
1916       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1917   }
1918
1919   return Chain;
1920 }
1921
1922 SDValue
1923 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1924                                     SDValue StackPtr, SDValue Arg,
1925                                     DebugLoc dl, SelectionDAG &DAG,
1926                                     const CCValAssign &VA,
1927                                     ISD::ArgFlagsTy Flags) const {
1928   unsigned LocMemOffset = VA.getLocMemOffset();
1929   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1930   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1931   if (Flags.isByVal())
1932     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1933
1934   return DAG.getStore(Chain, dl, Arg, PtrOff,
1935                       MachinePointerInfo::getStack(LocMemOffset),
1936                       false, false, 0);
1937 }
1938
1939 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1940 /// optimization is performed and it is required.
1941 SDValue
1942 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1943                                            SDValue &OutRetAddr, SDValue Chain,
1944                                            bool IsTailCall, bool Is64Bit,
1945                                            int FPDiff, DebugLoc dl) const {
1946   // Adjust the Return address stack slot.
1947   EVT VT = getPointerTy();
1948   OutRetAddr = getReturnAddressFrameIndex(DAG);
1949
1950   // Load the "old" Return address.
1951   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1952                            false, false, 0);
1953   return SDValue(OutRetAddr.getNode(), 1);
1954 }
1955
1956 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1957 /// optimization is performed and it is required (FPDiff!=0).
1958 static SDValue
1959 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1960                          SDValue Chain, SDValue RetAddrFrIdx,
1961                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1962   // Store the return address to the appropriate stack slot.
1963   if (!FPDiff) return Chain;
1964   // Calculate the new stack slot for the return address.
1965   int SlotSize = Is64Bit ? 8 : 4;
1966   int NewReturnAddrFI =
1967     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1968   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1969   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1970   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1971                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1972                        false, false, 0);
1973   return Chain;
1974 }
1975
1976 SDValue
1977 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1978                              CallingConv::ID CallConv, bool isVarArg,
1979                              bool &isTailCall,
1980                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                              const SmallVectorImpl<SDValue> &OutVals,
1982                              const SmallVectorImpl<ISD::InputArg> &Ins,
1983                              DebugLoc dl, SelectionDAG &DAG,
1984                              SmallVectorImpl<SDValue> &InVals) const {
1985   MachineFunction &MF = DAG.getMachineFunction();
1986   bool Is64Bit        = Subtarget->is64Bit();
1987   bool IsWin64        = Subtarget->isTargetWin64();
1988   bool IsStructRet    = CallIsStructReturn(Outs);
1989   bool IsSibcall      = false;
1990
1991   if (isTailCall) {
1992     // Check if it's really possible to do a tail call.
1993     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1994                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1995                                                    Outs, OutVals, Ins, DAG);
1996
1997     // Sibcalls are automatically detected tailcalls which do not require
1998     // ABI changes.
1999     if (!GuaranteedTailCallOpt && isTailCall)
2000       IsSibcall = true;
2001
2002     if (isTailCall)
2003       ++NumTailCalls;
2004   }
2005
2006   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2007          "Var args not supported with calling convention fastcc or ghc");
2008
2009   // Analyze operands of the call, assigning locations to each operand.
2010   SmallVector<CCValAssign, 16> ArgLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2012                  ArgLocs, *DAG.getContext());
2013
2014   // Allocate shadow area for Win64
2015   if (IsWin64) {
2016     CCInfo.AllocateStack(32, 8);
2017   }
2018
2019   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2020
2021   // Get a count of how many bytes are to be pushed on the stack.
2022   unsigned NumBytes = CCInfo.getNextStackOffset();
2023   if (IsSibcall)
2024     // This is a sibcall. The memory operands are available in caller's
2025     // own caller's stack.
2026     NumBytes = 0;
2027   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2028     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2029
2030   int FPDiff = 0;
2031   if (isTailCall && !IsSibcall) {
2032     // Lower arguments at fp - stackoffset + fpdiff.
2033     unsigned NumBytesCallerPushed =
2034       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2035     FPDiff = NumBytesCallerPushed - NumBytes;
2036
2037     // Set the delta of movement of the returnaddr stackslot.
2038     // But only set if delta is greater than previous delta.
2039     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2040       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2041   }
2042
2043   if (!IsSibcall)
2044     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2045
2046   SDValue RetAddrFrIdx;
2047   // Load return address for tail calls.
2048   if (isTailCall && FPDiff)
2049     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2050                                     Is64Bit, FPDiff, dl);
2051
2052   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2053   SmallVector<SDValue, 8> MemOpChains;
2054   SDValue StackPtr;
2055
2056   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2057   // of tail call optimization arguments are handle later.
2058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2059     CCValAssign &VA = ArgLocs[i];
2060     EVT RegVT = VA.getLocVT();
2061     SDValue Arg = OutVals[i];
2062     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2063     bool isByVal = Flags.isByVal();
2064
2065     // Promote the value if needed.
2066     switch (VA.getLocInfo()) {
2067     default: llvm_unreachable("Unknown loc info!");
2068     case CCValAssign::Full: break;
2069     case CCValAssign::SExt:
2070       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2071       break;
2072     case CCValAssign::ZExt:
2073       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2074       break;
2075     case CCValAssign::AExt:
2076       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2077         // Special case: passing MMX values in XMM registers.
2078         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2079         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2080         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2081       } else
2082         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2083       break;
2084     case CCValAssign::BCvt:
2085       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2086       break;
2087     case CCValAssign::Indirect: {
2088       // Store the argument.
2089       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2090       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2091       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2092                            MachinePointerInfo::getFixedStack(FI),
2093                            false, false, 0);
2094       Arg = SpillSlot;
2095       break;
2096     }
2097     }
2098
2099     if (VA.isRegLoc()) {
2100       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2101       if (isVarArg && IsWin64) {
2102         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2103         // shadow reg if callee is a varargs function.
2104         unsigned ShadowReg = 0;
2105         switch (VA.getLocReg()) {
2106         case X86::XMM0: ShadowReg = X86::RCX; break;
2107         case X86::XMM1: ShadowReg = X86::RDX; break;
2108         case X86::XMM2: ShadowReg = X86::R8; break;
2109         case X86::XMM3: ShadowReg = X86::R9; break;
2110         }
2111         if (ShadowReg)
2112           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2113       }
2114     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2115       assert(VA.isMemLoc());
2116       if (StackPtr.getNode() == 0)
2117         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2118       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2119                                              dl, DAG, VA, Flags));
2120     }
2121   }
2122
2123   if (!MemOpChains.empty())
2124     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2125                         &MemOpChains[0], MemOpChains.size());
2126
2127   // Build a sequence of copy-to-reg nodes chained together with token chain
2128   // and flag operands which copy the outgoing args into registers.
2129   SDValue InFlag;
2130   // Tail call byval lowering might overwrite argument registers so in case of
2131   // tail call optimization the copies to registers are lowered later.
2132   if (!isTailCall)
2133     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2134       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2135                                RegsToPass[i].second, InFlag);
2136       InFlag = Chain.getValue(1);
2137     }
2138
2139   if (Subtarget->isPICStyleGOT()) {
2140     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2141     // GOT pointer.
2142     if (!isTailCall) {
2143       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2144                                DAG.getNode(X86ISD::GlobalBaseReg,
2145                                            DebugLoc(), getPointerTy()),
2146                                InFlag);
2147       InFlag = Chain.getValue(1);
2148     } else {
2149       // If we are tail calling and generating PIC/GOT style code load the
2150       // address of the callee into ECX. The value in ecx is used as target of
2151       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2152       // for tail calls on PIC/GOT architectures. Normally we would just put the
2153       // address of GOT into ebx and then call target@PLT. But for tail calls
2154       // ebx would be restored (since ebx is callee saved) before jumping to the
2155       // target@PLT.
2156
2157       // Note: The actual moving to ECX is done further down.
2158       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2159       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2160           !G->getGlobal()->hasProtectedVisibility())
2161         Callee = LowerGlobalAddress(Callee, DAG);
2162       else if (isa<ExternalSymbolSDNode>(Callee))
2163         Callee = LowerExternalSymbol(Callee, DAG);
2164     }
2165   }
2166
2167   if (Is64Bit && isVarArg && !IsWin64) {
2168     // From AMD64 ABI document:
2169     // For calls that may call functions that use varargs or stdargs
2170     // (prototype-less calls or calls to functions containing ellipsis (...) in
2171     // the declaration) %al is used as hidden argument to specify the number
2172     // of SSE registers used. The contents of %al do not need to match exactly
2173     // the number of registers, but must be an ubound on the number of SSE
2174     // registers used and is in the range 0 - 8 inclusive.
2175
2176     // Count the number of XMM registers allocated.
2177     static const unsigned XMMArgRegs[] = {
2178       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2179       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2180     };
2181     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2182     assert((Subtarget->hasXMM() || !NumXMMRegs)
2183            && "SSE registers cannot be used when SSE is disabled");
2184
2185     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2186                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2187     InFlag = Chain.getValue(1);
2188   }
2189
2190
2191   // For tail calls lower the arguments to the 'real' stack slot.
2192   if (isTailCall) {
2193     // Force all the incoming stack arguments to be loaded from the stack
2194     // before any new outgoing arguments are stored to the stack, because the
2195     // outgoing stack slots may alias the incoming argument stack slots, and
2196     // the alias isn't otherwise explicit. This is slightly more conservative
2197     // than necessary, because it means that each store effectively depends
2198     // on every argument instead of just those arguments it would clobber.
2199     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2200
2201     SmallVector<SDValue, 8> MemOpChains2;
2202     SDValue FIN;
2203     int FI = 0;
2204     // Do not flag preceding copytoreg stuff together with the following stuff.
2205     InFlag = SDValue();
2206     if (GuaranteedTailCallOpt) {
2207       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2208         CCValAssign &VA = ArgLocs[i];
2209         if (VA.isRegLoc())
2210           continue;
2211         assert(VA.isMemLoc());
2212         SDValue Arg = OutVals[i];
2213         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2214         // Create frame index.
2215         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2216         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2217         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2218         FIN = DAG.getFrameIndex(FI, getPointerTy());
2219
2220         if (Flags.isByVal()) {
2221           // Copy relative to framepointer.
2222           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2223           if (StackPtr.getNode() == 0)
2224             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2225                                           getPointerTy());
2226           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2227
2228           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2229                                                            ArgChain,
2230                                                            Flags, DAG, dl));
2231         } else {
2232           // Store relative to framepointer.
2233           MemOpChains2.push_back(
2234             DAG.getStore(ArgChain, dl, Arg, FIN,
2235                          MachinePointerInfo::getFixedStack(FI),
2236                          false, false, 0));
2237         }
2238       }
2239     }
2240
2241     if (!MemOpChains2.empty())
2242       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2243                           &MemOpChains2[0], MemOpChains2.size());
2244
2245     // Copy arguments to their registers.
2246     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2247       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2248                                RegsToPass[i].second, InFlag);
2249       InFlag = Chain.getValue(1);
2250     }
2251     InFlag =SDValue();
2252
2253     // Store the return address to the appropriate stack slot.
2254     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2255                                      FPDiff, dl);
2256   }
2257
2258   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2259     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2260     // In the 64-bit large code model, we have to make all calls
2261     // through a register, since the call instruction's 32-bit
2262     // pc-relative offset may not be large enough to hold the whole
2263     // address.
2264   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2265     // If the callee is a GlobalAddress node (quite common, every direct call
2266     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2267     // it.
2268
2269     // We should use extra load for direct calls to dllimported functions in
2270     // non-JIT mode.
2271     const GlobalValue *GV = G->getGlobal();
2272     if (!GV->hasDLLImportLinkage()) {
2273       unsigned char OpFlags = 0;
2274       bool ExtraLoad = false;
2275       unsigned WrapperKind = ISD::DELETED_NODE;
2276
2277       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2278       // external symbols most go through the PLT in PIC mode.  If the symbol
2279       // has hidden or protected visibility, or if it is static or local, then
2280       // we don't need to use the PLT - we can directly call it.
2281       if (Subtarget->isTargetELF() &&
2282           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2283           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2284         OpFlags = X86II::MO_PLT;
2285       } else if (Subtarget->isPICStyleStubAny() &&
2286                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2287                  (!Subtarget->getTargetTriple().isMacOSX() ||
2288                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2289         // PC-relative references to external symbols should go through $stub,
2290         // unless we're building with the leopard linker or later, which
2291         // automatically synthesizes these stubs.
2292         OpFlags = X86II::MO_DARWIN_STUB;
2293       } else if (Subtarget->isPICStyleRIPRel() &&
2294                  isa<Function>(GV) &&
2295                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2296         // If the function is marked as non-lazy, generate an indirect call
2297         // which loads from the GOT directly. This avoids runtime overhead
2298         // at the cost of eager binding (and one extra byte of encoding).
2299         OpFlags = X86II::MO_GOTPCREL;
2300         WrapperKind = X86ISD::WrapperRIP;
2301         ExtraLoad = true;
2302       }
2303
2304       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2305                                           G->getOffset(), OpFlags);
2306
2307       // Add a wrapper if needed.
2308       if (WrapperKind != ISD::DELETED_NODE)
2309         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2310       // Add extra indirection if needed.
2311       if (ExtraLoad)
2312         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2313                              MachinePointerInfo::getGOT(),
2314                              false, false, 0);
2315     }
2316   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2317     unsigned char OpFlags = 0;
2318
2319     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2320     // external symbols should go through the PLT.
2321     if (Subtarget->isTargetELF() &&
2322         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2323       OpFlags = X86II::MO_PLT;
2324     } else if (Subtarget->isPICStyleStubAny() &&
2325                (!Subtarget->getTargetTriple().isMacOSX() ||
2326                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2327       // PC-relative references to external symbols should go through $stub,
2328       // unless we're building with the leopard linker or later, which
2329       // automatically synthesizes these stubs.
2330       OpFlags = X86II::MO_DARWIN_STUB;
2331     }
2332
2333     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2334                                          OpFlags);
2335   }
2336
2337   // Returns a chain & a flag for retval copy to use.
2338   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2339   SmallVector<SDValue, 8> Ops;
2340
2341   if (!IsSibcall && isTailCall) {
2342     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2343                            DAG.getIntPtrConstant(0, true), InFlag);
2344     InFlag = Chain.getValue(1);
2345   }
2346
2347   Ops.push_back(Chain);
2348   Ops.push_back(Callee);
2349
2350   if (isTailCall)
2351     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2352
2353   // Add argument registers to the end of the list so that they are known live
2354   // into the call.
2355   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2356     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2357                                   RegsToPass[i].second.getValueType()));
2358
2359   // Add an implicit use GOT pointer in EBX.
2360   if (!isTailCall && Subtarget->isPICStyleGOT())
2361     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2362
2363   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2364   if (Is64Bit && isVarArg && !IsWin64)
2365     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2366
2367   if (InFlag.getNode())
2368     Ops.push_back(InFlag);
2369
2370   if (isTailCall) {
2371     // We used to do:
2372     //// If this is the first return lowered for this function, add the regs
2373     //// to the liveout set for the function.
2374     // This isn't right, although it's probably harmless on x86; liveouts
2375     // should be computed from returns not tail calls.  Consider a void
2376     // function making a tail call to a function returning int.
2377     return DAG.getNode(X86ISD::TC_RETURN, dl,
2378                        NodeTys, &Ops[0], Ops.size());
2379   }
2380
2381   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2382   InFlag = Chain.getValue(1);
2383
2384   // Create the CALLSEQ_END node.
2385   unsigned NumBytesForCalleeToPush;
2386   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2387     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2388   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2389     // If this is a call to a struct-return function, the callee
2390     // pops the hidden struct pointer, so we have to push it back.
2391     // This is common for Darwin/X86, Linux & Mingw32 targets.
2392     NumBytesForCalleeToPush = 4;
2393   else
2394     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2395
2396   // Returns a flag for retval copy to use.
2397   if (!IsSibcall) {
2398     Chain = DAG.getCALLSEQ_END(Chain,
2399                                DAG.getIntPtrConstant(NumBytes, true),
2400                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2401                                                      true),
2402                                InFlag);
2403     InFlag = Chain.getValue(1);
2404   }
2405
2406   // Handle result values, copying them out of physregs into vregs that we
2407   // return.
2408   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2409                          Ins, dl, DAG, InVals);
2410 }
2411
2412
2413 //===----------------------------------------------------------------------===//
2414 //                Fast Calling Convention (tail call) implementation
2415 //===----------------------------------------------------------------------===//
2416
2417 //  Like std call, callee cleans arguments, convention except that ECX is
2418 //  reserved for storing the tail called function address. Only 2 registers are
2419 //  free for argument passing (inreg). Tail call optimization is performed
2420 //  provided:
2421 //                * tailcallopt is enabled
2422 //                * caller/callee are fastcc
2423 //  On X86_64 architecture with GOT-style position independent code only local
2424 //  (within module) calls are supported at the moment.
2425 //  To keep the stack aligned according to platform abi the function
2426 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2427 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2428 //  If a tail called function callee has more arguments than the caller the
2429 //  caller needs to make sure that there is room to move the RETADDR to. This is
2430 //  achieved by reserving an area the size of the argument delta right after the
2431 //  original REtADDR, but before the saved framepointer or the spilled registers
2432 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2433 //  stack layout:
2434 //    arg1
2435 //    arg2
2436 //    RETADDR
2437 //    [ new RETADDR
2438 //      move area ]
2439 //    (possible EBP)
2440 //    ESI
2441 //    EDI
2442 //    local1 ..
2443
2444 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2445 /// for a 16 byte align requirement.
2446 unsigned
2447 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2448                                                SelectionDAG& DAG) const {
2449   MachineFunction &MF = DAG.getMachineFunction();
2450   const TargetMachine &TM = MF.getTarget();
2451   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2452   unsigned StackAlignment = TFI.getStackAlignment();
2453   uint64_t AlignMask = StackAlignment - 1;
2454   int64_t Offset = StackSize;
2455   uint64_t SlotSize = TD->getPointerSize();
2456   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2457     // Number smaller than 12 so just add the difference.
2458     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2459   } else {
2460     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2461     Offset = ((~AlignMask) & Offset) + StackAlignment +
2462       (StackAlignment-SlotSize);
2463   }
2464   return Offset;
2465 }
2466
2467 /// MatchingStackOffset - Return true if the given stack call argument is
2468 /// already available in the same position (relatively) of the caller's
2469 /// incoming argument stack.
2470 static
2471 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2472                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2473                          const X86InstrInfo *TII) {
2474   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2475   int FI = INT_MAX;
2476   if (Arg.getOpcode() == ISD::CopyFromReg) {
2477     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2478     if (!TargetRegisterInfo::isVirtualRegister(VR))
2479       return false;
2480     MachineInstr *Def = MRI->getVRegDef(VR);
2481     if (!Def)
2482       return false;
2483     if (!Flags.isByVal()) {
2484       if (!TII->isLoadFromStackSlot(Def, FI))
2485         return false;
2486     } else {
2487       unsigned Opcode = Def->getOpcode();
2488       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2489           Def->getOperand(1).isFI()) {
2490         FI = Def->getOperand(1).getIndex();
2491         Bytes = Flags.getByValSize();
2492       } else
2493         return false;
2494     }
2495   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2496     if (Flags.isByVal())
2497       // ByVal argument is passed in as a pointer but it's now being
2498       // dereferenced. e.g.
2499       // define @foo(%struct.X* %A) {
2500       //   tail call @bar(%struct.X* byval %A)
2501       // }
2502       return false;
2503     SDValue Ptr = Ld->getBasePtr();
2504     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2505     if (!FINode)
2506       return false;
2507     FI = FINode->getIndex();
2508   } else
2509     return false;
2510
2511   assert(FI != INT_MAX);
2512   if (!MFI->isFixedObjectIndex(FI))
2513     return false;
2514   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2515 }
2516
2517 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2518 /// for tail call optimization. Targets which want to do tail call
2519 /// optimization should implement this function.
2520 bool
2521 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2522                                                      CallingConv::ID CalleeCC,
2523                                                      bool isVarArg,
2524                                                      bool isCalleeStructRet,
2525                                                      bool isCallerStructRet,
2526                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2527                                     const SmallVectorImpl<SDValue> &OutVals,
2528                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2529                                                      SelectionDAG& DAG) const {
2530   if (!IsTailCallConvention(CalleeCC) &&
2531       CalleeCC != CallingConv::C)
2532     return false;
2533
2534   // If -tailcallopt is specified, make fastcc functions tail-callable.
2535   const MachineFunction &MF = DAG.getMachineFunction();
2536   const Function *CallerF = DAG.getMachineFunction().getFunction();
2537   CallingConv::ID CallerCC = CallerF->getCallingConv();
2538   bool CCMatch = CallerCC == CalleeCC;
2539
2540   if (GuaranteedTailCallOpt) {
2541     if (IsTailCallConvention(CalleeCC) && CCMatch)
2542       return true;
2543     return false;
2544   }
2545
2546   // Look for obvious safe cases to perform tail call optimization that do not
2547   // require ABI changes. This is what gcc calls sibcall.
2548
2549   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2550   // emit a special epilogue.
2551   if (RegInfo->needsStackRealignment(MF))
2552     return false;
2553
2554   // Also avoid sibcall optimization if either caller or callee uses struct
2555   // return semantics.
2556   if (isCalleeStructRet || isCallerStructRet)
2557     return false;
2558
2559   // Do not sibcall optimize vararg calls unless all arguments are passed via
2560   // registers.
2561   if (isVarArg && !Outs.empty()) {
2562
2563     // Optimizing for varargs on Win64 is unlikely to be safe without
2564     // additional testing.
2565     if (Subtarget->isTargetWin64())
2566       return false;
2567
2568     SmallVector<CCValAssign, 16> ArgLocs;
2569     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2570                    getTargetMachine(), ArgLocs, *DAG.getContext());
2571
2572     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2574       if (!ArgLocs[i].isRegLoc())
2575         return false;
2576   }
2577
2578   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2579   // Therefore if it's not used by the call it is not safe to optimize this into
2580   // a sibcall.
2581   bool Unused = false;
2582   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2583     if (!Ins[i].Used) {
2584       Unused = true;
2585       break;
2586     }
2587   }
2588   if (Unused) {
2589     SmallVector<CCValAssign, 16> RVLocs;
2590     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2591                    getTargetMachine(), RVLocs, *DAG.getContext());
2592     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2593     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2594       CCValAssign &VA = RVLocs[i];
2595       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2596         return false;
2597     }
2598   }
2599
2600   // If the calling conventions do not match, then we'd better make sure the
2601   // results are returned in the same way as what the caller expects.
2602   if (!CCMatch) {
2603     SmallVector<CCValAssign, 16> RVLocs1;
2604     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2605                     getTargetMachine(), RVLocs1, *DAG.getContext());
2606     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2607
2608     SmallVector<CCValAssign, 16> RVLocs2;
2609     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2610                     getTargetMachine(), RVLocs2, *DAG.getContext());
2611     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2612
2613     if (RVLocs1.size() != RVLocs2.size())
2614       return false;
2615     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2616       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2617         return false;
2618       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2619         return false;
2620       if (RVLocs1[i].isRegLoc()) {
2621         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2622           return false;
2623       } else {
2624         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2625           return false;
2626       }
2627     }
2628   }
2629
2630   // If the callee takes no arguments then go on to check the results of the
2631   // call.
2632   if (!Outs.empty()) {
2633     // Check if stack adjustment is needed. For now, do not do this if any
2634     // argument is passed on the stack.
2635     SmallVector<CCValAssign, 16> ArgLocs;
2636     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2637                    getTargetMachine(), ArgLocs, *DAG.getContext());
2638
2639     // Allocate shadow area for Win64
2640     if (Subtarget->isTargetWin64()) {
2641       CCInfo.AllocateStack(32, 8);
2642     }
2643
2644     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2645     if (CCInfo.getNextStackOffset()) {
2646       MachineFunction &MF = DAG.getMachineFunction();
2647       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2648         return false;
2649
2650       // Check if the arguments are already laid out in the right way as
2651       // the caller's fixed stack objects.
2652       MachineFrameInfo *MFI = MF.getFrameInfo();
2653       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2654       const X86InstrInfo *TII =
2655         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2656       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657         CCValAssign &VA = ArgLocs[i];
2658         SDValue Arg = OutVals[i];
2659         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2660         if (VA.getLocInfo() == CCValAssign::Indirect)
2661           return false;
2662         if (!VA.isRegLoc()) {
2663           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2664                                    MFI, MRI, TII))
2665             return false;
2666         }
2667       }
2668     }
2669
2670     // If the tailcall address may be in a register, then make sure it's
2671     // possible to register allocate for it. In 32-bit, the call address can
2672     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2673     // callee-saved registers are restored. These happen to be the same
2674     // registers used to pass 'inreg' arguments so watch out for those.
2675     if (!Subtarget->is64Bit() &&
2676         !isa<GlobalAddressSDNode>(Callee) &&
2677         !isa<ExternalSymbolSDNode>(Callee)) {
2678       unsigned NumInRegs = 0;
2679       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2680         CCValAssign &VA = ArgLocs[i];
2681         if (!VA.isRegLoc())
2682           continue;
2683         unsigned Reg = VA.getLocReg();
2684         switch (Reg) {
2685         default: break;
2686         case X86::EAX: case X86::EDX: case X86::ECX:
2687           if (++NumInRegs == 3)
2688             return false;
2689           break;
2690         }
2691       }
2692     }
2693   }
2694
2695   // An stdcall caller is expected to clean up its arguments; the callee
2696   // isn't going to do that.
2697   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2698     return false;
2699
2700   return true;
2701 }
2702
2703 FastISel *
2704 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2705   return X86::createFastISel(funcInfo);
2706 }
2707
2708
2709 //===----------------------------------------------------------------------===//
2710 //                           Other Lowering Hooks
2711 //===----------------------------------------------------------------------===//
2712
2713 static bool MayFoldLoad(SDValue Op) {
2714   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2715 }
2716
2717 static bool MayFoldIntoStore(SDValue Op) {
2718   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2719 }
2720
2721 static bool isTargetShuffle(unsigned Opcode) {
2722   switch(Opcode) {
2723   default: return false;
2724   case X86ISD::PSHUFD:
2725   case X86ISD::PSHUFHW:
2726   case X86ISD::PSHUFLW:
2727   case X86ISD::SHUFPD:
2728   case X86ISD::PALIGN:
2729   case X86ISD::SHUFPS:
2730   case X86ISD::MOVLHPS:
2731   case X86ISD::MOVLHPD:
2732   case X86ISD::MOVHLPS:
2733   case X86ISD::MOVLPS:
2734   case X86ISD::MOVLPD:
2735   case X86ISD::MOVSHDUP:
2736   case X86ISD::MOVSLDUP:
2737   case X86ISD::MOVDDUP:
2738   case X86ISD::MOVSS:
2739   case X86ISD::MOVSD:
2740   case X86ISD::UNPCKLPS:
2741   case X86ISD::UNPCKLPD:
2742   case X86ISD::VUNPCKLPS:
2743   case X86ISD::VUNPCKLPD:
2744   case X86ISD::VUNPCKLPSY:
2745   case X86ISD::VUNPCKLPDY:
2746   case X86ISD::PUNPCKLWD:
2747   case X86ISD::PUNPCKLBW:
2748   case X86ISD::PUNPCKLDQ:
2749   case X86ISD::PUNPCKLQDQ:
2750   case X86ISD::UNPCKHPS:
2751   case X86ISD::UNPCKHPD:
2752   case X86ISD::PUNPCKHWD:
2753   case X86ISD::PUNPCKHBW:
2754   case X86ISD::PUNPCKHDQ:
2755   case X86ISD::PUNPCKHQDQ:
2756     return true;
2757   }
2758   return false;
2759 }
2760
2761 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2762                                                SDValue V1, SelectionDAG &DAG) {
2763   switch(Opc) {
2764   default: llvm_unreachable("Unknown x86 shuffle node");
2765   case X86ISD::MOVSHDUP:
2766   case X86ISD::MOVSLDUP:
2767   case X86ISD::MOVDDUP:
2768     return DAG.getNode(Opc, dl, VT, V1);
2769   }
2770
2771   return SDValue();
2772 }
2773
2774 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2775                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2776   switch(Opc) {
2777   default: llvm_unreachable("Unknown x86 shuffle node");
2778   case X86ISD::PSHUFD:
2779   case X86ISD::PSHUFHW:
2780   case X86ISD::PSHUFLW:
2781     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2782   }
2783
2784   return SDValue();
2785 }
2786
2787 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2788                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2789   switch(Opc) {
2790   default: llvm_unreachable("Unknown x86 shuffle node");
2791   case X86ISD::PALIGN:
2792   case X86ISD::SHUFPD:
2793   case X86ISD::SHUFPS:
2794     return DAG.getNode(Opc, dl, VT, V1, V2,
2795                        DAG.getConstant(TargetMask, MVT::i8));
2796   }
2797   return SDValue();
2798 }
2799
2800 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2801                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2802   switch(Opc) {
2803   default: llvm_unreachable("Unknown x86 shuffle node");
2804   case X86ISD::MOVLHPS:
2805   case X86ISD::MOVLHPD:
2806   case X86ISD::MOVHLPS:
2807   case X86ISD::MOVLPS:
2808   case X86ISD::MOVLPD:
2809   case X86ISD::MOVSS:
2810   case X86ISD::MOVSD:
2811   case X86ISD::UNPCKLPS:
2812   case X86ISD::UNPCKLPD:
2813   case X86ISD::VUNPCKLPS:
2814   case X86ISD::VUNPCKLPD:
2815   case X86ISD::VUNPCKLPSY:
2816   case X86ISD::VUNPCKLPDY:
2817   case X86ISD::PUNPCKLWD:
2818   case X86ISD::PUNPCKLBW:
2819   case X86ISD::PUNPCKLDQ:
2820   case X86ISD::PUNPCKLQDQ:
2821   case X86ISD::UNPCKHPS:
2822   case X86ISD::UNPCKHPD:
2823   case X86ISD::PUNPCKHWD:
2824   case X86ISD::PUNPCKHBW:
2825   case X86ISD::PUNPCKHDQ:
2826   case X86ISD::PUNPCKHQDQ:
2827     return DAG.getNode(Opc, dl, VT, V1, V2);
2828   }
2829   return SDValue();
2830 }
2831
2832 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2833   MachineFunction &MF = DAG.getMachineFunction();
2834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2835   int ReturnAddrIndex = FuncInfo->getRAIndex();
2836
2837   if (ReturnAddrIndex == 0) {
2838     // Set up a frame object for the return address.
2839     uint64_t SlotSize = TD->getPointerSize();
2840     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2841                                                            false);
2842     FuncInfo->setRAIndex(ReturnAddrIndex);
2843   }
2844
2845   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2846 }
2847
2848
2849 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2850                                        bool hasSymbolicDisplacement) {
2851   // Offset should fit into 32 bit immediate field.
2852   if (!isInt<32>(Offset))
2853     return false;
2854
2855   // If we don't have a symbolic displacement - we don't have any extra
2856   // restrictions.
2857   if (!hasSymbolicDisplacement)
2858     return true;
2859
2860   // FIXME: Some tweaks might be needed for medium code model.
2861   if (M != CodeModel::Small && M != CodeModel::Kernel)
2862     return false;
2863
2864   // For small code model we assume that latest object is 16MB before end of 31
2865   // bits boundary. We may also accept pretty large negative constants knowing
2866   // that all objects are in the positive half of address space.
2867   if (M == CodeModel::Small && Offset < 16*1024*1024)
2868     return true;
2869
2870   // For kernel code model we know that all object resist in the negative half
2871   // of 32bits address space. We may not accept negative offsets, since they may
2872   // be just off and we may accept pretty large positive ones.
2873   if (M == CodeModel::Kernel && Offset > 0)
2874     return true;
2875
2876   return false;
2877 }
2878
2879 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2880 /// specific condition code, returning the condition code and the LHS/RHS of the
2881 /// comparison to make.
2882 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2883                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2884   if (!isFP) {
2885     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2886       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2887         // X > -1   -> X == 0, jump !sign.
2888         RHS = DAG.getConstant(0, RHS.getValueType());
2889         return X86::COND_NS;
2890       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2891         // X < 0   -> X == 0, jump on sign.
2892         return X86::COND_S;
2893       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2894         // X < 1   -> X <= 0
2895         RHS = DAG.getConstant(0, RHS.getValueType());
2896         return X86::COND_LE;
2897       }
2898     }
2899
2900     switch (SetCCOpcode) {
2901     default: llvm_unreachable("Invalid integer condition!");
2902     case ISD::SETEQ:  return X86::COND_E;
2903     case ISD::SETGT:  return X86::COND_G;
2904     case ISD::SETGE:  return X86::COND_GE;
2905     case ISD::SETLT:  return X86::COND_L;
2906     case ISD::SETLE:  return X86::COND_LE;
2907     case ISD::SETNE:  return X86::COND_NE;
2908     case ISD::SETULT: return X86::COND_B;
2909     case ISD::SETUGT: return X86::COND_A;
2910     case ISD::SETULE: return X86::COND_BE;
2911     case ISD::SETUGE: return X86::COND_AE;
2912     }
2913   }
2914
2915   // First determine if it is required or is profitable to flip the operands.
2916
2917   // If LHS is a foldable load, but RHS is not, flip the condition.
2918   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2919       !ISD::isNON_EXTLoad(RHS.getNode())) {
2920     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2921     std::swap(LHS, RHS);
2922   }
2923
2924   switch (SetCCOpcode) {
2925   default: break;
2926   case ISD::SETOLT:
2927   case ISD::SETOLE:
2928   case ISD::SETUGT:
2929   case ISD::SETUGE:
2930     std::swap(LHS, RHS);
2931     break;
2932   }
2933
2934   // On a floating point condition, the flags are set as follows:
2935   // ZF  PF  CF   op
2936   //  0 | 0 | 0 | X > Y
2937   //  0 | 0 | 1 | X < Y
2938   //  1 | 0 | 0 | X == Y
2939   //  1 | 1 | 1 | unordered
2940   switch (SetCCOpcode) {
2941   default: llvm_unreachable("Condcode should be pre-legalized away");
2942   case ISD::SETUEQ:
2943   case ISD::SETEQ:   return X86::COND_E;
2944   case ISD::SETOLT:              // flipped
2945   case ISD::SETOGT:
2946   case ISD::SETGT:   return X86::COND_A;
2947   case ISD::SETOLE:              // flipped
2948   case ISD::SETOGE:
2949   case ISD::SETGE:   return X86::COND_AE;
2950   case ISD::SETUGT:              // flipped
2951   case ISD::SETULT:
2952   case ISD::SETLT:   return X86::COND_B;
2953   case ISD::SETUGE:              // flipped
2954   case ISD::SETULE:
2955   case ISD::SETLE:   return X86::COND_BE;
2956   case ISD::SETONE:
2957   case ISD::SETNE:   return X86::COND_NE;
2958   case ISD::SETUO:   return X86::COND_P;
2959   case ISD::SETO:    return X86::COND_NP;
2960   case ISD::SETOEQ:
2961   case ISD::SETUNE:  return X86::COND_INVALID;
2962   }
2963 }
2964
2965 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2966 /// code. Current x86 isa includes the following FP cmov instructions:
2967 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2968 static bool hasFPCMov(unsigned X86CC) {
2969   switch (X86CC) {
2970   default:
2971     return false;
2972   case X86::COND_B:
2973   case X86::COND_BE:
2974   case X86::COND_E:
2975   case X86::COND_P:
2976   case X86::COND_A:
2977   case X86::COND_AE:
2978   case X86::COND_NE:
2979   case X86::COND_NP:
2980     return true;
2981   }
2982 }
2983
2984 /// isFPImmLegal - Returns true if the target can instruction select the
2985 /// specified FP immediate natively. If false, the legalizer will
2986 /// materialize the FP immediate as a load from a constant pool.
2987 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2988   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2989     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2990       return true;
2991   }
2992   return false;
2993 }
2994
2995 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2996 /// the specified range (L, H].
2997 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2998   return (Val < 0) || (Val >= Low && Val < Hi);
2999 }
3000
3001 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3002 /// specified value.
3003 static bool isUndefOrEqual(int Val, int CmpVal) {
3004   if (Val < 0 || Val == CmpVal)
3005     return true;
3006   return false;
3007 }
3008
3009 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3010 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3011 /// the second operand.
3012 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3013   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3014     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3015   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3016     return (Mask[0] < 2 && Mask[1] < 2);
3017   return false;
3018 }
3019
3020 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3021   SmallVector<int, 8> M;
3022   N->getMask(M);
3023   return ::isPSHUFDMask(M, N->getValueType(0));
3024 }
3025
3026 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3027 /// is suitable for input to PSHUFHW.
3028 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3029   if (VT != MVT::v8i16)
3030     return false;
3031
3032   // Lower quadword copied in order or undef.
3033   for (int i = 0; i != 4; ++i)
3034     if (Mask[i] >= 0 && Mask[i] != i)
3035       return false;
3036
3037   // Upper quadword shuffled.
3038   for (int i = 4; i != 8; ++i)
3039     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3040       return false;
3041
3042   return true;
3043 }
3044
3045 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3046   SmallVector<int, 8> M;
3047   N->getMask(M);
3048   return ::isPSHUFHWMask(M, N->getValueType(0));
3049 }
3050
3051 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3052 /// is suitable for input to PSHUFLW.
3053 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3054   if (VT != MVT::v8i16)
3055     return false;
3056
3057   // Upper quadword copied in order.
3058   for (int i = 4; i != 8; ++i)
3059     if (Mask[i] >= 0 && Mask[i] != i)
3060       return false;
3061
3062   // Lower quadword shuffled.
3063   for (int i = 0; i != 4; ++i)
3064     if (Mask[i] >= 4)
3065       return false;
3066
3067   return true;
3068 }
3069
3070 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3071   SmallVector<int, 8> M;
3072   N->getMask(M);
3073   return ::isPSHUFLWMask(M, N->getValueType(0));
3074 }
3075
3076 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3077 /// is suitable for input to PALIGNR.
3078 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3079                           bool hasSSSE3) {
3080   int i, e = VT.getVectorNumElements();
3081
3082   // Do not handle v2i64 / v2f64 shuffles with palignr.
3083   if (e < 4 || !hasSSSE3)
3084     return false;
3085
3086   for (i = 0; i != e; ++i)
3087     if (Mask[i] >= 0)
3088       break;
3089
3090   // All undef, not a palignr.
3091   if (i == e)
3092     return false;
3093
3094   // Determine if it's ok to perform a palignr with only the LHS, since we
3095   // don't have access to the actual shuffle elements to see if RHS is undef.
3096   bool Unary = Mask[i] < (int)e;
3097   bool NeedsUnary = false;
3098
3099   int s = Mask[i] - i;
3100
3101   // Check the rest of the elements to see if they are consecutive.
3102   for (++i; i != e; ++i) {
3103     int m = Mask[i];
3104     if (m < 0)
3105       continue;
3106
3107     Unary = Unary && (m < (int)e);
3108     NeedsUnary = NeedsUnary || (m < s);
3109
3110     if (NeedsUnary && !Unary)
3111       return false;
3112     if (Unary && m != ((s+i) & (e-1)))
3113       return false;
3114     if (!Unary && m != (s+i))
3115       return false;
3116   }
3117   return true;
3118 }
3119
3120 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3121   SmallVector<int, 8> M;
3122   N->getMask(M);
3123   return ::isPALIGNRMask(M, N->getValueType(0), true);
3124 }
3125
3126 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3127 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3128 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3129   int NumElems = VT.getVectorNumElements();
3130   if (NumElems != 2 && NumElems != 4)
3131     return false;
3132
3133   int Half = NumElems / 2;
3134   for (int i = 0; i < Half; ++i)
3135     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3136       return false;
3137   for (int i = Half; i < NumElems; ++i)
3138     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3139       return false;
3140
3141   return true;
3142 }
3143
3144 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3145   SmallVector<int, 8> M;
3146   N->getMask(M);
3147   return ::isSHUFPMask(M, N->getValueType(0));
3148 }
3149
3150 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3151 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3152 /// half elements to come from vector 1 (which would equal the dest.) and
3153 /// the upper half to come from vector 2.
3154 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3155   int NumElems = VT.getVectorNumElements();
3156
3157   if (NumElems != 2 && NumElems != 4)
3158     return false;
3159
3160   int Half = NumElems / 2;
3161   for (int i = 0; i < Half; ++i)
3162     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3163       return false;
3164   for (int i = Half; i < NumElems; ++i)
3165     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3166       return false;
3167   return true;
3168 }
3169
3170 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3171   SmallVector<int, 8> M;
3172   N->getMask(M);
3173   return isCommutedSHUFPMask(M, N->getValueType(0));
3174 }
3175
3176 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3177 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3178 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3179   if (N->getValueType(0).getVectorNumElements() != 4)
3180     return false;
3181
3182   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3183   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3184          isUndefOrEqual(N->getMaskElt(1), 7) &&
3185          isUndefOrEqual(N->getMaskElt(2), 2) &&
3186          isUndefOrEqual(N->getMaskElt(3), 3);
3187 }
3188
3189 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3190 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3191 /// <2, 3, 2, 3>
3192 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3193   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3194
3195   if (NumElems != 4)
3196     return false;
3197
3198   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3199   isUndefOrEqual(N->getMaskElt(1), 3) &&
3200   isUndefOrEqual(N->getMaskElt(2), 2) &&
3201   isUndefOrEqual(N->getMaskElt(3), 3);
3202 }
3203
3204 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3205 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3206 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3207   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3208
3209   if (NumElems != 2 && NumElems != 4)
3210     return false;
3211
3212   for (unsigned i = 0; i < NumElems/2; ++i)
3213     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3214       return false;
3215
3216   for (unsigned i = NumElems/2; i < NumElems; ++i)
3217     if (!isUndefOrEqual(N->getMaskElt(i), i))
3218       return false;
3219
3220   return true;
3221 }
3222
3223 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3224 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3225 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3226   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3227
3228   if ((NumElems != 2 && NumElems != 4)
3229       || N->getValueType(0).getSizeInBits() > 128)
3230     return false;
3231
3232   for (unsigned i = 0; i < NumElems/2; ++i)
3233     if (!isUndefOrEqual(N->getMaskElt(i), i))
3234       return false;
3235
3236   for (unsigned i = 0; i < NumElems/2; ++i)
3237     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3238       return false;
3239
3240   return true;
3241 }
3242
3243 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3244 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3245 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3246                          bool V2IsSplat = false) {
3247   int NumElts = VT.getVectorNumElements();
3248   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3249     return false;
3250
3251   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3252   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3253   // sections.
3254   unsigned NumSections = VT.getSizeInBits() / 128;
3255   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3256   unsigned NumSectionElts = NumElts / NumSections;
3257
3258   unsigned Start = 0;
3259   unsigned End = NumSectionElts;
3260   for (unsigned s = 0; s < NumSections; ++s) {
3261     for (unsigned i = Start, j = s * NumSectionElts;
3262          i != End;
3263          i += 2, ++j) {
3264       int BitI  = Mask[i];
3265       int BitI1 = Mask[i+1];
3266       if (!isUndefOrEqual(BitI, j))
3267         return false;
3268       if (V2IsSplat) {
3269         if (!isUndefOrEqual(BitI1, NumElts))
3270           return false;
3271       } else {
3272         if (!isUndefOrEqual(BitI1, j + NumElts))
3273           return false;
3274       }
3275     }
3276     // Process the next 128 bits.
3277     Start += NumSectionElts;
3278     End += NumSectionElts;
3279   }
3280
3281   return true;
3282 }
3283
3284 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3285   SmallVector<int, 8> M;
3286   N->getMask(M);
3287   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3288 }
3289
3290 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3291 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3292 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3293                          bool V2IsSplat = false) {
3294   int NumElts = VT.getVectorNumElements();
3295   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3296     return false;
3297
3298   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3299     int BitI  = Mask[i];
3300     int BitI1 = Mask[i+1];
3301     if (!isUndefOrEqual(BitI, j + NumElts/2))
3302       return false;
3303     if (V2IsSplat) {
3304       if (isUndefOrEqual(BitI1, NumElts))
3305         return false;
3306     } else {
3307       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3308         return false;
3309     }
3310   }
3311   return true;
3312 }
3313
3314 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3315   SmallVector<int, 8> M;
3316   N->getMask(M);
3317   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3318 }
3319
3320 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3321 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3322 /// <0, 0, 1, 1>
3323 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3324   int NumElems = VT.getVectorNumElements();
3325   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3326     return false;
3327
3328   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3329   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3330   // sections.
3331   unsigned NumSections = VT.getSizeInBits() / 128;
3332   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3333   unsigned NumSectionElts = NumElems / NumSections;
3334
3335   for (unsigned s = 0; s < NumSections; ++s) {
3336     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3337          i != NumSectionElts * (s + 1);
3338          i += 2, ++j) {
3339       int BitI  = Mask[i];
3340       int BitI1 = Mask[i+1];
3341
3342       if (!isUndefOrEqual(BitI, j))
3343         return false;
3344       if (!isUndefOrEqual(BitI1, j))
3345         return false;
3346     }
3347   }
3348
3349   return true;
3350 }
3351
3352 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3353   SmallVector<int, 8> M;
3354   N->getMask(M);
3355   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3356 }
3357
3358 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3359 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3360 /// <2, 2, 3, 3>
3361 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3362   int NumElems = VT.getVectorNumElements();
3363   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3364     return false;
3365
3366   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3367     int BitI  = Mask[i];
3368     int BitI1 = Mask[i+1];
3369     if (!isUndefOrEqual(BitI, j))
3370       return false;
3371     if (!isUndefOrEqual(BitI1, j))
3372       return false;
3373   }
3374   return true;
3375 }
3376
3377 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3378   SmallVector<int, 8> M;
3379   N->getMask(M);
3380   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3381 }
3382
3383 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3384 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3385 /// MOVSD, and MOVD, i.e. setting the lowest element.
3386 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3387   if (VT.getVectorElementType().getSizeInBits() < 32)
3388     return false;
3389
3390   int NumElts = VT.getVectorNumElements();
3391
3392   if (!isUndefOrEqual(Mask[0], NumElts))
3393     return false;
3394
3395   for (int i = 1; i < NumElts; ++i)
3396     if (!isUndefOrEqual(Mask[i], i))
3397       return false;
3398
3399   return true;
3400 }
3401
3402 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3403   SmallVector<int, 8> M;
3404   N->getMask(M);
3405   return ::isMOVLMask(M, N->getValueType(0));
3406 }
3407
3408 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3409 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3410 /// element of vector 2 and the other elements to come from vector 1 in order.
3411 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3412                                bool V2IsSplat = false, bool V2IsUndef = false) {
3413   int NumOps = VT.getVectorNumElements();
3414   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3415     return false;
3416
3417   if (!isUndefOrEqual(Mask[0], 0))
3418     return false;
3419
3420   for (int i = 1; i < NumOps; ++i)
3421     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3422           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3423           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3424       return false;
3425
3426   return true;
3427 }
3428
3429 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3430                            bool V2IsUndef = false) {
3431   SmallVector<int, 8> M;
3432   N->getMask(M);
3433   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3434 }
3435
3436 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3437 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3438 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3439   if (N->getValueType(0).getVectorNumElements() != 4)
3440     return false;
3441
3442   // Expect 1, 1, 3, 3
3443   for (unsigned i = 0; i < 2; ++i) {
3444     int Elt = N->getMaskElt(i);
3445     if (Elt >= 0 && Elt != 1)
3446       return false;
3447   }
3448
3449   bool HasHi = false;
3450   for (unsigned i = 2; i < 4; ++i) {
3451     int Elt = N->getMaskElt(i);
3452     if (Elt >= 0 && Elt != 3)
3453       return false;
3454     if (Elt == 3)
3455       HasHi = true;
3456   }
3457   // Don't use movshdup if it can be done with a shufps.
3458   // FIXME: verify that matching u, u, 3, 3 is what we want.
3459   return HasHi;
3460 }
3461
3462 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3463 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3464 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3465   if (N->getValueType(0).getVectorNumElements() != 4)
3466     return false;
3467
3468   // Expect 0, 0, 2, 2
3469   for (unsigned i = 0; i < 2; ++i)
3470     if (N->getMaskElt(i) > 0)
3471       return false;
3472
3473   bool HasHi = false;
3474   for (unsigned i = 2; i < 4; ++i) {
3475     int Elt = N->getMaskElt(i);
3476     if (Elt >= 0 && Elt != 2)
3477       return false;
3478     if (Elt == 2)
3479       HasHi = true;
3480   }
3481   // Don't use movsldup if it can be done with a shufps.
3482   return HasHi;
3483 }
3484
3485 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3486 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3487 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3488   int e = N->getValueType(0).getVectorNumElements() / 2;
3489
3490   for (int i = 0; i < e; ++i)
3491     if (!isUndefOrEqual(N->getMaskElt(i), i))
3492       return false;
3493   for (int i = 0; i < e; ++i)
3494     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3495       return false;
3496   return true;
3497 }
3498
3499 /// isVEXTRACTF128Index - Return true if the specified
3500 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3501 /// suitable for input to VEXTRACTF128.
3502 bool X86::isVEXTRACTF128Index(SDNode *N) {
3503   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3504     return false;
3505
3506   // The index should be aligned on a 128-bit boundary.
3507   uint64_t Index =
3508     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3509
3510   unsigned VL = N->getValueType(0).getVectorNumElements();
3511   unsigned VBits = N->getValueType(0).getSizeInBits();
3512   unsigned ElSize = VBits / VL;
3513   bool Result = (Index * ElSize) % 128 == 0;
3514
3515   return Result;
3516 }
3517
3518 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3519 /// operand specifies a subvector insert that is suitable for input to
3520 /// VINSERTF128.
3521 bool X86::isVINSERTF128Index(SDNode *N) {
3522   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3523     return false;
3524
3525   // The index should be aligned on a 128-bit boundary.
3526   uint64_t Index =
3527     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3528
3529   unsigned VL = N->getValueType(0).getVectorNumElements();
3530   unsigned VBits = N->getValueType(0).getSizeInBits();
3531   unsigned ElSize = VBits / VL;
3532   bool Result = (Index * ElSize) % 128 == 0;
3533
3534   return Result;
3535 }
3536
3537 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3538 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3539 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3540   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3541   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3542
3543   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3544   unsigned Mask = 0;
3545   for (int i = 0; i < NumOperands; ++i) {
3546     int Val = SVOp->getMaskElt(NumOperands-i-1);
3547     if (Val < 0) Val = 0;
3548     if (Val >= NumOperands) Val -= NumOperands;
3549     Mask |= Val;
3550     if (i != NumOperands - 1)
3551       Mask <<= Shift;
3552   }
3553   return Mask;
3554 }
3555
3556 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3557 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3558 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3559   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3560   unsigned Mask = 0;
3561   // 8 nodes, but we only care about the last 4.
3562   for (unsigned i = 7; i >= 4; --i) {
3563     int Val = SVOp->getMaskElt(i);
3564     if (Val >= 0)
3565       Mask |= (Val - 4);
3566     if (i != 4)
3567       Mask <<= 2;
3568   }
3569   return Mask;
3570 }
3571
3572 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3573 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3574 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3575   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3576   unsigned Mask = 0;
3577   // 8 nodes, but we only care about the first 4.
3578   for (int i = 3; i >= 0; --i) {
3579     int Val = SVOp->getMaskElt(i);
3580     if (Val >= 0)
3581       Mask |= Val;
3582     if (i != 0)
3583       Mask <<= 2;
3584   }
3585   return Mask;
3586 }
3587
3588 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3589 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3590 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3592   EVT VVT = N->getValueType(0);
3593   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3594   int Val = 0;
3595
3596   unsigned i, e;
3597   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3598     Val = SVOp->getMaskElt(i);
3599     if (Val >= 0)
3600       break;
3601   }
3602   return (Val - i) * EltSize;
3603 }
3604
3605 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3606 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3607 /// instructions.
3608 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3609   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3610     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3611
3612   uint64_t Index =
3613     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3614
3615   EVT VecVT = N->getOperand(0).getValueType();
3616   EVT ElVT = VecVT.getVectorElementType();
3617
3618   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3619
3620   return Index / NumElemsPerChunk;
3621 }
3622
3623 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3624 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3625 /// instructions.
3626 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3627   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3628     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3629
3630   uint64_t Index =
3631     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3632
3633   EVT VecVT = N->getValueType(0);
3634   EVT ElVT = VecVT.getVectorElementType();
3635
3636   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3637
3638   return Index / NumElemsPerChunk;
3639 }
3640
3641 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3642 /// constant +0.0.
3643 bool X86::isZeroNode(SDValue Elt) {
3644   return ((isa<ConstantSDNode>(Elt) &&
3645            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3646           (isa<ConstantFPSDNode>(Elt) &&
3647            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3648 }
3649
3650 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3651 /// their permute mask.
3652 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3653                                     SelectionDAG &DAG) {
3654   EVT VT = SVOp->getValueType(0);
3655   unsigned NumElems = VT.getVectorNumElements();
3656   SmallVector<int, 8> MaskVec;
3657
3658   for (unsigned i = 0; i != NumElems; ++i) {
3659     int idx = SVOp->getMaskElt(i);
3660     if (idx < 0)
3661       MaskVec.push_back(idx);
3662     else if (idx < (int)NumElems)
3663       MaskVec.push_back(idx + NumElems);
3664     else
3665       MaskVec.push_back(idx - NumElems);
3666   }
3667   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3668                               SVOp->getOperand(0), &MaskVec[0]);
3669 }
3670
3671 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3672 /// the two vector operands have swapped position.
3673 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3674   unsigned NumElems = VT.getVectorNumElements();
3675   for (unsigned i = 0; i != NumElems; ++i) {
3676     int idx = Mask[i];
3677     if (idx < 0)
3678       continue;
3679     else if (idx < (int)NumElems)
3680       Mask[i] = idx + NumElems;
3681     else
3682       Mask[i] = idx - NumElems;
3683   }
3684 }
3685
3686 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3687 /// match movhlps. The lower half elements should come from upper half of
3688 /// V1 (and in order), and the upper half elements should come from the upper
3689 /// half of V2 (and in order).
3690 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3691   if (Op->getValueType(0).getVectorNumElements() != 4)
3692     return false;
3693   for (unsigned i = 0, e = 2; i != e; ++i)
3694     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3695       return false;
3696   for (unsigned i = 2; i != 4; ++i)
3697     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3698       return false;
3699   return true;
3700 }
3701
3702 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3703 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3704 /// required.
3705 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3706   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3707     return false;
3708   N = N->getOperand(0).getNode();
3709   if (!ISD::isNON_EXTLoad(N))
3710     return false;
3711   if (LD)
3712     *LD = cast<LoadSDNode>(N);
3713   return true;
3714 }
3715
3716 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3717 /// match movlp{s|d}. The lower half elements should come from lower half of
3718 /// V1 (and in order), and the upper half elements should come from the upper
3719 /// half of V2 (and in order). And since V1 will become the source of the
3720 /// MOVLP, it must be either a vector load or a scalar load to vector.
3721 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3722                                ShuffleVectorSDNode *Op) {
3723   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3724     return false;
3725   // Is V2 is a vector load, don't do this transformation. We will try to use
3726   // load folding shufps op.
3727   if (ISD::isNON_EXTLoad(V2))
3728     return false;
3729
3730   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3731
3732   if (NumElems != 2 && NumElems != 4)
3733     return false;
3734   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3735     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3736       return false;
3737   for (unsigned i = NumElems/2; i != NumElems; ++i)
3738     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3739       return false;
3740   return true;
3741 }
3742
3743 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3744 /// all the same.
3745 static bool isSplatVector(SDNode *N) {
3746   if (N->getOpcode() != ISD::BUILD_VECTOR)
3747     return false;
3748
3749   SDValue SplatValue = N->getOperand(0);
3750   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3751     if (N->getOperand(i) != SplatValue)
3752       return false;
3753   return true;
3754 }
3755
3756 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3757 /// to an zero vector.
3758 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3759 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3760   SDValue V1 = N->getOperand(0);
3761   SDValue V2 = N->getOperand(1);
3762   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3763   for (unsigned i = 0; i != NumElems; ++i) {
3764     int Idx = N->getMaskElt(i);
3765     if (Idx >= (int)NumElems) {
3766       unsigned Opc = V2.getOpcode();
3767       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3768         continue;
3769       if (Opc != ISD::BUILD_VECTOR ||
3770           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3771         return false;
3772     } else if (Idx >= 0) {
3773       unsigned Opc = V1.getOpcode();
3774       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3775         continue;
3776       if (Opc != ISD::BUILD_VECTOR ||
3777           !X86::isZeroNode(V1.getOperand(Idx)))
3778         return false;
3779     }
3780   }
3781   return true;
3782 }
3783
3784 /// getZeroVector - Returns a vector of specified type with all zero elements.
3785 ///
3786 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3787                              DebugLoc dl) {
3788   assert(VT.isVector() && "Expected a vector type");
3789
3790   // Always build SSE zero vectors as <4 x i32> bitcasted
3791   // to their dest type. This ensures they get CSE'd.
3792   SDValue Vec;
3793   if (VT.getSizeInBits() == 128) {  // SSE
3794     if (HasSSE2) {  // SSE2
3795       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3796       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3797     } else { // SSE1
3798       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3799       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3800     }
3801   } else if (VT.getSizeInBits() == 256) { // AVX
3802     // 256-bit logic and arithmetic instructions in AVX are
3803     // all floating-point, no support for integer ops. Default
3804     // to emitting fp zeroed vectors then.
3805     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3806     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3807     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3808   }
3809   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3810 }
3811
3812 /// getOnesVector - Returns a vector of specified type with all bits set.
3813 ///
3814 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3815   assert(VT.isVector() && "Expected a vector type");
3816
3817   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3818   // type.  This ensures they get CSE'd.
3819   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3820   SDValue Vec;
3821   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3822   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3823 }
3824
3825
3826 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3827 /// that point to V2 points to its first element.
3828 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3829   EVT VT = SVOp->getValueType(0);
3830   unsigned NumElems = VT.getVectorNumElements();
3831
3832   bool Changed = false;
3833   SmallVector<int, 8> MaskVec;
3834   SVOp->getMask(MaskVec);
3835
3836   for (unsigned i = 0; i != NumElems; ++i) {
3837     if (MaskVec[i] > (int)NumElems) {
3838       MaskVec[i] = NumElems;
3839       Changed = true;
3840     }
3841   }
3842   if (Changed)
3843     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3844                                 SVOp->getOperand(1), &MaskVec[0]);
3845   return SDValue(SVOp, 0);
3846 }
3847
3848 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3849 /// operation of specified width.
3850 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3851                        SDValue V2) {
3852   unsigned NumElems = VT.getVectorNumElements();
3853   SmallVector<int, 8> Mask;
3854   Mask.push_back(NumElems);
3855   for (unsigned i = 1; i != NumElems; ++i)
3856     Mask.push_back(i);
3857   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3858 }
3859
3860 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3861 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3862                           SDValue V2) {
3863   unsigned NumElems = VT.getVectorNumElements();
3864   SmallVector<int, 8> Mask;
3865   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3866     Mask.push_back(i);
3867     Mask.push_back(i + NumElems);
3868   }
3869   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3870 }
3871
3872 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3873 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3874                           SDValue V2) {
3875   unsigned NumElems = VT.getVectorNumElements();
3876   unsigned Half = NumElems/2;
3877   SmallVector<int, 8> Mask;
3878   for (unsigned i = 0; i != Half; ++i) {
3879     Mask.push_back(i + Half);
3880     Mask.push_back(i + NumElems + Half);
3881   }
3882   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3883 }
3884
3885 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3886 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3887   EVT PVT = MVT::v4f32;
3888   EVT VT = SV->getValueType(0);
3889   DebugLoc dl = SV->getDebugLoc();
3890   SDValue V1 = SV->getOperand(0);
3891   int NumElems = VT.getVectorNumElements();
3892   int EltNo = SV->getSplatIndex();
3893
3894   // unpack elements to the correct location
3895   while (NumElems > 4) {
3896     if (EltNo < NumElems/2) {
3897       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3898     } else {
3899       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3900       EltNo -= NumElems/2;
3901     }
3902     NumElems >>= 1;
3903   }
3904
3905   // Perform the splat.
3906   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3907   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3908   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3909   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3910 }
3911
3912 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3913 /// vector of zero or undef vector.  This produces a shuffle where the low
3914 /// element of V2 is swizzled into the zero/undef vector, landing at element
3915 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3916 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3917                                              bool isZero, bool HasSSE2,
3918                                              SelectionDAG &DAG) {
3919   EVT VT = V2.getValueType();
3920   SDValue V1 = isZero
3921     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3922   unsigned NumElems = VT.getVectorNumElements();
3923   SmallVector<int, 16> MaskVec;
3924   for (unsigned i = 0; i != NumElems; ++i)
3925     // If this is the insertion idx, put the low elt of V2 here.
3926     MaskVec.push_back(i == Idx ? NumElems : i);
3927   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3928 }
3929
3930 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3931 /// element of the result of the vector shuffle.
3932 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3933                                    unsigned Depth) {
3934   if (Depth == 6)
3935     return SDValue();  // Limit search depth.
3936
3937   SDValue V = SDValue(N, 0);
3938   EVT VT = V.getValueType();
3939   unsigned Opcode = V.getOpcode();
3940
3941   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3942   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3943     Index = SV->getMaskElt(Index);
3944
3945     if (Index < 0)
3946       return DAG.getUNDEF(VT.getVectorElementType());
3947
3948     int NumElems = VT.getVectorNumElements();
3949     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3950     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3951   }
3952
3953   // Recurse into target specific vector shuffles to find scalars.
3954   if (isTargetShuffle(Opcode)) {
3955     int NumElems = VT.getVectorNumElements();
3956     SmallVector<unsigned, 16> ShuffleMask;
3957     SDValue ImmN;
3958
3959     switch(Opcode) {
3960     case X86ISD::SHUFPS:
3961     case X86ISD::SHUFPD:
3962       ImmN = N->getOperand(N->getNumOperands()-1);
3963       DecodeSHUFPSMask(NumElems,
3964                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3965                        ShuffleMask);
3966       break;
3967     case X86ISD::PUNPCKHBW:
3968     case X86ISD::PUNPCKHWD:
3969     case X86ISD::PUNPCKHDQ:
3970     case X86ISD::PUNPCKHQDQ:
3971       DecodePUNPCKHMask(NumElems, ShuffleMask);
3972       break;
3973     case X86ISD::UNPCKHPS:
3974     case X86ISD::UNPCKHPD:
3975       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3976       break;
3977     case X86ISD::PUNPCKLBW:
3978     case X86ISD::PUNPCKLWD:
3979     case X86ISD::PUNPCKLDQ:
3980     case X86ISD::PUNPCKLQDQ:
3981       DecodePUNPCKLMask(VT, ShuffleMask);
3982       break;
3983     case X86ISD::UNPCKLPS:
3984     case X86ISD::UNPCKLPD:
3985     case X86ISD::VUNPCKLPS:
3986     case X86ISD::VUNPCKLPD:
3987     case X86ISD::VUNPCKLPSY:
3988     case X86ISD::VUNPCKLPDY:
3989       DecodeUNPCKLPMask(VT, ShuffleMask);
3990       break;
3991     case X86ISD::MOVHLPS:
3992       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3993       break;
3994     case X86ISD::MOVLHPS:
3995       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3996       break;
3997     case X86ISD::PSHUFD:
3998       ImmN = N->getOperand(N->getNumOperands()-1);
3999       DecodePSHUFMask(NumElems,
4000                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4001                       ShuffleMask);
4002       break;
4003     case X86ISD::PSHUFHW:
4004       ImmN = N->getOperand(N->getNumOperands()-1);
4005       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4006                         ShuffleMask);
4007       break;
4008     case X86ISD::PSHUFLW:
4009       ImmN = N->getOperand(N->getNumOperands()-1);
4010       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4011                         ShuffleMask);
4012       break;
4013     case X86ISD::MOVSS:
4014     case X86ISD::MOVSD: {
4015       // The index 0 always comes from the first element of the second source,
4016       // this is why MOVSS and MOVSD are used in the first place. The other
4017       // elements come from the other positions of the first source vector.
4018       unsigned OpNum = (Index == 0) ? 1 : 0;
4019       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4020                                  Depth+1);
4021     }
4022     default:
4023       assert("not implemented for target shuffle node");
4024       return SDValue();
4025     }
4026
4027     Index = ShuffleMask[Index];
4028     if (Index < 0)
4029       return DAG.getUNDEF(VT.getVectorElementType());
4030
4031     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4032     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4033                                Depth+1);
4034   }
4035
4036   // Actual nodes that may contain scalar elements
4037   if (Opcode == ISD::BITCAST) {
4038     V = V.getOperand(0);
4039     EVT SrcVT = V.getValueType();
4040     unsigned NumElems = VT.getVectorNumElements();
4041
4042     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4043       return SDValue();
4044   }
4045
4046   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4047     return (Index == 0) ? V.getOperand(0)
4048                           : DAG.getUNDEF(VT.getVectorElementType());
4049
4050   if (V.getOpcode() == ISD::BUILD_VECTOR)
4051     return V.getOperand(Index);
4052
4053   return SDValue();
4054 }
4055
4056 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4057 /// shuffle operation which come from a consecutively from a zero. The
4058 /// search can start in two different directions, from left or right.
4059 static
4060 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4061                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4062   int i = 0;
4063
4064   while (i < NumElems) {
4065     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4066     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4067     if (!(Elt.getNode() &&
4068          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4069       break;
4070     ++i;
4071   }
4072
4073   return i;
4074 }
4075
4076 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4077 /// MaskE correspond consecutively to elements from one of the vector operands,
4078 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4079 static
4080 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4081                               int OpIdx, int NumElems, unsigned &OpNum) {
4082   bool SeenV1 = false;
4083   bool SeenV2 = false;
4084
4085   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4086     int Idx = SVOp->getMaskElt(i);
4087     // Ignore undef indicies
4088     if (Idx < 0)
4089       continue;
4090
4091     if (Idx < NumElems)
4092       SeenV1 = true;
4093     else
4094       SeenV2 = true;
4095
4096     // Only accept consecutive elements from the same vector
4097     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4098       return false;
4099   }
4100
4101   OpNum = SeenV1 ? 0 : 1;
4102   return true;
4103 }
4104
4105 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4106 /// logical left shift of a vector.
4107 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4108                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4109   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4110   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4111               false /* check zeros from right */, DAG);
4112   unsigned OpSrc;
4113
4114   if (!NumZeros)
4115     return false;
4116
4117   // Considering the elements in the mask that are not consecutive zeros,
4118   // check if they consecutively come from only one of the source vectors.
4119   //
4120   //               V1 = {X, A, B, C}     0
4121   //                         \  \  \    /
4122   //   vector_shuffle V1, V2 <1, 2, 3, X>
4123   //
4124   if (!isShuffleMaskConsecutive(SVOp,
4125             0,                   // Mask Start Index
4126             NumElems-NumZeros-1, // Mask End Index
4127             NumZeros,            // Where to start looking in the src vector
4128             NumElems,            // Number of elements in vector
4129             OpSrc))              // Which source operand ?
4130     return false;
4131
4132   isLeft = false;
4133   ShAmt = NumZeros;
4134   ShVal = SVOp->getOperand(OpSrc);
4135   return true;
4136 }
4137
4138 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4139 /// logical left shift of a vector.
4140 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4141                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4142   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4143   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4144               true /* check zeros from left */, DAG);
4145   unsigned OpSrc;
4146
4147   if (!NumZeros)
4148     return false;
4149
4150   // Considering the elements in the mask that are not consecutive zeros,
4151   // check if they consecutively come from only one of the source vectors.
4152   //
4153   //                           0    { A, B, X, X } = V2
4154   //                          / \    /  /
4155   //   vector_shuffle V1, V2 <X, X, 4, 5>
4156   //
4157   if (!isShuffleMaskConsecutive(SVOp,
4158             NumZeros,     // Mask Start Index
4159             NumElems-1,   // Mask End Index
4160             0,            // Where to start looking in the src vector
4161             NumElems,     // Number of elements in vector
4162             OpSrc))       // Which source operand ?
4163     return false;
4164
4165   isLeft = true;
4166   ShAmt = NumZeros;
4167   ShVal = SVOp->getOperand(OpSrc);
4168   return true;
4169 }
4170
4171 /// isVectorShift - Returns true if the shuffle can be implemented as a
4172 /// logical left or right shift of a vector.
4173 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4174                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4175   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4176       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4177     return true;
4178
4179   return false;
4180 }
4181
4182 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4183 ///
4184 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4185                                        unsigned NumNonZero, unsigned NumZero,
4186                                        SelectionDAG &DAG,
4187                                        const TargetLowering &TLI) {
4188   if (NumNonZero > 8)
4189     return SDValue();
4190
4191   DebugLoc dl = Op.getDebugLoc();
4192   SDValue V(0, 0);
4193   bool First = true;
4194   for (unsigned i = 0; i < 16; ++i) {
4195     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4196     if (ThisIsNonZero && First) {
4197       if (NumZero)
4198         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4199       else
4200         V = DAG.getUNDEF(MVT::v8i16);
4201       First = false;
4202     }
4203
4204     if ((i & 1) != 0) {
4205       SDValue ThisElt(0, 0), LastElt(0, 0);
4206       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4207       if (LastIsNonZero) {
4208         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4209                               MVT::i16, Op.getOperand(i-1));
4210       }
4211       if (ThisIsNonZero) {
4212         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4213         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4214                               ThisElt, DAG.getConstant(8, MVT::i8));
4215         if (LastIsNonZero)
4216           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4217       } else
4218         ThisElt = LastElt;
4219
4220       if (ThisElt.getNode())
4221         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4222                         DAG.getIntPtrConstant(i/2));
4223     }
4224   }
4225
4226   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4227 }
4228
4229 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4230 ///
4231 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4232                                      unsigned NumNonZero, unsigned NumZero,
4233                                      SelectionDAG &DAG,
4234                                      const TargetLowering &TLI) {
4235   if (NumNonZero > 4)
4236     return SDValue();
4237
4238   DebugLoc dl = Op.getDebugLoc();
4239   SDValue V(0, 0);
4240   bool First = true;
4241   for (unsigned i = 0; i < 8; ++i) {
4242     bool isNonZero = (NonZeros & (1 << i)) != 0;
4243     if (isNonZero) {
4244       if (First) {
4245         if (NumZero)
4246           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4247         else
4248           V = DAG.getUNDEF(MVT::v8i16);
4249         First = false;
4250       }
4251       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4252                       MVT::v8i16, V, Op.getOperand(i),
4253                       DAG.getIntPtrConstant(i));
4254     }
4255   }
4256
4257   return V;
4258 }
4259
4260 /// getVShift - Return a vector logical shift node.
4261 ///
4262 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4263                          unsigned NumBits, SelectionDAG &DAG,
4264                          const TargetLowering &TLI, DebugLoc dl) {
4265   EVT ShVT = MVT::v2i64;
4266   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4267   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4268   return DAG.getNode(ISD::BITCAST, dl, VT,
4269                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4270                              DAG.getConstant(NumBits,
4271                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4272 }
4273
4274 SDValue
4275 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4276                                           SelectionDAG &DAG) const {
4277
4278   // Check if the scalar load can be widened into a vector load. And if
4279   // the address is "base + cst" see if the cst can be "absorbed" into
4280   // the shuffle mask.
4281   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4282     SDValue Ptr = LD->getBasePtr();
4283     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4284       return SDValue();
4285     EVT PVT = LD->getValueType(0);
4286     if (PVT != MVT::i32 && PVT != MVT::f32)
4287       return SDValue();
4288
4289     int FI = -1;
4290     int64_t Offset = 0;
4291     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4292       FI = FINode->getIndex();
4293       Offset = 0;
4294     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4295                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4296       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4297       Offset = Ptr.getConstantOperandVal(1);
4298       Ptr = Ptr.getOperand(0);
4299     } else {
4300       return SDValue();
4301     }
4302
4303     SDValue Chain = LD->getChain();
4304     // Make sure the stack object alignment is at least 16.
4305     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4306     if (DAG.InferPtrAlignment(Ptr) < 16) {
4307       if (MFI->isFixedObjectIndex(FI)) {
4308         // Can't change the alignment. FIXME: It's possible to compute
4309         // the exact stack offset and reference FI + adjust offset instead.
4310         // If someone *really* cares about this. That's the way to implement it.
4311         return SDValue();
4312       } else {
4313         MFI->setObjectAlignment(FI, 16);
4314       }
4315     }
4316
4317     // (Offset % 16) must be multiple of 4. Then address is then
4318     // Ptr + (Offset & ~15).
4319     if (Offset < 0)
4320       return SDValue();
4321     if ((Offset % 16) & 3)
4322       return SDValue();
4323     int64_t StartOffset = Offset & ~15;
4324     if (StartOffset)
4325       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4326                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4327
4328     int EltNo = (Offset - StartOffset) >> 2;
4329     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4330     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4331     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4332                              LD->getPointerInfo().getWithOffset(StartOffset),
4333                              false, false, 0);
4334     // Canonicalize it to a v4i32 shuffle.
4335     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4336     return DAG.getNode(ISD::BITCAST, dl, VT,
4337                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4338                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4339   }
4340
4341   return SDValue();
4342 }
4343
4344 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4345 /// vector of type 'VT', see if the elements can be replaced by a single large
4346 /// load which has the same value as a build_vector whose operands are 'elts'.
4347 ///
4348 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4349 ///
4350 /// FIXME: we'd also like to handle the case where the last elements are zero
4351 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4352 /// There's even a handy isZeroNode for that purpose.
4353 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4354                                         DebugLoc &DL, SelectionDAG &DAG) {
4355   EVT EltVT = VT.getVectorElementType();
4356   unsigned NumElems = Elts.size();
4357
4358   LoadSDNode *LDBase = NULL;
4359   unsigned LastLoadedElt = -1U;
4360
4361   // For each element in the initializer, see if we've found a load or an undef.
4362   // If we don't find an initial load element, or later load elements are
4363   // non-consecutive, bail out.
4364   for (unsigned i = 0; i < NumElems; ++i) {
4365     SDValue Elt = Elts[i];
4366
4367     if (!Elt.getNode() ||
4368         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4369       return SDValue();
4370     if (!LDBase) {
4371       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4372         return SDValue();
4373       LDBase = cast<LoadSDNode>(Elt.getNode());
4374       LastLoadedElt = i;
4375       continue;
4376     }
4377     if (Elt.getOpcode() == ISD::UNDEF)
4378       continue;
4379
4380     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4381     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4382       return SDValue();
4383     LastLoadedElt = i;
4384   }
4385
4386   // If we have found an entire vector of loads and undefs, then return a large
4387   // load of the entire vector width starting at the base pointer.  If we found
4388   // consecutive loads for the low half, generate a vzext_load node.
4389   if (LastLoadedElt == NumElems - 1) {
4390     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4391       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4392                          LDBase->getPointerInfo(),
4393                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4394     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4395                        LDBase->getPointerInfo(),
4396                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4397                        LDBase->getAlignment());
4398   } else if (NumElems == 4 && LastLoadedElt == 1) {
4399     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4400     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4401     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4402                                               Ops, 2, MVT::i32,
4403                                               LDBase->getMemOperand());
4404     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4405   }
4406   return SDValue();
4407 }
4408
4409 SDValue
4410 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4411   DebugLoc dl = Op.getDebugLoc();
4412
4413   EVT VT = Op.getValueType();
4414   EVT ExtVT = VT.getVectorElementType();
4415
4416   unsigned NumElems = Op.getNumOperands();
4417
4418   // For AVX-length vectors, build the individual 128-bit pieces and
4419   // use shuffles to put them in place.
4420   if (VT.getSizeInBits() > 256 &&
4421       Subtarget->hasAVX() &&
4422       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4423     SmallVector<SDValue, 8> V;
4424     V.resize(NumElems);
4425     for (unsigned i = 0; i < NumElems; ++i) {
4426       V[i] = Op.getOperand(i);
4427     }
4428
4429     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4430
4431     // Build the lower subvector.
4432     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4433     // Build the upper subvector.
4434     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4435                                 NumElems/2);
4436
4437     return ConcatVectors(Lower, Upper, DAG);
4438   }
4439
4440   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4441   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4442   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4443   // is present, so AllOnes is ignored.
4444   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4445       (Op.getValueType().getSizeInBits() != 256 &&
4446        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4447     // Canonicalize this to <4 x i32> (SSE) to
4448     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4449     // eliminated on x86-32 hosts.
4450     if (Op.getValueType() == MVT::v4i32)
4451       return Op;
4452
4453     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4454       return getOnesVector(Op.getValueType(), DAG, dl);
4455     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4456   }
4457
4458   unsigned EVTBits = ExtVT.getSizeInBits();
4459
4460   unsigned NumZero  = 0;
4461   unsigned NumNonZero = 0;
4462   unsigned NonZeros = 0;
4463   bool IsAllConstants = true;
4464   SmallSet<SDValue, 8> Values;
4465   for (unsigned i = 0; i < NumElems; ++i) {
4466     SDValue Elt = Op.getOperand(i);
4467     if (Elt.getOpcode() == ISD::UNDEF)
4468       continue;
4469     Values.insert(Elt);
4470     if (Elt.getOpcode() != ISD::Constant &&
4471         Elt.getOpcode() != ISD::ConstantFP)
4472       IsAllConstants = false;
4473     if (X86::isZeroNode(Elt))
4474       NumZero++;
4475     else {
4476       NonZeros |= (1 << i);
4477       NumNonZero++;
4478     }
4479   }
4480
4481   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4482   if (NumNonZero == 0)
4483     return DAG.getUNDEF(VT);
4484
4485   // Special case for single non-zero, non-undef, element.
4486   if (NumNonZero == 1) {
4487     unsigned Idx = CountTrailingZeros_32(NonZeros);
4488     SDValue Item = Op.getOperand(Idx);
4489
4490     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4491     // the value are obviously zero, truncate the value to i32 and do the
4492     // insertion that way.  Only do this if the value is non-constant or if the
4493     // value is a constant being inserted into element 0.  It is cheaper to do
4494     // a constant pool load than it is to do a movd + shuffle.
4495     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4496         (!IsAllConstants || Idx == 0)) {
4497       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4498         // Handle SSE only.
4499         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4500         EVT VecVT = MVT::v4i32;
4501         unsigned VecElts = 4;
4502
4503         // Truncate the value (which may itself be a constant) to i32, and
4504         // convert it to a vector with movd (S2V+shuffle to zero extend).
4505         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4506         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4507         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4508                                            Subtarget->hasSSE2(), DAG);
4509
4510         // Now we have our 32-bit value zero extended in the low element of
4511         // a vector.  If Idx != 0, swizzle it into place.
4512         if (Idx != 0) {
4513           SmallVector<int, 4> Mask;
4514           Mask.push_back(Idx);
4515           for (unsigned i = 1; i != VecElts; ++i)
4516             Mask.push_back(i);
4517           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4518                                       DAG.getUNDEF(Item.getValueType()),
4519                                       &Mask[0]);
4520         }
4521         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4522       }
4523     }
4524
4525     // If we have a constant or non-constant insertion into the low element of
4526     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4527     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4528     // depending on what the source datatype is.
4529     if (Idx == 0) {
4530       if (NumZero == 0) {
4531         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4532       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4533           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4534         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4535         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4536         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4537                                            DAG);
4538       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4539         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4540         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4541         EVT MiddleVT = MVT::v4i32;
4542         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4543         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4544                                            Subtarget->hasSSE2(), DAG);
4545         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4546       }
4547     }
4548
4549     // Is it a vector logical left shift?
4550     if (NumElems == 2 && Idx == 1 &&
4551         X86::isZeroNode(Op.getOperand(0)) &&
4552         !X86::isZeroNode(Op.getOperand(1))) {
4553       unsigned NumBits = VT.getSizeInBits();
4554       return getVShift(true, VT,
4555                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4556                                    VT, Op.getOperand(1)),
4557                        NumBits/2, DAG, *this, dl);
4558     }
4559
4560     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4561       return SDValue();
4562
4563     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4564     // is a non-constant being inserted into an element other than the low one,
4565     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4566     // movd/movss) to move this into the low element, then shuffle it into
4567     // place.
4568     if (EVTBits == 32) {
4569       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4570
4571       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4572       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4573                                          Subtarget->hasSSE2(), DAG);
4574       SmallVector<int, 8> MaskVec;
4575       for (unsigned i = 0; i < NumElems; i++)
4576         MaskVec.push_back(i == Idx ? 0 : 1);
4577       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4578     }
4579   }
4580
4581   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4582   if (Values.size() == 1) {
4583     if (EVTBits == 32) {
4584       // Instead of a shuffle like this:
4585       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4586       // Check if it's possible to issue this instead.
4587       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4588       unsigned Idx = CountTrailingZeros_32(NonZeros);
4589       SDValue Item = Op.getOperand(Idx);
4590       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4591         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4592     }
4593     return SDValue();
4594   }
4595
4596   // A vector full of immediates; various special cases are already
4597   // handled, so this is best done with a single constant-pool load.
4598   if (IsAllConstants)
4599     return SDValue();
4600
4601   // Let legalizer expand 2-wide build_vectors.
4602   if (EVTBits == 64) {
4603     if (NumNonZero == 1) {
4604       // One half is zero or undef.
4605       unsigned Idx = CountTrailingZeros_32(NonZeros);
4606       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4607                                  Op.getOperand(Idx));
4608       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4609                                          Subtarget->hasSSE2(), DAG);
4610     }
4611     return SDValue();
4612   }
4613
4614   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4615   if (EVTBits == 8 && NumElems == 16) {
4616     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4617                                         *this);
4618     if (V.getNode()) return V;
4619   }
4620
4621   if (EVTBits == 16 && NumElems == 8) {
4622     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4623                                       *this);
4624     if (V.getNode()) return V;
4625   }
4626
4627   // If element VT is == 32 bits, turn it into a number of shuffles.
4628   SmallVector<SDValue, 8> V;
4629   V.resize(NumElems);
4630   if (NumElems == 4 && NumZero > 0) {
4631     for (unsigned i = 0; i < 4; ++i) {
4632       bool isZero = !(NonZeros & (1 << i));
4633       if (isZero)
4634         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4635       else
4636         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4637     }
4638
4639     for (unsigned i = 0; i < 2; ++i) {
4640       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4641         default: break;
4642         case 0:
4643           V[i] = V[i*2];  // Must be a zero vector.
4644           break;
4645         case 1:
4646           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4647           break;
4648         case 2:
4649           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4650           break;
4651         case 3:
4652           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4653           break;
4654       }
4655     }
4656
4657     SmallVector<int, 8> MaskVec;
4658     bool Reverse = (NonZeros & 0x3) == 2;
4659     for (unsigned i = 0; i < 2; ++i)
4660       MaskVec.push_back(Reverse ? 1-i : i);
4661     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4662     for (unsigned i = 0; i < 2; ++i)
4663       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4664     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4665   }
4666
4667   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4668     // Check for a build vector of consecutive loads.
4669     for (unsigned i = 0; i < NumElems; ++i)
4670       V[i] = Op.getOperand(i);
4671
4672     // Check for elements which are consecutive loads.
4673     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4674     if (LD.getNode())
4675       return LD;
4676
4677     // For SSE 4.1, use insertps to put the high elements into the low element.
4678     if (getSubtarget()->hasSSE41()) {
4679       SDValue Result;
4680       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4681         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4682       else
4683         Result = DAG.getUNDEF(VT);
4684
4685       for (unsigned i = 1; i < NumElems; ++i) {
4686         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4687         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4688                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4689       }
4690       return Result;
4691     }
4692
4693     // Otherwise, expand into a number of unpckl*, start by extending each of
4694     // our (non-undef) elements to the full vector width with the element in the
4695     // bottom slot of the vector (which generates no code for SSE).
4696     for (unsigned i = 0; i < NumElems; ++i) {
4697       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4698         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4699       else
4700         V[i] = DAG.getUNDEF(VT);
4701     }
4702
4703     // Next, we iteratively mix elements, e.g. for v4f32:
4704     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4705     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4706     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4707     unsigned EltStride = NumElems >> 1;
4708     while (EltStride != 0) {
4709       for (unsigned i = 0; i < EltStride; ++i) {
4710         // If V[i+EltStride] is undef and this is the first round of mixing,
4711         // then it is safe to just drop this shuffle: V[i] is already in the
4712         // right place, the one element (since it's the first round) being
4713         // inserted as undef can be dropped.  This isn't safe for successive
4714         // rounds because they will permute elements within both vectors.
4715         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4716             EltStride == NumElems/2)
4717           continue;
4718
4719         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4720       }
4721       EltStride >>= 1;
4722     }
4723     return V[0];
4724   }
4725   return SDValue();
4726 }
4727
4728 SDValue
4729 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4730   // We support concatenate two MMX registers and place them in a MMX
4731   // register.  This is better than doing a stack convert.
4732   DebugLoc dl = Op.getDebugLoc();
4733   EVT ResVT = Op.getValueType();
4734   assert(Op.getNumOperands() == 2);
4735   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4736          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4737   int Mask[2];
4738   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4739   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4740   InVec = Op.getOperand(1);
4741   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4742     unsigned NumElts = ResVT.getVectorNumElements();
4743     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4744     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4745                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4746   } else {
4747     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4748     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4749     Mask[0] = 0; Mask[1] = 2;
4750     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4751   }
4752   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4753 }
4754
4755 // v8i16 shuffles - Prefer shuffles in the following order:
4756 // 1. [all]   pshuflw, pshufhw, optional move
4757 // 2. [ssse3] 1 x pshufb
4758 // 3. [ssse3] 2 x pshufb + 1 x por
4759 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4760 SDValue
4761 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4762                                             SelectionDAG &DAG) const {
4763   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4764   SDValue V1 = SVOp->getOperand(0);
4765   SDValue V2 = SVOp->getOperand(1);
4766   DebugLoc dl = SVOp->getDebugLoc();
4767   SmallVector<int, 8> MaskVals;
4768
4769   // Determine if more than 1 of the words in each of the low and high quadwords
4770   // of the result come from the same quadword of one of the two inputs.  Undef
4771   // mask values count as coming from any quadword, for better codegen.
4772   SmallVector<unsigned, 4> LoQuad(4);
4773   SmallVector<unsigned, 4> HiQuad(4);
4774   BitVector InputQuads(4);
4775   for (unsigned i = 0; i < 8; ++i) {
4776     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4777     int EltIdx = SVOp->getMaskElt(i);
4778     MaskVals.push_back(EltIdx);
4779     if (EltIdx < 0) {
4780       ++Quad[0];
4781       ++Quad[1];
4782       ++Quad[2];
4783       ++Quad[3];
4784       continue;
4785     }
4786     ++Quad[EltIdx / 4];
4787     InputQuads.set(EltIdx / 4);
4788   }
4789
4790   int BestLoQuad = -1;
4791   unsigned MaxQuad = 1;
4792   for (unsigned i = 0; i < 4; ++i) {
4793     if (LoQuad[i] > MaxQuad) {
4794       BestLoQuad = i;
4795       MaxQuad = LoQuad[i];
4796     }
4797   }
4798
4799   int BestHiQuad = -1;
4800   MaxQuad = 1;
4801   for (unsigned i = 0; i < 4; ++i) {
4802     if (HiQuad[i] > MaxQuad) {
4803       BestHiQuad = i;
4804       MaxQuad = HiQuad[i];
4805     }
4806   }
4807
4808   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4809   // of the two input vectors, shuffle them into one input vector so only a
4810   // single pshufb instruction is necessary. If There are more than 2 input
4811   // quads, disable the next transformation since it does not help SSSE3.
4812   bool V1Used = InputQuads[0] || InputQuads[1];
4813   bool V2Used = InputQuads[2] || InputQuads[3];
4814   if (Subtarget->hasSSSE3()) {
4815     if (InputQuads.count() == 2 && V1Used && V2Used) {
4816       BestLoQuad = InputQuads.find_first();
4817       BestHiQuad = InputQuads.find_next(BestLoQuad);
4818     }
4819     if (InputQuads.count() > 2) {
4820       BestLoQuad = -1;
4821       BestHiQuad = -1;
4822     }
4823   }
4824
4825   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4826   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4827   // words from all 4 input quadwords.
4828   SDValue NewV;
4829   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4830     SmallVector<int, 8> MaskV;
4831     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4832     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4833     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4834                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4835                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4836     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4837
4838     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4839     // source words for the shuffle, to aid later transformations.
4840     bool AllWordsInNewV = true;
4841     bool InOrder[2] = { true, true };
4842     for (unsigned i = 0; i != 8; ++i) {
4843       int idx = MaskVals[i];
4844       if (idx != (int)i)
4845         InOrder[i/4] = false;
4846       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4847         continue;
4848       AllWordsInNewV = false;
4849       break;
4850     }
4851
4852     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4853     if (AllWordsInNewV) {
4854       for (int i = 0; i != 8; ++i) {
4855         int idx = MaskVals[i];
4856         if (idx < 0)
4857           continue;
4858         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4859         if ((idx != i) && idx < 4)
4860           pshufhw = false;
4861         if ((idx != i) && idx > 3)
4862           pshuflw = false;
4863       }
4864       V1 = NewV;
4865       V2Used = false;
4866       BestLoQuad = 0;
4867       BestHiQuad = 1;
4868     }
4869
4870     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4871     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4872     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4873       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4874       unsigned TargetMask = 0;
4875       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4876                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4877       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4878                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4879       V1 = NewV.getOperand(0);
4880       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4881     }
4882   }
4883
4884   // If we have SSSE3, and all words of the result are from 1 input vector,
4885   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4886   // is present, fall back to case 4.
4887   if (Subtarget->hasSSSE3()) {
4888     SmallVector<SDValue,16> pshufbMask;
4889
4890     // If we have elements from both input vectors, set the high bit of the
4891     // shuffle mask element to zero out elements that come from V2 in the V1
4892     // mask, and elements that come from V1 in the V2 mask, so that the two
4893     // results can be OR'd together.
4894     bool TwoInputs = V1Used && V2Used;
4895     for (unsigned i = 0; i != 8; ++i) {
4896       int EltIdx = MaskVals[i] * 2;
4897       if (TwoInputs && (EltIdx >= 16)) {
4898         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4899         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4900         continue;
4901       }
4902       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4903       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4904     }
4905     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4906     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4907                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4908                                  MVT::v16i8, &pshufbMask[0], 16));
4909     if (!TwoInputs)
4910       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4911
4912     // Calculate the shuffle mask for the second input, shuffle it, and
4913     // OR it with the first shuffled input.
4914     pshufbMask.clear();
4915     for (unsigned i = 0; i != 8; ++i) {
4916       int EltIdx = MaskVals[i] * 2;
4917       if (EltIdx < 16) {
4918         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4919         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4920         continue;
4921       }
4922       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4923       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4924     }
4925     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4926     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4927                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4928                                  MVT::v16i8, &pshufbMask[0], 16));
4929     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4930     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4931   }
4932
4933   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4934   // and update MaskVals with new element order.
4935   BitVector InOrder(8);
4936   if (BestLoQuad >= 0) {
4937     SmallVector<int, 8> MaskV;
4938     for (int i = 0; i != 4; ++i) {
4939       int idx = MaskVals[i];
4940       if (idx < 0) {
4941         MaskV.push_back(-1);
4942         InOrder.set(i);
4943       } else if ((idx / 4) == BestLoQuad) {
4944         MaskV.push_back(idx & 3);
4945         InOrder.set(i);
4946       } else {
4947         MaskV.push_back(-1);
4948       }
4949     }
4950     for (unsigned i = 4; i != 8; ++i)
4951       MaskV.push_back(i);
4952     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4953                                 &MaskV[0]);
4954
4955     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4956       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4957                                NewV.getOperand(0),
4958                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4959                                DAG);
4960   }
4961
4962   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4963   // and update MaskVals with the new element order.
4964   if (BestHiQuad >= 0) {
4965     SmallVector<int, 8> MaskV;
4966     for (unsigned i = 0; i != 4; ++i)
4967       MaskV.push_back(i);
4968     for (unsigned i = 4; i != 8; ++i) {
4969       int idx = MaskVals[i];
4970       if (idx < 0) {
4971         MaskV.push_back(-1);
4972         InOrder.set(i);
4973       } else if ((idx / 4) == BestHiQuad) {
4974         MaskV.push_back((idx & 3) + 4);
4975         InOrder.set(i);
4976       } else {
4977         MaskV.push_back(-1);
4978       }
4979     }
4980     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4981                                 &MaskV[0]);
4982
4983     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4984       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4985                               NewV.getOperand(0),
4986                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4987                               DAG);
4988   }
4989
4990   // In case BestHi & BestLo were both -1, which means each quadword has a word
4991   // from each of the four input quadwords, calculate the InOrder bitvector now
4992   // before falling through to the insert/extract cleanup.
4993   if (BestLoQuad == -1 && BestHiQuad == -1) {
4994     NewV = V1;
4995     for (int i = 0; i != 8; ++i)
4996       if (MaskVals[i] < 0 || MaskVals[i] == i)
4997         InOrder.set(i);
4998   }
4999
5000   // The other elements are put in the right place using pextrw and pinsrw.
5001   for (unsigned i = 0; i != 8; ++i) {
5002     if (InOrder[i])
5003       continue;
5004     int EltIdx = MaskVals[i];
5005     if (EltIdx < 0)
5006       continue;
5007     SDValue ExtOp = (EltIdx < 8)
5008     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5009                   DAG.getIntPtrConstant(EltIdx))
5010     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5011                   DAG.getIntPtrConstant(EltIdx - 8));
5012     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5013                        DAG.getIntPtrConstant(i));
5014   }
5015   return NewV;
5016 }
5017
5018 // v16i8 shuffles - Prefer shuffles in the following order:
5019 // 1. [ssse3] 1 x pshufb
5020 // 2. [ssse3] 2 x pshufb + 1 x por
5021 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5022 static
5023 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5024                                  SelectionDAG &DAG,
5025                                  const X86TargetLowering &TLI) {
5026   SDValue V1 = SVOp->getOperand(0);
5027   SDValue V2 = SVOp->getOperand(1);
5028   DebugLoc dl = SVOp->getDebugLoc();
5029   SmallVector<int, 16> MaskVals;
5030   SVOp->getMask(MaskVals);
5031
5032   // If we have SSSE3, case 1 is generated when all result bytes come from
5033   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5034   // present, fall back to case 3.
5035   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5036   bool V1Only = true;
5037   bool V2Only = true;
5038   for (unsigned i = 0; i < 16; ++i) {
5039     int EltIdx = MaskVals[i];
5040     if (EltIdx < 0)
5041       continue;
5042     if (EltIdx < 16)
5043       V2Only = false;
5044     else
5045       V1Only = false;
5046   }
5047
5048   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5049   if (TLI.getSubtarget()->hasSSSE3()) {
5050     SmallVector<SDValue,16> pshufbMask;
5051
5052     // If all result elements are from one input vector, then only translate
5053     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5054     //
5055     // Otherwise, we have elements from both input vectors, and must zero out
5056     // elements that come from V2 in the first mask, and V1 in the second mask
5057     // so that we can OR them together.
5058     bool TwoInputs = !(V1Only || V2Only);
5059     for (unsigned i = 0; i != 16; ++i) {
5060       int EltIdx = MaskVals[i];
5061       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5062         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5063         continue;
5064       }
5065       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5066     }
5067     // If all the elements are from V2, assign it to V1 and return after
5068     // building the first pshufb.
5069     if (V2Only)
5070       V1 = V2;
5071     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5072                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5073                                  MVT::v16i8, &pshufbMask[0], 16));
5074     if (!TwoInputs)
5075       return V1;
5076
5077     // Calculate the shuffle mask for the second input, shuffle it, and
5078     // OR it with the first shuffled input.
5079     pshufbMask.clear();
5080     for (unsigned i = 0; i != 16; ++i) {
5081       int EltIdx = MaskVals[i];
5082       if (EltIdx < 16) {
5083         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5084         continue;
5085       }
5086       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5087     }
5088     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5089                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5090                                  MVT::v16i8, &pshufbMask[0], 16));
5091     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5092   }
5093
5094   // No SSSE3 - Calculate in place words and then fix all out of place words
5095   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5096   // the 16 different words that comprise the two doublequadword input vectors.
5097   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5098   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5099   SDValue NewV = V2Only ? V2 : V1;
5100   for (int i = 0; i != 8; ++i) {
5101     int Elt0 = MaskVals[i*2];
5102     int Elt1 = MaskVals[i*2+1];
5103
5104     // This word of the result is all undef, skip it.
5105     if (Elt0 < 0 && Elt1 < 0)
5106       continue;
5107
5108     // This word of the result is already in the correct place, skip it.
5109     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5110       continue;
5111     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5112       continue;
5113
5114     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5115     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5116     SDValue InsElt;
5117
5118     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5119     // using a single extract together, load it and store it.
5120     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5121       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5122                            DAG.getIntPtrConstant(Elt1 / 2));
5123       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5124                         DAG.getIntPtrConstant(i));
5125       continue;
5126     }
5127
5128     // If Elt1 is defined, extract it from the appropriate source.  If the
5129     // source byte is not also odd, shift the extracted word left 8 bits
5130     // otherwise clear the bottom 8 bits if we need to do an or.
5131     if (Elt1 >= 0) {
5132       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5133                            DAG.getIntPtrConstant(Elt1 / 2));
5134       if ((Elt1 & 1) == 0)
5135         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5136                              DAG.getConstant(8,
5137                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5138       else if (Elt0 >= 0)
5139         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5140                              DAG.getConstant(0xFF00, MVT::i16));
5141     }
5142     // If Elt0 is defined, extract it from the appropriate source.  If the
5143     // source byte is not also even, shift the extracted word right 8 bits. If
5144     // Elt1 was also defined, OR the extracted values together before
5145     // inserting them in the result.
5146     if (Elt0 >= 0) {
5147       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5148                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5149       if ((Elt0 & 1) != 0)
5150         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5151                               DAG.getConstant(8,
5152                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5153       else if (Elt1 >= 0)
5154         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5155                              DAG.getConstant(0x00FF, MVT::i16));
5156       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5157                          : InsElt0;
5158     }
5159     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5160                        DAG.getIntPtrConstant(i));
5161   }
5162   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5163 }
5164
5165 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5166 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5167 /// done when every pair / quad of shuffle mask elements point to elements in
5168 /// the right sequence. e.g.
5169 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5170 static
5171 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5172                                  SelectionDAG &DAG, DebugLoc dl) {
5173   EVT VT = SVOp->getValueType(0);
5174   SDValue V1 = SVOp->getOperand(0);
5175   SDValue V2 = SVOp->getOperand(1);
5176   unsigned NumElems = VT.getVectorNumElements();
5177   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5178   EVT NewVT;
5179   switch (VT.getSimpleVT().SimpleTy) {
5180   default: assert(false && "Unexpected!");
5181   case MVT::v4f32: NewVT = MVT::v2f64; break;
5182   case MVT::v4i32: NewVT = MVT::v2i64; break;
5183   case MVT::v8i16: NewVT = MVT::v4i32; break;
5184   case MVT::v16i8: NewVT = MVT::v4i32; break;
5185   }
5186
5187   int Scale = NumElems / NewWidth;
5188   SmallVector<int, 8> MaskVec;
5189   for (unsigned i = 0; i < NumElems; i += Scale) {
5190     int StartIdx = -1;
5191     for (int j = 0; j < Scale; ++j) {
5192       int EltIdx = SVOp->getMaskElt(i+j);
5193       if (EltIdx < 0)
5194         continue;
5195       if (StartIdx == -1)
5196         StartIdx = EltIdx - (EltIdx % Scale);
5197       if (EltIdx != StartIdx + j)
5198         return SDValue();
5199     }
5200     if (StartIdx == -1)
5201       MaskVec.push_back(-1);
5202     else
5203       MaskVec.push_back(StartIdx / Scale);
5204   }
5205
5206   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5207   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5208   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5209 }
5210
5211 /// getVZextMovL - Return a zero-extending vector move low node.
5212 ///
5213 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5214                             SDValue SrcOp, SelectionDAG &DAG,
5215                             const X86Subtarget *Subtarget, DebugLoc dl) {
5216   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5217     LoadSDNode *LD = NULL;
5218     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5219       LD = dyn_cast<LoadSDNode>(SrcOp);
5220     if (!LD) {
5221       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5222       // instead.
5223       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5224       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5225           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5226           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5227           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5228         // PR2108
5229         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5230         return DAG.getNode(ISD::BITCAST, dl, VT,
5231                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5232                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5233                                                    OpVT,
5234                                                    SrcOp.getOperand(0)
5235                                                           .getOperand(0))));
5236       }
5237     }
5238   }
5239
5240   return DAG.getNode(ISD::BITCAST, dl, VT,
5241                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5242                                  DAG.getNode(ISD::BITCAST, dl,
5243                                              OpVT, SrcOp)));
5244 }
5245
5246 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5247 /// shuffles.
5248 static SDValue
5249 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5250   SDValue V1 = SVOp->getOperand(0);
5251   SDValue V2 = SVOp->getOperand(1);
5252   DebugLoc dl = SVOp->getDebugLoc();
5253   EVT VT = SVOp->getValueType(0);
5254
5255   SmallVector<std::pair<int, int>, 8> Locs;
5256   Locs.resize(4);
5257   SmallVector<int, 8> Mask1(4U, -1);
5258   SmallVector<int, 8> PermMask;
5259   SVOp->getMask(PermMask);
5260
5261   unsigned NumHi = 0;
5262   unsigned NumLo = 0;
5263   for (unsigned i = 0; i != 4; ++i) {
5264     int Idx = PermMask[i];
5265     if (Idx < 0) {
5266       Locs[i] = std::make_pair(-1, -1);
5267     } else {
5268       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5269       if (Idx < 4) {
5270         Locs[i] = std::make_pair(0, NumLo);
5271         Mask1[NumLo] = Idx;
5272         NumLo++;
5273       } else {
5274         Locs[i] = std::make_pair(1, NumHi);
5275         if (2+NumHi < 4)
5276           Mask1[2+NumHi] = Idx;
5277         NumHi++;
5278       }
5279     }
5280   }
5281
5282   if (NumLo <= 2 && NumHi <= 2) {
5283     // If no more than two elements come from either vector. This can be
5284     // implemented with two shuffles. First shuffle gather the elements.
5285     // The second shuffle, which takes the first shuffle as both of its
5286     // vector operands, put the elements into the right order.
5287     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5288
5289     SmallVector<int, 8> Mask2(4U, -1);
5290
5291     for (unsigned i = 0; i != 4; ++i) {
5292       if (Locs[i].first == -1)
5293         continue;
5294       else {
5295         unsigned Idx = (i < 2) ? 0 : 4;
5296         Idx += Locs[i].first * 2 + Locs[i].second;
5297         Mask2[i] = Idx;
5298       }
5299     }
5300
5301     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5302   } else if (NumLo == 3 || NumHi == 3) {
5303     // Otherwise, we must have three elements from one vector, call it X, and
5304     // one element from the other, call it Y.  First, use a shufps to build an
5305     // intermediate vector with the one element from Y and the element from X
5306     // that will be in the same half in the final destination (the indexes don't
5307     // matter). Then, use a shufps to build the final vector, taking the half
5308     // containing the element from Y from the intermediate, and the other half
5309     // from X.
5310     if (NumHi == 3) {
5311       // Normalize it so the 3 elements come from V1.
5312       CommuteVectorShuffleMask(PermMask, VT);
5313       std::swap(V1, V2);
5314     }
5315
5316     // Find the element from V2.
5317     unsigned HiIndex;
5318     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5319       int Val = PermMask[HiIndex];
5320       if (Val < 0)
5321         continue;
5322       if (Val >= 4)
5323         break;
5324     }
5325
5326     Mask1[0] = PermMask[HiIndex];
5327     Mask1[1] = -1;
5328     Mask1[2] = PermMask[HiIndex^1];
5329     Mask1[3] = -1;
5330     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5331
5332     if (HiIndex >= 2) {
5333       Mask1[0] = PermMask[0];
5334       Mask1[1] = PermMask[1];
5335       Mask1[2] = HiIndex & 1 ? 6 : 4;
5336       Mask1[3] = HiIndex & 1 ? 4 : 6;
5337       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5338     } else {
5339       Mask1[0] = HiIndex & 1 ? 2 : 0;
5340       Mask1[1] = HiIndex & 1 ? 0 : 2;
5341       Mask1[2] = PermMask[2];
5342       Mask1[3] = PermMask[3];
5343       if (Mask1[2] >= 0)
5344         Mask1[2] += 4;
5345       if (Mask1[3] >= 0)
5346         Mask1[3] += 4;
5347       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5348     }
5349   }
5350
5351   // Break it into (shuffle shuffle_hi, shuffle_lo).
5352   Locs.clear();
5353   Locs.resize(4);
5354   SmallVector<int,8> LoMask(4U, -1);
5355   SmallVector<int,8> HiMask(4U, -1);
5356
5357   SmallVector<int,8> *MaskPtr = &LoMask;
5358   unsigned MaskIdx = 0;
5359   unsigned LoIdx = 0;
5360   unsigned HiIdx = 2;
5361   for (unsigned i = 0; i != 4; ++i) {
5362     if (i == 2) {
5363       MaskPtr = &HiMask;
5364       MaskIdx = 1;
5365       LoIdx = 0;
5366       HiIdx = 2;
5367     }
5368     int Idx = PermMask[i];
5369     if (Idx < 0) {
5370       Locs[i] = std::make_pair(-1, -1);
5371     } else if (Idx < 4) {
5372       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5373       (*MaskPtr)[LoIdx] = Idx;
5374       LoIdx++;
5375     } else {
5376       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5377       (*MaskPtr)[HiIdx] = Idx;
5378       HiIdx++;
5379     }
5380   }
5381
5382   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5383   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5384   SmallVector<int, 8> MaskOps;
5385   for (unsigned i = 0; i != 4; ++i) {
5386     if (Locs[i].first == -1) {
5387       MaskOps.push_back(-1);
5388     } else {
5389       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5390       MaskOps.push_back(Idx);
5391     }
5392   }
5393   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5394 }
5395
5396 static bool MayFoldVectorLoad(SDValue V) {
5397   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5398     V = V.getOperand(0);
5399   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5400     V = V.getOperand(0);
5401   if (MayFoldLoad(V))
5402     return true;
5403   return false;
5404 }
5405
5406 // FIXME: the version above should always be used. Since there's
5407 // a bug where several vector shuffles can't be folded because the
5408 // DAG is not updated during lowering and a node claims to have two
5409 // uses while it only has one, use this version, and let isel match
5410 // another instruction if the load really happens to have more than
5411 // one use. Remove this version after this bug get fixed.
5412 // rdar://8434668, PR8156
5413 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5414   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5415     V = V.getOperand(0);
5416   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5417     V = V.getOperand(0);
5418   if (ISD::isNormalLoad(V.getNode()))
5419     return true;
5420   return false;
5421 }
5422
5423 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5424 /// a vector extract, and if both can be later optimized into a single load.
5425 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5426 /// here because otherwise a target specific shuffle node is going to be
5427 /// emitted for this shuffle, and the optimization not done.
5428 /// FIXME: This is probably not the best approach, but fix the problem
5429 /// until the right path is decided.
5430 static
5431 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5432                                          const TargetLowering &TLI) {
5433   EVT VT = V.getValueType();
5434   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5435
5436   // Be sure that the vector shuffle is present in a pattern like this:
5437   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5438   if (!V.hasOneUse())
5439     return false;
5440
5441   SDNode *N = *V.getNode()->use_begin();
5442   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5443     return false;
5444
5445   SDValue EltNo = N->getOperand(1);
5446   if (!isa<ConstantSDNode>(EltNo))
5447     return false;
5448
5449   // If the bit convert changed the number of elements, it is unsafe
5450   // to examine the mask.
5451   bool HasShuffleIntoBitcast = false;
5452   if (V.getOpcode() == ISD::BITCAST) {
5453     EVT SrcVT = V.getOperand(0).getValueType();
5454     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5455       return false;
5456     V = V.getOperand(0);
5457     HasShuffleIntoBitcast = true;
5458   }
5459
5460   // Select the input vector, guarding against out of range extract vector.
5461   unsigned NumElems = VT.getVectorNumElements();
5462   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5463   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5464   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5465
5466   // Skip one more bit_convert if necessary
5467   if (V.getOpcode() == ISD::BITCAST)
5468     V = V.getOperand(0);
5469
5470   if (ISD::isNormalLoad(V.getNode())) {
5471     // Is the original load suitable?
5472     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5473
5474     // FIXME: avoid the multi-use bug that is preventing lots of
5475     // of foldings to be detected, this is still wrong of course, but
5476     // give the temporary desired behavior, and if it happens that
5477     // the load has real more uses, during isel it will not fold, and
5478     // will generate poor code.
5479     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5480       return false;
5481
5482     if (!HasShuffleIntoBitcast)
5483       return true;
5484
5485     // If there's a bitcast before the shuffle, check if the load type and
5486     // alignment is valid.
5487     unsigned Align = LN0->getAlignment();
5488     unsigned NewAlign =
5489       TLI.getTargetData()->getABITypeAlignment(
5490                                     VT.getTypeForEVT(*DAG.getContext()));
5491
5492     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5493       return false;
5494   }
5495
5496   return true;
5497 }
5498
5499 static
5500 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5501   EVT VT = Op.getValueType();
5502
5503   // Canonizalize to v2f64.
5504   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5505   return DAG.getNode(ISD::BITCAST, dl, VT,
5506                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5507                                           V1, DAG));
5508 }
5509
5510 static
5511 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5512                         bool HasSSE2) {
5513   SDValue V1 = Op.getOperand(0);
5514   SDValue V2 = Op.getOperand(1);
5515   EVT VT = Op.getValueType();
5516
5517   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5518
5519   if (HasSSE2 && VT == MVT::v2f64)
5520     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5521
5522   // v4f32 or v4i32
5523   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5524 }
5525
5526 static
5527 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5528   SDValue V1 = Op.getOperand(0);
5529   SDValue V2 = Op.getOperand(1);
5530   EVT VT = Op.getValueType();
5531
5532   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5533          "unsupported shuffle type");
5534
5535   if (V2.getOpcode() == ISD::UNDEF)
5536     V2 = V1;
5537
5538   // v4i32 or v4f32
5539   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5540 }
5541
5542 static
5543 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5544   SDValue V1 = Op.getOperand(0);
5545   SDValue V2 = Op.getOperand(1);
5546   EVT VT = Op.getValueType();
5547   unsigned NumElems = VT.getVectorNumElements();
5548
5549   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5550   // operand of these instructions is only memory, so check if there's a
5551   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5552   // same masks.
5553   bool CanFoldLoad = false;
5554
5555   // Trivial case, when V2 comes from a load.
5556   if (MayFoldVectorLoad(V2))
5557     CanFoldLoad = true;
5558
5559   // When V1 is a load, it can be folded later into a store in isel, example:
5560   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5561   //    turns into:
5562   //  (MOVLPSmr addr:$src1, VR128:$src2)
5563   // So, recognize this potential and also use MOVLPS or MOVLPD
5564   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5565     CanFoldLoad = true;
5566
5567   // Both of them can't be memory operations though.
5568   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5569     CanFoldLoad = false;
5570
5571   if (CanFoldLoad) {
5572     if (HasSSE2 && NumElems == 2)
5573       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5574
5575     if (NumElems == 4)
5576       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5577   }
5578
5579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5580   // movl and movlp will both match v2i64, but v2i64 is never matched by
5581   // movl earlier because we make it strict to avoid messing with the movlp load
5582   // folding logic (see the code above getMOVLP call). Match it here then,
5583   // this is horrible, but will stay like this until we move all shuffle
5584   // matching to x86 specific nodes. Note that for the 1st condition all
5585   // types are matched with movsd.
5586   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5587     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5588   else if (HasSSE2)
5589     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5590
5591
5592   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5593
5594   // Invert the operand order and use SHUFPS to match it.
5595   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5596                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5597 }
5598
5599 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5600   switch(VT.getSimpleVT().SimpleTy) {
5601   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5602   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5603   case MVT::v4f32:
5604     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5605   case MVT::v2f64:
5606     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5607   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5608   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5609   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5610   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5611   default:
5612     llvm_unreachable("Unknown type for unpckl");
5613   }
5614   return 0;
5615 }
5616
5617 static inline unsigned getUNPCKHOpcode(EVT VT) {
5618   switch(VT.getSimpleVT().SimpleTy) {
5619   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5620   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5621   case MVT::v4f32: return X86ISD::UNPCKHPS;
5622   case MVT::v2f64: return X86ISD::UNPCKHPD;
5623   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5624   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5625   default:
5626     llvm_unreachable("Unknown type for unpckh");
5627   }
5628   return 0;
5629 }
5630
5631 static
5632 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5633                                const TargetLowering &TLI,
5634                                const X86Subtarget *Subtarget) {
5635   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5636   EVT VT = Op.getValueType();
5637   DebugLoc dl = Op.getDebugLoc();
5638   SDValue V1 = Op.getOperand(0);
5639   SDValue V2 = Op.getOperand(1);
5640
5641   if (isZeroShuffle(SVOp))
5642     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5643
5644   // Handle splat operations
5645   if (SVOp->isSplat()) {
5646     // Special case, this is the only place now where it's
5647     // allowed to return a vector_shuffle operation without
5648     // using a target specific node, because *hopefully* it
5649     // will be optimized away by the dag combiner.
5650     if (VT.getVectorNumElements() <= 4 &&
5651         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5652       return Op;
5653
5654     // Handle splats by matching through known masks
5655     if (VT.getVectorNumElements() <= 4)
5656       return SDValue();
5657
5658     // Canonicalize all of the remaining to v4f32.
5659     return PromoteSplat(SVOp, DAG);
5660   }
5661
5662   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5663   // do it!
5664   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5665     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5666     if (NewOp.getNode())
5667       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5668   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5669     // FIXME: Figure out a cleaner way to do this.
5670     // Try to make use of movq to zero out the top part.
5671     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5672       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5673       if (NewOp.getNode()) {
5674         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5675           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5676                               DAG, Subtarget, dl);
5677       }
5678     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5679       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5680       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5681         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5682                             DAG, Subtarget, dl);
5683     }
5684   }
5685   return SDValue();
5686 }
5687
5688 SDValue
5689 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5691   SDValue V1 = Op.getOperand(0);
5692   SDValue V2 = Op.getOperand(1);
5693   EVT VT = Op.getValueType();
5694   DebugLoc dl = Op.getDebugLoc();
5695   unsigned NumElems = VT.getVectorNumElements();
5696   bool isMMX = VT.getSizeInBits() == 64;
5697   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5698   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5699   bool V1IsSplat = false;
5700   bool V2IsSplat = false;
5701   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5702   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5703   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5704   MachineFunction &MF = DAG.getMachineFunction();
5705   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5706
5707   // Shuffle operations on MMX not supported.
5708   if (isMMX)
5709     return Op;
5710
5711   // Vector shuffle lowering takes 3 steps:
5712   //
5713   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5714   //    narrowing and commutation of operands should be handled.
5715   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5716   //    shuffle nodes.
5717   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5718   //    so the shuffle can be broken into other shuffles and the legalizer can
5719   //    try the lowering again.
5720   //
5721   // The general ideia is that no vector_shuffle operation should be left to
5722   // be matched during isel, all of them must be converted to a target specific
5723   // node here.
5724
5725   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5726   // narrowing and commutation of operands should be handled. The actual code
5727   // doesn't include all of those, work in progress...
5728   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5729   if (NewOp.getNode())
5730     return NewOp;
5731
5732   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5733   // unpckh_undef). Only use pshufd if speed is more important than size.
5734   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5735     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5736       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5737   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5738     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5739       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5740
5741   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5742       RelaxedMayFoldVectorLoad(V1))
5743     return getMOVDDup(Op, dl, V1, DAG);
5744
5745   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5746     return getMOVHighToLow(Op, dl, DAG);
5747
5748   // Use to match splats
5749   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5750       (VT == MVT::v2f64 || VT == MVT::v2i64))
5751     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5752
5753   if (X86::isPSHUFDMask(SVOp)) {
5754     // The actual implementation will match the mask in the if above and then
5755     // during isel it can match several different instructions, not only pshufd
5756     // as its name says, sad but true, emulate the behavior for now...
5757     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5758         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5759
5760     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5761
5762     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5763       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5764
5765     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5766       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5767                                   TargetMask, DAG);
5768
5769     if (VT == MVT::v4f32)
5770       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5771                                   TargetMask, DAG);
5772   }
5773
5774   // Check if this can be converted into a logical shift.
5775   bool isLeft = false;
5776   unsigned ShAmt = 0;
5777   SDValue ShVal;
5778   bool isShift = getSubtarget()->hasSSE2() &&
5779     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5780   if (isShift && ShVal.hasOneUse()) {
5781     // If the shifted value has multiple uses, it may be cheaper to use
5782     // v_set0 + movlhps or movhlps, etc.
5783     EVT EltVT = VT.getVectorElementType();
5784     ShAmt *= EltVT.getSizeInBits();
5785     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5786   }
5787
5788   if (X86::isMOVLMask(SVOp)) {
5789     if (V1IsUndef)
5790       return V2;
5791     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5792       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5793     if (!X86::isMOVLPMask(SVOp)) {
5794       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5795         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5796
5797       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5798         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5799     }
5800   }
5801
5802   // FIXME: fold these into legal mask.
5803   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5804     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5805
5806   if (X86::isMOVHLPSMask(SVOp))
5807     return getMOVHighToLow(Op, dl, DAG);
5808
5809   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5810     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5811
5812   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5813     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5814
5815   if (X86::isMOVLPMask(SVOp))
5816     return getMOVLP(Op, dl, DAG, HasSSE2);
5817
5818   if (ShouldXformToMOVHLPS(SVOp) ||
5819       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5820     return CommuteVectorShuffle(SVOp, DAG);
5821
5822   if (isShift) {
5823     // No better options. Use a vshl / vsrl.
5824     EVT EltVT = VT.getVectorElementType();
5825     ShAmt *= EltVT.getSizeInBits();
5826     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5827   }
5828
5829   bool Commuted = false;
5830   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5831   // 1,1,1,1 -> v8i16 though.
5832   V1IsSplat = isSplatVector(V1.getNode());
5833   V2IsSplat = isSplatVector(V2.getNode());
5834
5835   // Canonicalize the splat or undef, if present, to be on the RHS.
5836   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5837     Op = CommuteVectorShuffle(SVOp, DAG);
5838     SVOp = cast<ShuffleVectorSDNode>(Op);
5839     V1 = SVOp->getOperand(0);
5840     V2 = SVOp->getOperand(1);
5841     std::swap(V1IsSplat, V2IsSplat);
5842     std::swap(V1IsUndef, V2IsUndef);
5843     Commuted = true;
5844   }
5845
5846   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5847     // Shuffling low element of v1 into undef, just return v1.
5848     if (V2IsUndef)
5849       return V1;
5850     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5851     // the instruction selector will not match, so get a canonical MOVL with
5852     // swapped operands to undo the commute.
5853     return getMOVL(DAG, dl, VT, V2, V1);
5854   }
5855
5856   if (X86::isUNPCKLMask(SVOp))
5857     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5858                                 dl, VT, V1, V2, DAG);
5859
5860   if (X86::isUNPCKHMask(SVOp))
5861     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5862
5863   if (V2IsSplat) {
5864     // Normalize mask so all entries that point to V2 points to its first
5865     // element then try to match unpck{h|l} again. If match, return a
5866     // new vector_shuffle with the corrected mask.
5867     SDValue NewMask = NormalizeMask(SVOp, DAG);
5868     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5869     if (NSVOp != SVOp) {
5870       if (X86::isUNPCKLMask(NSVOp, true)) {
5871         return NewMask;
5872       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5873         return NewMask;
5874       }
5875     }
5876   }
5877
5878   if (Commuted) {
5879     // Commute is back and try unpck* again.
5880     // FIXME: this seems wrong.
5881     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5882     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5883
5884     if (X86::isUNPCKLMask(NewSVOp))
5885       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5886                                   dl, VT, V2, V1, DAG);
5887
5888     if (X86::isUNPCKHMask(NewSVOp))
5889       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5890   }
5891
5892   // Normalize the node to match x86 shuffle ops if needed
5893   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5894     return CommuteVectorShuffle(SVOp, DAG);
5895
5896   // The checks below are all present in isShuffleMaskLegal, but they are
5897   // inlined here right now to enable us to directly emit target specific
5898   // nodes, and remove one by one until they don't return Op anymore.
5899   SmallVector<int, 16> M;
5900   SVOp->getMask(M);
5901
5902   if (isPALIGNRMask(M, VT, HasSSSE3))
5903     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5904                                 X86::getShufflePALIGNRImmediate(SVOp),
5905                                 DAG);
5906
5907   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5908       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5909     if (VT == MVT::v2f64) {
5910       X86ISD::NodeType Opcode =
5911         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5912       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5913     }
5914     if (VT == MVT::v2i64)
5915       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5916   }
5917
5918   if (isPSHUFHWMask(M, VT))
5919     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5920                                 X86::getShufflePSHUFHWImmediate(SVOp),
5921                                 DAG);
5922
5923   if (isPSHUFLWMask(M, VT))
5924     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5925                                 X86::getShufflePSHUFLWImmediate(SVOp),
5926                                 DAG);
5927
5928   if (isSHUFPMask(M, VT)) {
5929     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5930     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5931       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5932                                   TargetMask, DAG);
5933     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5934       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5935                                   TargetMask, DAG);
5936   }
5937
5938   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5939     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5940       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5941                                   dl, VT, V1, V1, DAG);
5942   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5943     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5944       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5945
5946   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5947   if (VT == MVT::v8i16) {
5948     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5949     if (NewOp.getNode())
5950       return NewOp;
5951   }
5952
5953   if (VT == MVT::v16i8) {
5954     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5955     if (NewOp.getNode())
5956       return NewOp;
5957   }
5958
5959   // Handle all 4 wide cases with a number of shuffles.
5960   if (NumElems == 4)
5961     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5962
5963   return SDValue();
5964 }
5965
5966 SDValue
5967 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5968                                                 SelectionDAG &DAG) const {
5969   EVT VT = Op.getValueType();
5970   DebugLoc dl = Op.getDebugLoc();
5971   if (VT.getSizeInBits() == 8) {
5972     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5973                                     Op.getOperand(0), Op.getOperand(1));
5974     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5975                                     DAG.getValueType(VT));
5976     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5977   } else if (VT.getSizeInBits() == 16) {
5978     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5979     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5980     if (Idx == 0)
5981       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5982                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5983                                      DAG.getNode(ISD::BITCAST, dl,
5984                                                  MVT::v4i32,
5985                                                  Op.getOperand(0)),
5986                                      Op.getOperand(1)));
5987     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5988                                     Op.getOperand(0), Op.getOperand(1));
5989     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5990                                     DAG.getValueType(VT));
5991     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5992   } else if (VT == MVT::f32) {
5993     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5994     // the result back to FR32 register. It's only worth matching if the
5995     // result has a single use which is a store or a bitcast to i32.  And in
5996     // the case of a store, it's not worth it if the index is a constant 0,
5997     // because a MOVSSmr can be used instead, which is smaller and faster.
5998     if (!Op.hasOneUse())
5999       return SDValue();
6000     SDNode *User = *Op.getNode()->use_begin();
6001     if ((User->getOpcode() != ISD::STORE ||
6002          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6003           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6004         (User->getOpcode() != ISD::BITCAST ||
6005          User->getValueType(0) != MVT::i32))
6006       return SDValue();
6007     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6008                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6009                                               Op.getOperand(0)),
6010                                               Op.getOperand(1));
6011     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6012   } else if (VT == MVT::i32) {
6013     // ExtractPS works with constant index.
6014     if (isa<ConstantSDNode>(Op.getOperand(1)))
6015       return Op;
6016   }
6017   return SDValue();
6018 }
6019
6020
6021 SDValue
6022 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6023                                            SelectionDAG &DAG) const {
6024   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6025     return SDValue();
6026
6027   SDValue Vec = Op.getOperand(0);
6028   EVT VecVT = Vec.getValueType();
6029
6030   // If this is a 256-bit vector result, first extract the 128-bit
6031   // vector and then extract from the 128-bit vector.
6032   if (VecVT.getSizeInBits() > 128) {
6033     DebugLoc dl = Op.getNode()->getDebugLoc();
6034     unsigned NumElems = VecVT.getVectorNumElements();
6035     SDValue Idx = Op.getOperand(1);
6036
6037     if (!isa<ConstantSDNode>(Idx))
6038       return SDValue();
6039
6040     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6041     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6042
6043     // Get the 128-bit vector.
6044     bool Upper = IdxVal >= ExtractNumElems;
6045     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6046
6047     // Extract from it.
6048     SDValue ScaledIdx = Idx;
6049     if (Upper)
6050       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6051                               DAG.getConstant(ExtractNumElems,
6052                                               Idx.getValueType()));
6053     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6054                        ScaledIdx);
6055   }
6056
6057   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6058
6059   if (Subtarget->hasSSE41()) {
6060     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6061     if (Res.getNode())
6062       return Res;
6063   }
6064
6065   EVT VT = Op.getValueType();
6066   DebugLoc dl = Op.getDebugLoc();
6067   // TODO: handle v16i8.
6068   if (VT.getSizeInBits() == 16) {
6069     SDValue Vec = Op.getOperand(0);
6070     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6071     if (Idx == 0)
6072       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6073                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6074                                      DAG.getNode(ISD::BITCAST, dl,
6075                                                  MVT::v4i32, Vec),
6076                                      Op.getOperand(1)));
6077     // Transform it so it match pextrw which produces a 32-bit result.
6078     EVT EltVT = MVT::i32;
6079     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6080                                     Op.getOperand(0), Op.getOperand(1));
6081     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6082                                     DAG.getValueType(VT));
6083     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6084   } else if (VT.getSizeInBits() == 32) {
6085     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6086     if (Idx == 0)
6087       return Op;
6088
6089     // SHUFPS the element to the lowest double word, then movss.
6090     int Mask[4] = { Idx, -1, -1, -1 };
6091     EVT VVT = Op.getOperand(0).getValueType();
6092     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6093                                        DAG.getUNDEF(VVT), Mask);
6094     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6095                        DAG.getIntPtrConstant(0));
6096   } else if (VT.getSizeInBits() == 64) {
6097     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6098     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6099     //        to match extract_elt for f64.
6100     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6101     if (Idx == 0)
6102       return Op;
6103
6104     // UNPCKHPD the element to the lowest double word, then movsd.
6105     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6106     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6107     int Mask[2] = { 1, -1 };
6108     EVT VVT = Op.getOperand(0).getValueType();
6109     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6110                                        DAG.getUNDEF(VVT), Mask);
6111     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6112                        DAG.getIntPtrConstant(0));
6113   }
6114
6115   return SDValue();
6116 }
6117
6118 SDValue
6119 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6120                                                SelectionDAG &DAG) const {
6121   EVT VT = Op.getValueType();
6122   EVT EltVT = VT.getVectorElementType();
6123   DebugLoc dl = Op.getDebugLoc();
6124
6125   SDValue N0 = Op.getOperand(0);
6126   SDValue N1 = Op.getOperand(1);
6127   SDValue N2 = Op.getOperand(2);
6128
6129   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6130       isa<ConstantSDNode>(N2)) {
6131     unsigned Opc;
6132     if (VT == MVT::v8i16)
6133       Opc = X86ISD::PINSRW;
6134     else if (VT == MVT::v16i8)
6135       Opc = X86ISD::PINSRB;
6136     else
6137       Opc = X86ISD::PINSRB;
6138
6139     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6140     // argument.
6141     if (N1.getValueType() != MVT::i32)
6142       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6143     if (N2.getValueType() != MVT::i32)
6144       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6145     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6146   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6147     // Bits [7:6] of the constant are the source select.  This will always be
6148     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6149     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6150     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6151     // Bits [5:4] of the constant are the destination select.  This is the
6152     //  value of the incoming immediate.
6153     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6154     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6155     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6156     // Create this as a scalar to vector..
6157     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6158     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6159   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6160     // PINSR* works with constant index.
6161     return Op;
6162   }
6163   return SDValue();
6164 }
6165
6166 SDValue
6167 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6168   EVT VT = Op.getValueType();
6169   EVT EltVT = VT.getVectorElementType();
6170
6171   DebugLoc dl = Op.getDebugLoc();
6172   SDValue N0 = Op.getOperand(0);
6173   SDValue N1 = Op.getOperand(1);
6174   SDValue N2 = Op.getOperand(2);
6175
6176   // If this is a 256-bit vector result, first insert into a 128-bit
6177   // vector and then insert into the 256-bit vector.
6178   if (VT.getSizeInBits() > 128) {
6179     if (!isa<ConstantSDNode>(N2))
6180       return SDValue();
6181
6182     // Get the 128-bit vector.
6183     unsigned NumElems = VT.getVectorNumElements();
6184     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6185     bool Upper = IdxVal >= NumElems / 2;
6186
6187     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6188
6189     // Insert into it.
6190     SDValue ScaledN2 = N2;
6191     if (Upper)
6192       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6193                              DAG.getConstant(NumElems /
6194                                              (VT.getSizeInBits() / 128),
6195                                              N2.getValueType()));
6196     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6197                      N1, ScaledN2);
6198
6199     // Insert the 128-bit vector
6200     // FIXME: Why UNDEF?
6201     return Insert128BitVector(N0, Op, N2, DAG, dl);
6202   }
6203
6204   if (Subtarget->hasSSE41())
6205     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6206
6207   if (EltVT == MVT::i8)
6208     return SDValue();
6209
6210   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6211     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6212     // as its second argument.
6213     if (N1.getValueType() != MVT::i32)
6214       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6215     if (N2.getValueType() != MVT::i32)
6216       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6217     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6218   }
6219   return SDValue();
6220 }
6221
6222 SDValue
6223 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6224   LLVMContext *Context = DAG.getContext();
6225   DebugLoc dl = Op.getDebugLoc();
6226   EVT OpVT = Op.getValueType();
6227
6228   // If this is a 256-bit vector result, first insert into a 128-bit
6229   // vector and then insert into the 256-bit vector.
6230   if (OpVT.getSizeInBits() > 128) {
6231     // Insert into a 128-bit vector.
6232     EVT VT128 = EVT::getVectorVT(*Context,
6233                                  OpVT.getVectorElementType(),
6234                                  OpVT.getVectorNumElements() / 2);
6235
6236     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6237
6238     // Insert the 128-bit vector.
6239     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6240                               DAG.getConstant(0, MVT::i32),
6241                               DAG, dl);
6242   }
6243
6244   if (Op.getValueType() == MVT::v1i64 &&
6245       Op.getOperand(0).getValueType() == MVT::i64)
6246     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6247
6248   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6249   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6250          "Expected an SSE type!");
6251   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6252                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6253 }
6254
6255 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6256 // a simple subregister reference or explicit instructions to grab
6257 // upper bits of a vector.
6258 SDValue
6259 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6260   if (Subtarget->hasAVX()) {
6261     DebugLoc dl = Op.getNode()->getDebugLoc();
6262     SDValue Vec = Op.getNode()->getOperand(0);
6263     SDValue Idx = Op.getNode()->getOperand(1);
6264
6265     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6266         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6267         return Extract128BitVector(Vec, Idx, DAG, dl);
6268     }
6269   }
6270   return SDValue();
6271 }
6272
6273 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6274 // simple superregister reference or explicit instructions to insert
6275 // the upper bits of a vector.
6276 SDValue
6277 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6278   if (Subtarget->hasAVX()) {
6279     DebugLoc dl = Op.getNode()->getDebugLoc();
6280     SDValue Vec = Op.getNode()->getOperand(0);
6281     SDValue SubVec = Op.getNode()->getOperand(1);
6282     SDValue Idx = Op.getNode()->getOperand(2);
6283
6284     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6285         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6286       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6287     }
6288   }
6289   return SDValue();
6290 }
6291
6292 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6293 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6294 // one of the above mentioned nodes. It has to be wrapped because otherwise
6295 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6296 // be used to form addressing mode. These wrapped nodes will be selected
6297 // into MOV32ri.
6298 SDValue
6299 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6300   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6301
6302   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6303   // global base reg.
6304   unsigned char OpFlag = 0;
6305   unsigned WrapperKind = X86ISD::Wrapper;
6306   CodeModel::Model M = getTargetMachine().getCodeModel();
6307
6308   if (Subtarget->isPICStyleRIPRel() &&
6309       (M == CodeModel::Small || M == CodeModel::Kernel))
6310     WrapperKind = X86ISD::WrapperRIP;
6311   else if (Subtarget->isPICStyleGOT())
6312     OpFlag = X86II::MO_GOTOFF;
6313   else if (Subtarget->isPICStyleStubPIC())
6314     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6315
6316   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6317                                              CP->getAlignment(),
6318                                              CP->getOffset(), OpFlag);
6319   DebugLoc DL = CP->getDebugLoc();
6320   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6321   // With PIC, the address is actually $g + Offset.
6322   if (OpFlag) {
6323     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6324                          DAG.getNode(X86ISD::GlobalBaseReg,
6325                                      DebugLoc(), getPointerTy()),
6326                          Result);
6327   }
6328
6329   return Result;
6330 }
6331
6332 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6333   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6334
6335   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6336   // global base reg.
6337   unsigned char OpFlag = 0;
6338   unsigned WrapperKind = X86ISD::Wrapper;
6339   CodeModel::Model M = getTargetMachine().getCodeModel();
6340
6341   if (Subtarget->isPICStyleRIPRel() &&
6342       (M == CodeModel::Small || M == CodeModel::Kernel))
6343     WrapperKind = X86ISD::WrapperRIP;
6344   else if (Subtarget->isPICStyleGOT())
6345     OpFlag = X86II::MO_GOTOFF;
6346   else if (Subtarget->isPICStyleStubPIC())
6347     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6348
6349   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6350                                           OpFlag);
6351   DebugLoc DL = JT->getDebugLoc();
6352   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6353
6354   // With PIC, the address is actually $g + Offset.
6355   if (OpFlag)
6356     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6357                          DAG.getNode(X86ISD::GlobalBaseReg,
6358                                      DebugLoc(), getPointerTy()),
6359                          Result);
6360
6361   return Result;
6362 }
6363
6364 SDValue
6365 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6366   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6367
6368   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6369   // global base reg.
6370   unsigned char OpFlag = 0;
6371   unsigned WrapperKind = X86ISD::Wrapper;
6372   CodeModel::Model M = getTargetMachine().getCodeModel();
6373
6374   if (Subtarget->isPICStyleRIPRel() &&
6375       (M == CodeModel::Small || M == CodeModel::Kernel))
6376     WrapperKind = X86ISD::WrapperRIP;
6377   else if (Subtarget->isPICStyleGOT())
6378     OpFlag = X86II::MO_GOTOFF;
6379   else if (Subtarget->isPICStyleStubPIC())
6380     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6381
6382   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6383
6384   DebugLoc DL = Op.getDebugLoc();
6385   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6386
6387
6388   // With PIC, the address is actually $g + Offset.
6389   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6390       !Subtarget->is64Bit()) {
6391     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6392                          DAG.getNode(X86ISD::GlobalBaseReg,
6393                                      DebugLoc(), getPointerTy()),
6394                          Result);
6395   }
6396
6397   return Result;
6398 }
6399
6400 SDValue
6401 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6402   // Create the TargetBlockAddressAddress node.
6403   unsigned char OpFlags =
6404     Subtarget->ClassifyBlockAddressReference();
6405   CodeModel::Model M = getTargetMachine().getCodeModel();
6406   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6407   DebugLoc dl = Op.getDebugLoc();
6408   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6409                                        /*isTarget=*/true, OpFlags);
6410
6411   if (Subtarget->isPICStyleRIPRel() &&
6412       (M == CodeModel::Small || M == CodeModel::Kernel))
6413     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6414   else
6415     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6416
6417   // With PIC, the address is actually $g + Offset.
6418   if (isGlobalRelativeToPICBase(OpFlags)) {
6419     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6420                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6421                          Result);
6422   }
6423
6424   return Result;
6425 }
6426
6427 SDValue
6428 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6429                                       int64_t Offset,
6430                                       SelectionDAG &DAG) const {
6431   // Create the TargetGlobalAddress node, folding in the constant
6432   // offset if it is legal.
6433   unsigned char OpFlags =
6434     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6435   CodeModel::Model M = getTargetMachine().getCodeModel();
6436   SDValue Result;
6437   if (OpFlags == X86II::MO_NO_FLAG &&
6438       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6439     // A direct static reference to a global.
6440     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6441     Offset = 0;
6442   } else {
6443     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6444   }
6445
6446   if (Subtarget->isPICStyleRIPRel() &&
6447       (M == CodeModel::Small || M == CodeModel::Kernel))
6448     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6449   else
6450     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6451
6452   // With PIC, the address is actually $g + Offset.
6453   if (isGlobalRelativeToPICBase(OpFlags)) {
6454     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6455                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6456                          Result);
6457   }
6458
6459   // For globals that require a load from a stub to get the address, emit the
6460   // load.
6461   if (isGlobalStubReference(OpFlags))
6462     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6463                          MachinePointerInfo::getGOT(), false, false, 0);
6464
6465   // If there was a non-zero offset that we didn't fold, create an explicit
6466   // addition for it.
6467   if (Offset != 0)
6468     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6469                          DAG.getConstant(Offset, getPointerTy()));
6470
6471   return Result;
6472 }
6473
6474 SDValue
6475 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6476   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6477   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6478   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6479 }
6480
6481 static SDValue
6482 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6483            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6484            unsigned char OperandFlags) {
6485   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6486   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6487   DebugLoc dl = GA->getDebugLoc();
6488   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6489                                            GA->getValueType(0),
6490                                            GA->getOffset(),
6491                                            OperandFlags);
6492   if (InFlag) {
6493     SDValue Ops[] = { Chain,  TGA, *InFlag };
6494     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6495   } else {
6496     SDValue Ops[]  = { Chain, TGA };
6497     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6498   }
6499
6500   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6501   MFI->setAdjustsStack(true);
6502
6503   SDValue Flag = Chain.getValue(1);
6504   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6505 }
6506
6507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6508 static SDValue
6509 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6510                                 const EVT PtrVT) {
6511   SDValue InFlag;
6512   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6513   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6514                                      DAG.getNode(X86ISD::GlobalBaseReg,
6515                                                  DebugLoc(), PtrVT), InFlag);
6516   InFlag = Chain.getValue(1);
6517
6518   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6519 }
6520
6521 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6522 static SDValue
6523 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6524                                 const EVT PtrVT) {
6525   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6526                     X86::RAX, X86II::MO_TLSGD);
6527 }
6528
6529 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6530 // "local exec" model.
6531 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6532                                    const EVT PtrVT, TLSModel::Model model,
6533                                    bool is64Bit) {
6534   DebugLoc dl = GA->getDebugLoc();
6535
6536   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6537   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6538                                                          is64Bit ? 257 : 256));
6539
6540   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6541                                       DAG.getIntPtrConstant(0),
6542                                       MachinePointerInfo(Ptr), false, false, 0);
6543
6544   unsigned char OperandFlags = 0;
6545   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6546   // initialexec.
6547   unsigned WrapperKind = X86ISD::Wrapper;
6548   if (model == TLSModel::LocalExec) {
6549     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6550   } else if (is64Bit) {
6551     assert(model == TLSModel::InitialExec);
6552     OperandFlags = X86II::MO_GOTTPOFF;
6553     WrapperKind = X86ISD::WrapperRIP;
6554   } else {
6555     assert(model == TLSModel::InitialExec);
6556     OperandFlags = X86II::MO_INDNTPOFF;
6557   }
6558
6559   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6560   // exec)
6561   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6562                                            GA->getValueType(0),
6563                                            GA->getOffset(), OperandFlags);
6564   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6565
6566   if (model == TLSModel::InitialExec)
6567     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6568                          MachinePointerInfo::getGOT(), false, false, 0);
6569
6570   // The address of the thread local variable is the add of the thread
6571   // pointer with the offset of the variable.
6572   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6573 }
6574
6575 SDValue
6576 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6577
6578   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6579   const GlobalValue *GV = GA->getGlobal();
6580
6581   if (Subtarget->isTargetELF()) {
6582     // TODO: implement the "local dynamic" model
6583     // TODO: implement the "initial exec"model for pic executables
6584
6585     // If GV is an alias then use the aliasee for determining
6586     // thread-localness.
6587     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6588       GV = GA->resolveAliasedGlobal(false);
6589
6590     TLSModel::Model model
6591       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6592
6593     switch (model) {
6594       case TLSModel::GeneralDynamic:
6595       case TLSModel::LocalDynamic: // not implemented
6596         if (Subtarget->is64Bit())
6597           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6598         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6599
6600       case TLSModel::InitialExec:
6601       case TLSModel::LocalExec:
6602         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6603                                    Subtarget->is64Bit());
6604     }
6605   } else if (Subtarget->isTargetDarwin()) {
6606     // Darwin only has one model of TLS.  Lower to that.
6607     unsigned char OpFlag = 0;
6608     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6609                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6610
6611     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6612     // global base reg.
6613     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6614                   !Subtarget->is64Bit();
6615     if (PIC32)
6616       OpFlag = X86II::MO_TLVP_PIC_BASE;
6617     else
6618       OpFlag = X86II::MO_TLVP;
6619     DebugLoc DL = Op.getDebugLoc();
6620     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6621                                                 GA->getValueType(0),
6622                                                 GA->getOffset(), OpFlag);
6623     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6624
6625     // With PIC32, the address is actually $g + Offset.
6626     if (PIC32)
6627       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6628                            DAG.getNode(X86ISD::GlobalBaseReg,
6629                                        DebugLoc(), getPointerTy()),
6630                            Offset);
6631
6632     // Lowering the machine isd will make sure everything is in the right
6633     // location.
6634     SDValue Chain = DAG.getEntryNode();
6635     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6636     SDValue Args[] = { Chain, Offset };
6637     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6638
6639     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6640     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6641     MFI->setAdjustsStack(true);
6642
6643     // And our return value (tls address) is in the standard call return value
6644     // location.
6645     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6646     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6647   }
6648
6649   assert(false &&
6650          "TLS not implemented for this target.");
6651
6652   llvm_unreachable("Unreachable");
6653   return SDValue();
6654 }
6655
6656
6657 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6658 /// take a 2 x i32 value to shift plus a shift amount.
6659 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6660   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6661   EVT VT = Op.getValueType();
6662   unsigned VTBits = VT.getSizeInBits();
6663   DebugLoc dl = Op.getDebugLoc();
6664   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6665   SDValue ShOpLo = Op.getOperand(0);
6666   SDValue ShOpHi = Op.getOperand(1);
6667   SDValue ShAmt  = Op.getOperand(2);
6668   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6669                                      DAG.getConstant(VTBits - 1, MVT::i8))
6670                        : DAG.getConstant(0, VT);
6671
6672   SDValue Tmp2, Tmp3;
6673   if (Op.getOpcode() == ISD::SHL_PARTS) {
6674     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6675     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6676   } else {
6677     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6678     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6679   }
6680
6681   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6682                                 DAG.getConstant(VTBits, MVT::i8));
6683   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6684                              AndNode, DAG.getConstant(0, MVT::i8));
6685
6686   SDValue Hi, Lo;
6687   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6688   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6689   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6690
6691   if (Op.getOpcode() == ISD::SHL_PARTS) {
6692     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6693     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6694   } else {
6695     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6696     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6697   }
6698
6699   SDValue Ops[2] = { Lo, Hi };
6700   return DAG.getMergeValues(Ops, 2, dl);
6701 }
6702
6703 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6704                                            SelectionDAG &DAG) const {
6705   EVT SrcVT = Op.getOperand(0).getValueType();
6706
6707   if (SrcVT.isVector())
6708     return SDValue();
6709
6710   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6711          "Unknown SINT_TO_FP to lower!");
6712
6713   // These are really Legal; return the operand so the caller accepts it as
6714   // Legal.
6715   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6716     return Op;
6717   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6718       Subtarget->is64Bit()) {
6719     return Op;
6720   }
6721
6722   DebugLoc dl = Op.getDebugLoc();
6723   unsigned Size = SrcVT.getSizeInBits()/8;
6724   MachineFunction &MF = DAG.getMachineFunction();
6725   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6726   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6727   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6728                                StackSlot,
6729                                MachinePointerInfo::getFixedStack(SSFI),
6730                                false, false, 0);
6731   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6732 }
6733
6734 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6735                                      SDValue StackSlot,
6736                                      SelectionDAG &DAG) const {
6737   // Build the FILD
6738   DebugLoc DL = Op.getDebugLoc();
6739   SDVTList Tys;
6740   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6741   if (useSSE)
6742     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6743   else
6744     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6745
6746   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6747
6748   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6749   MachineMemOperand *MMO;
6750   if (FI) {
6751     int SSFI = FI->getIndex();
6752     MMO =
6753       DAG.getMachineFunction()
6754       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6755                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6756   } else {
6757     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6758     StackSlot = StackSlot.getOperand(1);
6759   }
6760   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6761   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6762                                            X86ISD::FILD, DL,
6763                                            Tys, Ops, array_lengthof(Ops),
6764                                            SrcVT, MMO);
6765
6766   if (useSSE) {
6767     Chain = Result.getValue(1);
6768     SDValue InFlag = Result.getValue(2);
6769
6770     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6771     // shouldn't be necessary except that RFP cannot be live across
6772     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6773     MachineFunction &MF = DAG.getMachineFunction();
6774     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6775     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6776     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6777     Tys = DAG.getVTList(MVT::Other);
6778     SDValue Ops[] = {
6779       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6780     };
6781     MachineMemOperand *MMO =
6782       DAG.getMachineFunction()
6783       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6784                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6785
6786     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6787                                     Ops, array_lengthof(Ops),
6788                                     Op.getValueType(), MMO);
6789     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6790                          MachinePointerInfo::getFixedStack(SSFI),
6791                          false, false, 0);
6792   }
6793
6794   return Result;
6795 }
6796
6797 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6798 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6799                                                SelectionDAG &DAG) const {
6800   // This algorithm is not obvious. Here it is in C code, more or less:
6801   /*
6802     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6803       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6804       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6805
6806       // Copy ints to xmm registers.
6807       __m128i xh = _mm_cvtsi32_si128( hi );
6808       __m128i xl = _mm_cvtsi32_si128( lo );
6809
6810       // Combine into low half of a single xmm register.
6811       __m128i x = _mm_unpacklo_epi32( xh, xl );
6812       __m128d d;
6813       double sd;
6814
6815       // Merge in appropriate exponents to give the integer bits the right
6816       // magnitude.
6817       x = _mm_unpacklo_epi32( x, exp );
6818
6819       // Subtract away the biases to deal with the IEEE-754 double precision
6820       // implicit 1.
6821       d = _mm_sub_pd( (__m128d) x, bias );
6822
6823       // All conversions up to here are exact. The correctly rounded result is
6824       // calculated using the current rounding mode using the following
6825       // horizontal add.
6826       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6827       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6828                                 // store doesn't really need to be here (except
6829                                 // maybe to zero the other double)
6830       return sd;
6831     }
6832   */
6833
6834   DebugLoc dl = Op.getDebugLoc();
6835   LLVMContext *Context = DAG.getContext();
6836
6837   // Build some magic constants.
6838   std::vector<Constant*> CV0;
6839   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6840   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6841   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6842   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6843   Constant *C0 = ConstantVector::get(CV0);
6844   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6845
6846   std::vector<Constant*> CV1;
6847   CV1.push_back(
6848     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6849   CV1.push_back(
6850     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6851   Constant *C1 = ConstantVector::get(CV1);
6852   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6853
6854   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6855                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6856                                         Op.getOperand(0),
6857                                         DAG.getIntPtrConstant(1)));
6858   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6859                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6860                                         Op.getOperand(0),
6861                                         DAG.getIntPtrConstant(0)));
6862   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6863   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6864                               MachinePointerInfo::getConstantPool(),
6865                               false, false, 16);
6866   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6867   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6868   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6869                               MachinePointerInfo::getConstantPool(),
6870                               false, false, 16);
6871   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6872
6873   // Add the halves; easiest way is to swap them into another reg first.
6874   int ShufMask[2] = { 1, -1 };
6875   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6876                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6877   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6878   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6879                      DAG.getIntPtrConstant(0));
6880 }
6881
6882 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6883 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6884                                                SelectionDAG &DAG) const {
6885   DebugLoc dl = Op.getDebugLoc();
6886   // FP constant to bias correct the final result.
6887   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6888                                    MVT::f64);
6889
6890   // Load the 32-bit value into an XMM register.
6891   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6892                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6893                                          Op.getOperand(0),
6894                                          DAG.getIntPtrConstant(0)));
6895
6896   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6897                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6898                      DAG.getIntPtrConstant(0));
6899
6900   // Or the load with the bias.
6901   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6902                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6903                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6904                                                    MVT::v2f64, Load)),
6905                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6906                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6907                                                    MVT::v2f64, Bias)));
6908   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6909                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6910                    DAG.getIntPtrConstant(0));
6911
6912   // Subtract the bias.
6913   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6914
6915   // Handle final rounding.
6916   EVT DestVT = Op.getValueType();
6917
6918   if (DestVT.bitsLT(MVT::f64)) {
6919     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6920                        DAG.getIntPtrConstant(0));
6921   } else if (DestVT.bitsGT(MVT::f64)) {
6922     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6923   }
6924
6925   // Handle final rounding.
6926   return Sub;
6927 }
6928
6929 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6930                                            SelectionDAG &DAG) const {
6931   SDValue N0 = Op.getOperand(0);
6932   DebugLoc dl = Op.getDebugLoc();
6933
6934   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6935   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6936   // the optimization here.
6937   if (DAG.SignBitIsZero(N0))
6938     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6939
6940   EVT SrcVT = N0.getValueType();
6941   EVT DstVT = Op.getValueType();
6942   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6943     return LowerUINT_TO_FP_i64(Op, DAG);
6944   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6945     return LowerUINT_TO_FP_i32(Op, DAG);
6946
6947   // Make a 64-bit buffer, and use it to build an FILD.
6948   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6949   if (SrcVT == MVT::i32) {
6950     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6951     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6952                                      getPointerTy(), StackSlot, WordOff);
6953     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6954                                   StackSlot, MachinePointerInfo(),
6955                                   false, false, 0);
6956     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6957                                   OffsetSlot, MachinePointerInfo(),
6958                                   false, false, 0);
6959     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6960     return Fild;
6961   }
6962
6963   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6964   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6965                                 StackSlot, MachinePointerInfo(),
6966                                false, false, 0);
6967   // For i64 source, we need to add the appropriate power of 2 if the input
6968   // was negative.  This is the same as the optimization in
6969   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6970   // we must be careful to do the computation in x87 extended precision, not
6971   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6972   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6973   MachineMemOperand *MMO =
6974     DAG.getMachineFunction()
6975     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6976                           MachineMemOperand::MOLoad, 8, 8);
6977
6978   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6979   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6980   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6981                                          MVT::i64, MMO);
6982
6983   APInt FF(32, 0x5F800000ULL);
6984
6985   // Check whether the sign bit is set.
6986   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6987                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6988                                  ISD::SETLT);
6989
6990   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6991   SDValue FudgePtr = DAG.getConstantPool(
6992                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6993                                          getPointerTy());
6994
6995   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6996   SDValue Zero = DAG.getIntPtrConstant(0);
6997   SDValue Four = DAG.getIntPtrConstant(4);
6998   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6999                                Zero, Four);
7000   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7001
7002   // Load the value out, extending it from f32 to f80.
7003   // FIXME: Avoid the extend by constructing the right constant pool?
7004   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7005                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7006                                  MVT::f32, false, false, 4);
7007   // Extend everything to 80 bits to force it to be done on x87.
7008   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7009   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7010 }
7011
7012 std::pair<SDValue,SDValue> X86TargetLowering::
7013 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7014   DebugLoc DL = Op.getDebugLoc();
7015
7016   EVT DstTy = Op.getValueType();
7017
7018   if (!IsSigned) {
7019     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7020     DstTy = MVT::i64;
7021   }
7022
7023   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7024          DstTy.getSimpleVT() >= MVT::i16 &&
7025          "Unknown FP_TO_SINT to lower!");
7026
7027   // These are really Legal.
7028   if (DstTy == MVT::i32 &&
7029       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7030     return std::make_pair(SDValue(), SDValue());
7031   if (Subtarget->is64Bit() &&
7032       DstTy == MVT::i64 &&
7033       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7034     return std::make_pair(SDValue(), SDValue());
7035
7036   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7037   // stack slot.
7038   MachineFunction &MF = DAG.getMachineFunction();
7039   unsigned MemSize = DstTy.getSizeInBits()/8;
7040   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7041   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7042
7043
7044
7045   unsigned Opc;
7046   switch (DstTy.getSimpleVT().SimpleTy) {
7047   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7048   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7049   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7050   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7051   }
7052
7053   SDValue Chain = DAG.getEntryNode();
7054   SDValue Value = Op.getOperand(0);
7055   EVT TheVT = Op.getOperand(0).getValueType();
7056   if (isScalarFPTypeInSSEReg(TheVT)) {
7057     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7058     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7059                          MachinePointerInfo::getFixedStack(SSFI),
7060                          false, false, 0);
7061     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7062     SDValue Ops[] = {
7063       Chain, StackSlot, DAG.getValueType(TheVT)
7064     };
7065
7066     MachineMemOperand *MMO =
7067       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7068                               MachineMemOperand::MOLoad, MemSize, MemSize);
7069     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7070                                     DstTy, MMO);
7071     Chain = Value.getValue(1);
7072     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7073     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7074   }
7075
7076   MachineMemOperand *MMO =
7077     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7078                             MachineMemOperand::MOStore, MemSize, MemSize);
7079
7080   // Build the FP_TO_INT*_IN_MEM
7081   SDValue Ops[] = { Chain, Value, StackSlot };
7082   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7083                                          Ops, 3, DstTy, MMO);
7084
7085   return std::make_pair(FIST, StackSlot);
7086 }
7087
7088 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7089                                            SelectionDAG &DAG) const {
7090   if (Op.getValueType().isVector())
7091     return SDValue();
7092
7093   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7094   SDValue FIST = Vals.first, StackSlot = Vals.second;
7095   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7096   if (FIST.getNode() == 0) return Op;
7097
7098   // Load the result.
7099   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7100                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7101 }
7102
7103 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7104                                            SelectionDAG &DAG) const {
7105   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7106   SDValue FIST = Vals.first, StackSlot = Vals.second;
7107   assert(FIST.getNode() && "Unexpected failure");
7108
7109   // Load the result.
7110   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7111                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7112 }
7113
7114 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7115                                      SelectionDAG &DAG) const {
7116   LLVMContext *Context = DAG.getContext();
7117   DebugLoc dl = Op.getDebugLoc();
7118   EVT VT = Op.getValueType();
7119   EVT EltVT = VT;
7120   if (VT.isVector())
7121     EltVT = VT.getVectorElementType();
7122   std::vector<Constant*> CV;
7123   if (EltVT == MVT::f64) {
7124     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7125     CV.push_back(C);
7126     CV.push_back(C);
7127   } else {
7128     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7129     CV.push_back(C);
7130     CV.push_back(C);
7131     CV.push_back(C);
7132     CV.push_back(C);
7133   }
7134   Constant *C = ConstantVector::get(CV);
7135   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7136   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7137                              MachinePointerInfo::getConstantPool(),
7138                              false, false, 16);
7139   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7140 }
7141
7142 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7143   LLVMContext *Context = DAG.getContext();
7144   DebugLoc dl = Op.getDebugLoc();
7145   EVT VT = Op.getValueType();
7146   EVT EltVT = VT;
7147   if (VT.isVector())
7148     EltVT = VT.getVectorElementType();
7149   std::vector<Constant*> CV;
7150   if (EltVT == MVT::f64) {
7151     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7152     CV.push_back(C);
7153     CV.push_back(C);
7154   } else {
7155     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7156     CV.push_back(C);
7157     CV.push_back(C);
7158     CV.push_back(C);
7159     CV.push_back(C);
7160   }
7161   Constant *C = ConstantVector::get(CV);
7162   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7163   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7164                              MachinePointerInfo::getConstantPool(),
7165                              false, false, 16);
7166   if (VT.isVector()) {
7167     return DAG.getNode(ISD::BITCAST, dl, VT,
7168                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7169                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7170                                 Op.getOperand(0)),
7171                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7172   } else {
7173     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7174   }
7175 }
7176
7177 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7178   LLVMContext *Context = DAG.getContext();
7179   SDValue Op0 = Op.getOperand(0);
7180   SDValue Op1 = Op.getOperand(1);
7181   DebugLoc dl = Op.getDebugLoc();
7182   EVT VT = Op.getValueType();
7183   EVT SrcVT = Op1.getValueType();
7184
7185   // If second operand is smaller, extend it first.
7186   if (SrcVT.bitsLT(VT)) {
7187     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7188     SrcVT = VT;
7189   }
7190   // And if it is bigger, shrink it first.
7191   if (SrcVT.bitsGT(VT)) {
7192     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7193     SrcVT = VT;
7194   }
7195
7196   // At this point the operands and the result should have the same
7197   // type, and that won't be f80 since that is not custom lowered.
7198
7199   // First get the sign bit of second operand.
7200   std::vector<Constant*> CV;
7201   if (SrcVT == MVT::f64) {
7202     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7203     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7204   } else {
7205     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7206     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7207     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7208     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7209   }
7210   Constant *C = ConstantVector::get(CV);
7211   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7212   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7213                               MachinePointerInfo::getConstantPool(),
7214                               false, false, 16);
7215   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7216
7217   // Shift sign bit right or left if the two operands have different types.
7218   if (SrcVT.bitsGT(VT)) {
7219     // Op0 is MVT::f32, Op1 is MVT::f64.
7220     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7221     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7222                           DAG.getConstant(32, MVT::i32));
7223     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7224     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7225                           DAG.getIntPtrConstant(0));
7226   }
7227
7228   // Clear first operand sign bit.
7229   CV.clear();
7230   if (VT == MVT::f64) {
7231     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7232     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7233   } else {
7234     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7235     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7236     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7237     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7238   }
7239   C = ConstantVector::get(CV);
7240   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7241   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7242                               MachinePointerInfo::getConstantPool(),
7243                               false, false, 16);
7244   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7245
7246   // Or the value with the sign bit.
7247   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7248 }
7249
7250 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7251   SDValue N0 = Op.getOperand(0);
7252   DebugLoc dl = Op.getDebugLoc();
7253   EVT VT = Op.getValueType();
7254
7255   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7256   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7257                                   DAG.getConstant(1, VT));
7258   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7259 }
7260
7261 /// Emit nodes that will be selected as "test Op0,Op0", or something
7262 /// equivalent.
7263 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7264                                     SelectionDAG &DAG) const {
7265   DebugLoc dl = Op.getDebugLoc();
7266
7267   // CF and OF aren't always set the way we want. Determine which
7268   // of these we need.
7269   bool NeedCF = false;
7270   bool NeedOF = false;
7271   switch (X86CC) {
7272   default: break;
7273   case X86::COND_A: case X86::COND_AE:
7274   case X86::COND_B: case X86::COND_BE:
7275     NeedCF = true;
7276     break;
7277   case X86::COND_G: case X86::COND_GE:
7278   case X86::COND_L: case X86::COND_LE:
7279   case X86::COND_O: case X86::COND_NO:
7280     NeedOF = true;
7281     break;
7282   }
7283
7284   // See if we can use the EFLAGS value from the operand instead of
7285   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7286   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7287   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7288     // Emit a CMP with 0, which is the TEST pattern.
7289     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7290                        DAG.getConstant(0, Op.getValueType()));
7291
7292   unsigned Opcode = 0;
7293   unsigned NumOperands = 0;
7294   switch (Op.getNode()->getOpcode()) {
7295   case ISD::ADD:
7296     // Due to an isel shortcoming, be conservative if this add is likely to be
7297     // selected as part of a load-modify-store instruction. When the root node
7298     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7299     // uses of other nodes in the match, such as the ADD in this case. This
7300     // leads to the ADD being left around and reselected, with the result being
7301     // two adds in the output.  Alas, even if none our users are stores, that
7302     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7303     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7304     // climbing the DAG back to the root, and it doesn't seem to be worth the
7305     // effort.
7306     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7307            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7308       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7309         goto default_case;
7310
7311     if (ConstantSDNode *C =
7312         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7313       // An add of one will be selected as an INC.
7314       if (C->getAPIntValue() == 1) {
7315         Opcode = X86ISD::INC;
7316         NumOperands = 1;
7317         break;
7318       }
7319
7320       // An add of negative one (subtract of one) will be selected as a DEC.
7321       if (C->getAPIntValue().isAllOnesValue()) {
7322         Opcode = X86ISD::DEC;
7323         NumOperands = 1;
7324         break;
7325       }
7326     }
7327
7328     // Otherwise use a regular EFLAGS-setting add.
7329     Opcode = X86ISD::ADD;
7330     NumOperands = 2;
7331     break;
7332   case ISD::AND: {
7333     // If the primary and result isn't used, don't bother using X86ISD::AND,
7334     // because a TEST instruction will be better.
7335     bool NonFlagUse = false;
7336     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7337            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7338       SDNode *User = *UI;
7339       unsigned UOpNo = UI.getOperandNo();
7340       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7341         // Look pass truncate.
7342         UOpNo = User->use_begin().getOperandNo();
7343         User = *User->use_begin();
7344       }
7345
7346       if (User->getOpcode() != ISD::BRCOND &&
7347           User->getOpcode() != ISD::SETCC &&
7348           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7349         NonFlagUse = true;
7350         break;
7351       }
7352     }
7353
7354     if (!NonFlagUse)
7355       break;
7356   }
7357     // FALL THROUGH
7358   case ISD::SUB:
7359   case ISD::OR:
7360   case ISD::XOR:
7361     // Due to the ISEL shortcoming noted above, be conservative if this op is
7362     // likely to be selected as part of a load-modify-store instruction.
7363     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7364            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7365       if (UI->getOpcode() == ISD::STORE)
7366         goto default_case;
7367
7368     // Otherwise use a regular EFLAGS-setting instruction.
7369     switch (Op.getNode()->getOpcode()) {
7370     default: llvm_unreachable("unexpected operator!");
7371     case ISD::SUB: Opcode = X86ISD::SUB; break;
7372     case ISD::OR:  Opcode = X86ISD::OR;  break;
7373     case ISD::XOR: Opcode = X86ISD::XOR; break;
7374     case ISD::AND: Opcode = X86ISD::AND; break;
7375     }
7376
7377     NumOperands = 2;
7378     break;
7379   case X86ISD::ADD:
7380   case X86ISD::SUB:
7381   case X86ISD::INC:
7382   case X86ISD::DEC:
7383   case X86ISD::OR:
7384   case X86ISD::XOR:
7385   case X86ISD::AND:
7386     return SDValue(Op.getNode(), 1);
7387   default:
7388   default_case:
7389     break;
7390   }
7391
7392   if (Opcode == 0)
7393     // Emit a CMP with 0, which is the TEST pattern.
7394     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7395                        DAG.getConstant(0, Op.getValueType()));
7396
7397   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7398   SmallVector<SDValue, 4> Ops;
7399   for (unsigned i = 0; i != NumOperands; ++i)
7400     Ops.push_back(Op.getOperand(i));
7401
7402   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7403   DAG.ReplaceAllUsesWith(Op, New);
7404   return SDValue(New.getNode(), 1);
7405 }
7406
7407 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7408 /// equivalent.
7409 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7410                                    SelectionDAG &DAG) const {
7411   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7412     if (C->getAPIntValue() == 0)
7413       return EmitTest(Op0, X86CC, DAG);
7414
7415   DebugLoc dl = Op0.getDebugLoc();
7416   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7417 }
7418
7419 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7420 /// if it's possible.
7421 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7422                                      DebugLoc dl, SelectionDAG &DAG) const {
7423   SDValue Op0 = And.getOperand(0);
7424   SDValue Op1 = And.getOperand(1);
7425   if (Op0.getOpcode() == ISD::TRUNCATE)
7426     Op0 = Op0.getOperand(0);
7427   if (Op1.getOpcode() == ISD::TRUNCATE)
7428     Op1 = Op1.getOperand(0);
7429
7430   SDValue LHS, RHS;
7431   if (Op1.getOpcode() == ISD::SHL)
7432     std::swap(Op0, Op1);
7433   if (Op0.getOpcode() == ISD::SHL) {
7434     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7435       if (And00C->getZExtValue() == 1) {
7436         // If we looked past a truncate, check that it's only truncating away
7437         // known zeros.
7438         unsigned BitWidth = Op0.getValueSizeInBits();
7439         unsigned AndBitWidth = And.getValueSizeInBits();
7440         if (BitWidth > AndBitWidth) {
7441           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7442           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7443           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7444             return SDValue();
7445         }
7446         LHS = Op1;
7447         RHS = Op0.getOperand(1);
7448       }
7449   } else if (Op1.getOpcode() == ISD::Constant) {
7450     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7451     SDValue AndLHS = Op0;
7452     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7453       LHS = AndLHS.getOperand(0);
7454       RHS = AndLHS.getOperand(1);
7455     }
7456   }
7457
7458   if (LHS.getNode()) {
7459     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7460     // instruction.  Since the shift amount is in-range-or-undefined, we know
7461     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7462     // the encoding for the i16 version is larger than the i32 version.
7463     // Also promote i16 to i32 for performance / code size reason.
7464     if (LHS.getValueType() == MVT::i8 ||
7465         LHS.getValueType() == MVT::i16)
7466       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7467
7468     // If the operand types disagree, extend the shift amount to match.  Since
7469     // BT ignores high bits (like shifts) we can use anyextend.
7470     if (LHS.getValueType() != RHS.getValueType())
7471       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7472
7473     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7474     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7475     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7476                        DAG.getConstant(Cond, MVT::i8), BT);
7477   }
7478
7479   return SDValue();
7480 }
7481
7482 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7483   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7484   SDValue Op0 = Op.getOperand(0);
7485   SDValue Op1 = Op.getOperand(1);
7486   DebugLoc dl = Op.getDebugLoc();
7487   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7488
7489   // Optimize to BT if possible.
7490   // Lower (X & (1 << N)) == 0 to BT(X, N).
7491   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7492   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7493   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7494       Op1.getOpcode() == ISD::Constant &&
7495       cast<ConstantSDNode>(Op1)->isNullValue() &&
7496       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7497     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7498     if (NewSetCC.getNode())
7499       return NewSetCC;
7500   }
7501
7502   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7503   // these.
7504   if (Op1.getOpcode() == ISD::Constant &&
7505       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7506        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7507       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7508
7509     // If the input is a setcc, then reuse the input setcc or use a new one with
7510     // the inverted condition.
7511     if (Op0.getOpcode() == X86ISD::SETCC) {
7512       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7513       bool Invert = (CC == ISD::SETNE) ^
7514         cast<ConstantSDNode>(Op1)->isNullValue();
7515       if (!Invert) return Op0;
7516
7517       CCode = X86::GetOppositeBranchCondition(CCode);
7518       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7519                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7520     }
7521   }
7522
7523   bool isFP = Op1.getValueType().isFloatingPoint();
7524   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7525   if (X86CC == X86::COND_INVALID)
7526     return SDValue();
7527
7528   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7529   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7530                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7531 }
7532
7533 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7534   SDValue Cond;
7535   SDValue Op0 = Op.getOperand(0);
7536   SDValue Op1 = Op.getOperand(1);
7537   SDValue CC = Op.getOperand(2);
7538   EVT VT = Op.getValueType();
7539   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7540   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7541   DebugLoc dl = Op.getDebugLoc();
7542
7543   if (isFP) {
7544     unsigned SSECC = 8;
7545     EVT VT0 = Op0.getValueType();
7546     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7547     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7548     bool Swap = false;
7549
7550     switch (SetCCOpcode) {
7551     default: break;
7552     case ISD::SETOEQ:
7553     case ISD::SETEQ:  SSECC = 0; break;
7554     case ISD::SETOGT:
7555     case ISD::SETGT: Swap = true; // Fallthrough
7556     case ISD::SETLT:
7557     case ISD::SETOLT: SSECC = 1; break;
7558     case ISD::SETOGE:
7559     case ISD::SETGE: Swap = true; // Fallthrough
7560     case ISD::SETLE:
7561     case ISD::SETOLE: SSECC = 2; break;
7562     case ISD::SETUO:  SSECC = 3; break;
7563     case ISD::SETUNE:
7564     case ISD::SETNE:  SSECC = 4; break;
7565     case ISD::SETULE: Swap = true;
7566     case ISD::SETUGE: SSECC = 5; break;
7567     case ISD::SETULT: Swap = true;
7568     case ISD::SETUGT: SSECC = 6; break;
7569     case ISD::SETO:   SSECC = 7; break;
7570     }
7571     if (Swap)
7572       std::swap(Op0, Op1);
7573
7574     // In the two special cases we can't handle, emit two comparisons.
7575     if (SSECC == 8) {
7576       if (SetCCOpcode == ISD::SETUEQ) {
7577         SDValue UNORD, EQ;
7578         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7579         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7580         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7581       }
7582       else if (SetCCOpcode == ISD::SETONE) {
7583         SDValue ORD, NEQ;
7584         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7585         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7586         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7587       }
7588       llvm_unreachable("Illegal FP comparison");
7589     }
7590     // Handle all other FP comparisons here.
7591     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7592   }
7593
7594   // We are handling one of the integer comparisons here.  Since SSE only has
7595   // GT and EQ comparisons for integer, swapping operands and multiple
7596   // operations may be required for some comparisons.
7597   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7598   bool Swap = false, Invert = false, FlipSigns = false;
7599
7600   switch (VT.getSimpleVT().SimpleTy) {
7601   default: break;
7602   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7603   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7604   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7605   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7606   }
7607
7608   switch (SetCCOpcode) {
7609   default: break;
7610   case ISD::SETNE:  Invert = true;
7611   case ISD::SETEQ:  Opc = EQOpc; break;
7612   case ISD::SETLT:  Swap = true;
7613   case ISD::SETGT:  Opc = GTOpc; break;
7614   case ISD::SETGE:  Swap = true;
7615   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7616   case ISD::SETULT: Swap = true;
7617   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7618   case ISD::SETUGE: Swap = true;
7619   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7620   }
7621   if (Swap)
7622     std::swap(Op0, Op1);
7623
7624   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7625   // bits of the inputs before performing those operations.
7626   if (FlipSigns) {
7627     EVT EltVT = VT.getVectorElementType();
7628     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7629                                       EltVT);
7630     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7631     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7632                                     SignBits.size());
7633     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7634     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7635   }
7636
7637   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7638
7639   // If the logical-not of the result is required, perform that now.
7640   if (Invert)
7641     Result = DAG.getNOT(dl, Result, VT);
7642
7643   return Result;
7644 }
7645
7646 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7647 static bool isX86LogicalCmp(SDValue Op) {
7648   unsigned Opc = Op.getNode()->getOpcode();
7649   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7650     return true;
7651   if (Op.getResNo() == 1 &&
7652       (Opc == X86ISD::ADD ||
7653        Opc == X86ISD::SUB ||
7654        Opc == X86ISD::ADC ||
7655        Opc == X86ISD::SBB ||
7656        Opc == X86ISD::SMUL ||
7657        Opc == X86ISD::UMUL ||
7658        Opc == X86ISD::INC ||
7659        Opc == X86ISD::DEC ||
7660        Opc == X86ISD::OR ||
7661        Opc == X86ISD::XOR ||
7662        Opc == X86ISD::AND))
7663     return true;
7664
7665   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7666     return true;
7667
7668   return false;
7669 }
7670
7671 static bool isZero(SDValue V) {
7672   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7673   return C && C->isNullValue();
7674 }
7675
7676 static bool isAllOnes(SDValue V) {
7677   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7678   return C && C->isAllOnesValue();
7679 }
7680
7681 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7682   bool addTest = true;
7683   SDValue Cond  = Op.getOperand(0);
7684   SDValue Op1 = Op.getOperand(1);
7685   SDValue Op2 = Op.getOperand(2);
7686   DebugLoc DL = Op.getDebugLoc();
7687   SDValue CC;
7688
7689   if (Cond.getOpcode() == ISD::SETCC) {
7690     SDValue NewCond = LowerSETCC(Cond, DAG);
7691     if (NewCond.getNode())
7692       Cond = NewCond;
7693   }
7694
7695   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7696   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7697   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7698   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7699   if (Cond.getOpcode() == X86ISD::SETCC &&
7700       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7701       isZero(Cond.getOperand(1).getOperand(1))) {
7702     SDValue Cmp = Cond.getOperand(1);
7703
7704     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7705
7706     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7707         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7708       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7709
7710       SDValue CmpOp0 = Cmp.getOperand(0);
7711       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7712                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7713
7714       SDValue Res =   // Res = 0 or -1.
7715         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7716                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7717
7718       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7719         Res = DAG.getNOT(DL, Res, Res.getValueType());
7720
7721       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7722       if (N2C == 0 || !N2C->isNullValue())
7723         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7724       return Res;
7725     }
7726   }
7727
7728   // Look past (and (setcc_carry (cmp ...)), 1).
7729   if (Cond.getOpcode() == ISD::AND &&
7730       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7731     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7732     if (C && C->getAPIntValue() == 1)
7733       Cond = Cond.getOperand(0);
7734   }
7735
7736   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7737   // setting operand in place of the X86ISD::SETCC.
7738   if (Cond.getOpcode() == X86ISD::SETCC ||
7739       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7740     CC = Cond.getOperand(0);
7741
7742     SDValue Cmp = Cond.getOperand(1);
7743     unsigned Opc = Cmp.getOpcode();
7744     EVT VT = Op.getValueType();
7745
7746     bool IllegalFPCMov = false;
7747     if (VT.isFloatingPoint() && !VT.isVector() &&
7748         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7749       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7750
7751     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7752         Opc == X86ISD::BT) { // FIXME
7753       Cond = Cmp;
7754       addTest = false;
7755     }
7756   }
7757
7758   if (addTest) {
7759     // Look pass the truncate.
7760     if (Cond.getOpcode() == ISD::TRUNCATE)
7761       Cond = Cond.getOperand(0);
7762
7763     // We know the result of AND is compared against zero. Try to match
7764     // it to BT.
7765     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7766       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7767       if (NewSetCC.getNode()) {
7768         CC = NewSetCC.getOperand(0);
7769         Cond = NewSetCC.getOperand(1);
7770         addTest = false;
7771       }
7772     }
7773   }
7774
7775   if (addTest) {
7776     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7777     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7778   }
7779
7780   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7781   // a <  b ?  0 : -1 -> RES = setcc_carry
7782   // a >= b ? -1 :  0 -> RES = setcc_carry
7783   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7784   if (Cond.getOpcode() == X86ISD::CMP) {
7785     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7786
7787     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7788         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7789       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7790                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7791       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7792         return DAG.getNOT(DL, Res, Res.getValueType());
7793       return Res;
7794     }
7795   }
7796
7797   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7798   // condition is true.
7799   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7800   SDValue Ops[] = { Op2, Op1, CC, Cond };
7801   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7802 }
7803
7804 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7805 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7806 // from the AND / OR.
7807 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7808   Opc = Op.getOpcode();
7809   if (Opc != ISD::OR && Opc != ISD::AND)
7810     return false;
7811   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7812           Op.getOperand(0).hasOneUse() &&
7813           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7814           Op.getOperand(1).hasOneUse());
7815 }
7816
7817 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7818 // 1 and that the SETCC node has a single use.
7819 static bool isXor1OfSetCC(SDValue Op) {
7820   if (Op.getOpcode() != ISD::XOR)
7821     return false;
7822   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7823   if (N1C && N1C->getAPIntValue() == 1) {
7824     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7825       Op.getOperand(0).hasOneUse();
7826   }
7827   return false;
7828 }
7829
7830 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7831   bool addTest = true;
7832   SDValue Chain = Op.getOperand(0);
7833   SDValue Cond  = Op.getOperand(1);
7834   SDValue Dest  = Op.getOperand(2);
7835   DebugLoc dl = Op.getDebugLoc();
7836   SDValue CC;
7837
7838   if (Cond.getOpcode() == ISD::SETCC) {
7839     SDValue NewCond = LowerSETCC(Cond, DAG);
7840     if (NewCond.getNode())
7841       Cond = NewCond;
7842   }
7843 #if 0
7844   // FIXME: LowerXALUO doesn't handle these!!
7845   else if (Cond.getOpcode() == X86ISD::ADD  ||
7846            Cond.getOpcode() == X86ISD::SUB  ||
7847            Cond.getOpcode() == X86ISD::SMUL ||
7848            Cond.getOpcode() == X86ISD::UMUL)
7849     Cond = LowerXALUO(Cond, DAG);
7850 #endif
7851
7852   // Look pass (and (setcc_carry (cmp ...)), 1).
7853   if (Cond.getOpcode() == ISD::AND &&
7854       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7855     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7856     if (C && C->getAPIntValue() == 1)
7857       Cond = Cond.getOperand(0);
7858   }
7859
7860   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7861   // setting operand in place of the X86ISD::SETCC.
7862   if (Cond.getOpcode() == X86ISD::SETCC ||
7863       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7864     CC = Cond.getOperand(0);
7865
7866     SDValue Cmp = Cond.getOperand(1);
7867     unsigned Opc = Cmp.getOpcode();
7868     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7869     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7870       Cond = Cmp;
7871       addTest = false;
7872     } else {
7873       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7874       default: break;
7875       case X86::COND_O:
7876       case X86::COND_B:
7877         // These can only come from an arithmetic instruction with overflow,
7878         // e.g. SADDO, UADDO.
7879         Cond = Cond.getNode()->getOperand(1);
7880         addTest = false;
7881         break;
7882       }
7883     }
7884   } else {
7885     unsigned CondOpc;
7886     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7887       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7888       if (CondOpc == ISD::OR) {
7889         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7890         // two branches instead of an explicit OR instruction with a
7891         // separate test.
7892         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7893             isX86LogicalCmp(Cmp)) {
7894           CC = Cond.getOperand(0).getOperand(0);
7895           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7896                               Chain, Dest, CC, Cmp);
7897           CC = Cond.getOperand(1).getOperand(0);
7898           Cond = Cmp;
7899           addTest = false;
7900         }
7901       } else { // ISD::AND
7902         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7903         // two branches instead of an explicit AND instruction with a
7904         // separate test. However, we only do this if this block doesn't
7905         // have a fall-through edge, because this requires an explicit
7906         // jmp when the condition is false.
7907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7908             isX86LogicalCmp(Cmp) &&
7909             Op.getNode()->hasOneUse()) {
7910           X86::CondCode CCode =
7911             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7912           CCode = X86::GetOppositeBranchCondition(CCode);
7913           CC = DAG.getConstant(CCode, MVT::i8);
7914           SDNode *User = *Op.getNode()->use_begin();
7915           // Look for an unconditional branch following this conditional branch.
7916           // We need this because we need to reverse the successors in order
7917           // to implement FCMP_OEQ.
7918           if (User->getOpcode() == ISD::BR) {
7919             SDValue FalseBB = User->getOperand(1);
7920             SDNode *NewBR =
7921               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7922             assert(NewBR == User);
7923             (void)NewBR;
7924             Dest = FalseBB;
7925
7926             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7927                                 Chain, Dest, CC, Cmp);
7928             X86::CondCode CCode =
7929               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7930             CCode = X86::GetOppositeBranchCondition(CCode);
7931             CC = DAG.getConstant(CCode, MVT::i8);
7932             Cond = Cmp;
7933             addTest = false;
7934           }
7935         }
7936       }
7937     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7938       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7939       // It should be transformed during dag combiner except when the condition
7940       // is set by a arithmetics with overflow node.
7941       X86::CondCode CCode =
7942         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7943       CCode = X86::GetOppositeBranchCondition(CCode);
7944       CC = DAG.getConstant(CCode, MVT::i8);
7945       Cond = Cond.getOperand(0).getOperand(1);
7946       addTest = false;
7947     }
7948   }
7949
7950   if (addTest) {
7951     // Look pass the truncate.
7952     if (Cond.getOpcode() == ISD::TRUNCATE)
7953       Cond = Cond.getOperand(0);
7954
7955     // We know the result of AND is compared against zero. Try to match
7956     // it to BT.
7957     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7958       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7959       if (NewSetCC.getNode()) {
7960         CC = NewSetCC.getOperand(0);
7961         Cond = NewSetCC.getOperand(1);
7962         addTest = false;
7963       }
7964     }
7965   }
7966
7967   if (addTest) {
7968     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7969     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7970   }
7971   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7972                      Chain, Dest, CC, Cond);
7973 }
7974
7975
7976 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7977 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7978 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7979 // that the guard pages used by the OS virtual memory manager are allocated in
7980 // correct sequence.
7981 SDValue
7982 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7983                                            SelectionDAG &DAG) const {
7984   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7985          "This should be used only on Windows targets");
7986   assert(!Subtarget->isTargetEnvMacho());
7987   DebugLoc dl = Op.getDebugLoc();
7988
7989   // Get the inputs.
7990   SDValue Chain = Op.getOperand(0);
7991   SDValue Size  = Op.getOperand(1);
7992   // FIXME: Ensure alignment here
7993
7994   SDValue Flag;
7995
7996   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7997   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7998
7999   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8000   Flag = Chain.getValue(1);
8001
8002   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8003
8004   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8005   Flag = Chain.getValue(1);
8006
8007   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8008
8009   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8010   return DAG.getMergeValues(Ops1, 2, dl);
8011 }
8012
8013 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8014   MachineFunction &MF = DAG.getMachineFunction();
8015   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8016
8017   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8018   DebugLoc DL = Op.getDebugLoc();
8019
8020   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8021     // vastart just stores the address of the VarArgsFrameIndex slot into the
8022     // memory location argument.
8023     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8024                                    getPointerTy());
8025     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8026                         MachinePointerInfo(SV), false, false, 0);
8027   }
8028
8029   // __va_list_tag:
8030   //   gp_offset         (0 - 6 * 8)
8031   //   fp_offset         (48 - 48 + 8 * 16)
8032   //   overflow_arg_area (point to parameters coming in memory).
8033   //   reg_save_area
8034   SmallVector<SDValue, 8> MemOps;
8035   SDValue FIN = Op.getOperand(1);
8036   // Store gp_offset
8037   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8038                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8039                                                MVT::i32),
8040                                FIN, MachinePointerInfo(SV), false, false, 0);
8041   MemOps.push_back(Store);
8042
8043   // Store fp_offset
8044   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8045                     FIN, DAG.getIntPtrConstant(4));
8046   Store = DAG.getStore(Op.getOperand(0), DL,
8047                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8048                                        MVT::i32),
8049                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8050   MemOps.push_back(Store);
8051
8052   // Store ptr to overflow_arg_area
8053   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8054                     FIN, DAG.getIntPtrConstant(4));
8055   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8056                                     getPointerTy());
8057   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8058                        MachinePointerInfo(SV, 8),
8059                        false, false, 0);
8060   MemOps.push_back(Store);
8061
8062   // Store ptr to reg_save_area.
8063   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8064                     FIN, DAG.getIntPtrConstant(8));
8065   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8066                                     getPointerTy());
8067   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8068                        MachinePointerInfo(SV, 16), false, false, 0);
8069   MemOps.push_back(Store);
8070   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8071                      &MemOps[0], MemOps.size());
8072 }
8073
8074 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8075   assert(Subtarget->is64Bit() &&
8076          "LowerVAARG only handles 64-bit va_arg!");
8077   assert((Subtarget->isTargetLinux() ||
8078           Subtarget->isTargetDarwin()) &&
8079           "Unhandled target in LowerVAARG");
8080   assert(Op.getNode()->getNumOperands() == 4);
8081   SDValue Chain = Op.getOperand(0);
8082   SDValue SrcPtr = Op.getOperand(1);
8083   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8084   unsigned Align = Op.getConstantOperandVal(3);
8085   DebugLoc dl = Op.getDebugLoc();
8086
8087   EVT ArgVT = Op.getNode()->getValueType(0);
8088   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8089   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8090   uint8_t ArgMode;
8091
8092   // Decide which area this value should be read from.
8093   // TODO: Implement the AMD64 ABI in its entirety. This simple
8094   // selection mechanism works only for the basic types.
8095   if (ArgVT == MVT::f80) {
8096     llvm_unreachable("va_arg for f80 not yet implemented");
8097   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8098     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8099   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8100     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8101   } else {
8102     llvm_unreachable("Unhandled argument type in LowerVAARG");
8103   }
8104
8105   if (ArgMode == 2) {
8106     // Sanity Check: Make sure using fp_offset makes sense.
8107     assert(!UseSoftFloat &&
8108            !(DAG.getMachineFunction()
8109                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8110            Subtarget->hasXMM());
8111   }
8112
8113   // Insert VAARG_64 node into the DAG
8114   // VAARG_64 returns two values: Variable Argument Address, Chain
8115   SmallVector<SDValue, 11> InstOps;
8116   InstOps.push_back(Chain);
8117   InstOps.push_back(SrcPtr);
8118   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8119   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8120   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8121   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8122   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8123                                           VTs, &InstOps[0], InstOps.size(),
8124                                           MVT::i64,
8125                                           MachinePointerInfo(SV),
8126                                           /*Align=*/0,
8127                                           /*Volatile=*/false,
8128                                           /*ReadMem=*/true,
8129                                           /*WriteMem=*/true);
8130   Chain = VAARG.getValue(1);
8131
8132   // Load the next argument and return it
8133   return DAG.getLoad(ArgVT, dl,
8134                      Chain,
8135                      VAARG,
8136                      MachinePointerInfo(),
8137                      false, false, 0);
8138 }
8139
8140 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8141   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8142   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8143   SDValue Chain = Op.getOperand(0);
8144   SDValue DstPtr = Op.getOperand(1);
8145   SDValue SrcPtr = Op.getOperand(2);
8146   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8147   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8148   DebugLoc DL = Op.getDebugLoc();
8149
8150   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8151                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8152                        false,
8153                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8154 }
8155
8156 SDValue
8157 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8158   DebugLoc dl = Op.getDebugLoc();
8159   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8160   switch (IntNo) {
8161   default: return SDValue();    // Don't custom lower most intrinsics.
8162   // Comparison intrinsics.
8163   case Intrinsic::x86_sse_comieq_ss:
8164   case Intrinsic::x86_sse_comilt_ss:
8165   case Intrinsic::x86_sse_comile_ss:
8166   case Intrinsic::x86_sse_comigt_ss:
8167   case Intrinsic::x86_sse_comige_ss:
8168   case Intrinsic::x86_sse_comineq_ss:
8169   case Intrinsic::x86_sse_ucomieq_ss:
8170   case Intrinsic::x86_sse_ucomilt_ss:
8171   case Intrinsic::x86_sse_ucomile_ss:
8172   case Intrinsic::x86_sse_ucomigt_ss:
8173   case Intrinsic::x86_sse_ucomige_ss:
8174   case Intrinsic::x86_sse_ucomineq_ss:
8175   case Intrinsic::x86_sse2_comieq_sd:
8176   case Intrinsic::x86_sse2_comilt_sd:
8177   case Intrinsic::x86_sse2_comile_sd:
8178   case Intrinsic::x86_sse2_comigt_sd:
8179   case Intrinsic::x86_sse2_comige_sd:
8180   case Intrinsic::x86_sse2_comineq_sd:
8181   case Intrinsic::x86_sse2_ucomieq_sd:
8182   case Intrinsic::x86_sse2_ucomilt_sd:
8183   case Intrinsic::x86_sse2_ucomile_sd:
8184   case Intrinsic::x86_sse2_ucomigt_sd:
8185   case Intrinsic::x86_sse2_ucomige_sd:
8186   case Intrinsic::x86_sse2_ucomineq_sd: {
8187     unsigned Opc = 0;
8188     ISD::CondCode CC = ISD::SETCC_INVALID;
8189     switch (IntNo) {
8190     default: break;
8191     case Intrinsic::x86_sse_comieq_ss:
8192     case Intrinsic::x86_sse2_comieq_sd:
8193       Opc = X86ISD::COMI;
8194       CC = ISD::SETEQ;
8195       break;
8196     case Intrinsic::x86_sse_comilt_ss:
8197     case Intrinsic::x86_sse2_comilt_sd:
8198       Opc = X86ISD::COMI;
8199       CC = ISD::SETLT;
8200       break;
8201     case Intrinsic::x86_sse_comile_ss:
8202     case Intrinsic::x86_sse2_comile_sd:
8203       Opc = X86ISD::COMI;
8204       CC = ISD::SETLE;
8205       break;
8206     case Intrinsic::x86_sse_comigt_ss:
8207     case Intrinsic::x86_sse2_comigt_sd:
8208       Opc = X86ISD::COMI;
8209       CC = ISD::SETGT;
8210       break;
8211     case Intrinsic::x86_sse_comige_ss:
8212     case Intrinsic::x86_sse2_comige_sd:
8213       Opc = X86ISD::COMI;
8214       CC = ISD::SETGE;
8215       break;
8216     case Intrinsic::x86_sse_comineq_ss:
8217     case Intrinsic::x86_sse2_comineq_sd:
8218       Opc = X86ISD::COMI;
8219       CC = ISD::SETNE;
8220       break;
8221     case Intrinsic::x86_sse_ucomieq_ss:
8222     case Intrinsic::x86_sse2_ucomieq_sd:
8223       Opc = X86ISD::UCOMI;
8224       CC = ISD::SETEQ;
8225       break;
8226     case Intrinsic::x86_sse_ucomilt_ss:
8227     case Intrinsic::x86_sse2_ucomilt_sd:
8228       Opc = X86ISD::UCOMI;
8229       CC = ISD::SETLT;
8230       break;
8231     case Intrinsic::x86_sse_ucomile_ss:
8232     case Intrinsic::x86_sse2_ucomile_sd:
8233       Opc = X86ISD::UCOMI;
8234       CC = ISD::SETLE;
8235       break;
8236     case Intrinsic::x86_sse_ucomigt_ss:
8237     case Intrinsic::x86_sse2_ucomigt_sd:
8238       Opc = X86ISD::UCOMI;
8239       CC = ISD::SETGT;
8240       break;
8241     case Intrinsic::x86_sse_ucomige_ss:
8242     case Intrinsic::x86_sse2_ucomige_sd:
8243       Opc = X86ISD::UCOMI;
8244       CC = ISD::SETGE;
8245       break;
8246     case Intrinsic::x86_sse_ucomineq_ss:
8247     case Intrinsic::x86_sse2_ucomineq_sd:
8248       Opc = X86ISD::UCOMI;
8249       CC = ISD::SETNE;
8250       break;
8251     }
8252
8253     SDValue LHS = Op.getOperand(1);
8254     SDValue RHS = Op.getOperand(2);
8255     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8256     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8257     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8258     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8259                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8260     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8261   }
8262   // ptest and testp intrinsics. The intrinsic these come from are designed to
8263   // return an integer value, not just an instruction so lower it to the ptest
8264   // or testp pattern and a setcc for the result.
8265   case Intrinsic::x86_sse41_ptestz:
8266   case Intrinsic::x86_sse41_ptestc:
8267   case Intrinsic::x86_sse41_ptestnzc:
8268   case Intrinsic::x86_avx_ptestz_256:
8269   case Intrinsic::x86_avx_ptestc_256:
8270   case Intrinsic::x86_avx_ptestnzc_256:
8271   case Intrinsic::x86_avx_vtestz_ps:
8272   case Intrinsic::x86_avx_vtestc_ps:
8273   case Intrinsic::x86_avx_vtestnzc_ps:
8274   case Intrinsic::x86_avx_vtestz_pd:
8275   case Intrinsic::x86_avx_vtestc_pd:
8276   case Intrinsic::x86_avx_vtestnzc_pd:
8277   case Intrinsic::x86_avx_vtestz_ps_256:
8278   case Intrinsic::x86_avx_vtestc_ps_256:
8279   case Intrinsic::x86_avx_vtestnzc_ps_256:
8280   case Intrinsic::x86_avx_vtestz_pd_256:
8281   case Intrinsic::x86_avx_vtestc_pd_256:
8282   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8283     bool IsTestPacked = false;
8284     unsigned X86CC = 0;
8285     switch (IntNo) {
8286     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8287     case Intrinsic::x86_avx_vtestz_ps:
8288     case Intrinsic::x86_avx_vtestz_pd:
8289     case Intrinsic::x86_avx_vtestz_ps_256:
8290     case Intrinsic::x86_avx_vtestz_pd_256:
8291       IsTestPacked = true; // Fallthrough
8292     case Intrinsic::x86_sse41_ptestz:
8293     case Intrinsic::x86_avx_ptestz_256:
8294       // ZF = 1
8295       X86CC = X86::COND_E;
8296       break;
8297     case Intrinsic::x86_avx_vtestc_ps:
8298     case Intrinsic::x86_avx_vtestc_pd:
8299     case Intrinsic::x86_avx_vtestc_ps_256:
8300     case Intrinsic::x86_avx_vtestc_pd_256:
8301       IsTestPacked = true; // Fallthrough
8302     case Intrinsic::x86_sse41_ptestc:
8303     case Intrinsic::x86_avx_ptestc_256:
8304       // CF = 1
8305       X86CC = X86::COND_B;
8306       break;
8307     case Intrinsic::x86_avx_vtestnzc_ps:
8308     case Intrinsic::x86_avx_vtestnzc_pd:
8309     case Intrinsic::x86_avx_vtestnzc_ps_256:
8310     case Intrinsic::x86_avx_vtestnzc_pd_256:
8311       IsTestPacked = true; // Fallthrough
8312     case Intrinsic::x86_sse41_ptestnzc:
8313     case Intrinsic::x86_avx_ptestnzc_256:
8314       // ZF and CF = 0
8315       X86CC = X86::COND_A;
8316       break;
8317     }
8318
8319     SDValue LHS = Op.getOperand(1);
8320     SDValue RHS = Op.getOperand(2);
8321     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8322     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8323     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8324     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8325     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8326   }
8327
8328   // Fix vector shift instructions where the last operand is a non-immediate
8329   // i32 value.
8330   case Intrinsic::x86_sse2_pslli_w:
8331   case Intrinsic::x86_sse2_pslli_d:
8332   case Intrinsic::x86_sse2_pslli_q:
8333   case Intrinsic::x86_sse2_psrli_w:
8334   case Intrinsic::x86_sse2_psrli_d:
8335   case Intrinsic::x86_sse2_psrli_q:
8336   case Intrinsic::x86_sse2_psrai_w:
8337   case Intrinsic::x86_sse2_psrai_d:
8338   case Intrinsic::x86_mmx_pslli_w:
8339   case Intrinsic::x86_mmx_pslli_d:
8340   case Intrinsic::x86_mmx_pslli_q:
8341   case Intrinsic::x86_mmx_psrli_w:
8342   case Intrinsic::x86_mmx_psrli_d:
8343   case Intrinsic::x86_mmx_psrli_q:
8344   case Intrinsic::x86_mmx_psrai_w:
8345   case Intrinsic::x86_mmx_psrai_d: {
8346     SDValue ShAmt = Op.getOperand(2);
8347     if (isa<ConstantSDNode>(ShAmt))
8348       return SDValue();
8349
8350     unsigned NewIntNo = 0;
8351     EVT ShAmtVT = MVT::v4i32;
8352     switch (IntNo) {
8353     case Intrinsic::x86_sse2_pslli_w:
8354       NewIntNo = Intrinsic::x86_sse2_psll_w;
8355       break;
8356     case Intrinsic::x86_sse2_pslli_d:
8357       NewIntNo = Intrinsic::x86_sse2_psll_d;
8358       break;
8359     case Intrinsic::x86_sse2_pslli_q:
8360       NewIntNo = Intrinsic::x86_sse2_psll_q;
8361       break;
8362     case Intrinsic::x86_sse2_psrli_w:
8363       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8364       break;
8365     case Intrinsic::x86_sse2_psrli_d:
8366       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8367       break;
8368     case Intrinsic::x86_sse2_psrli_q:
8369       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8370       break;
8371     case Intrinsic::x86_sse2_psrai_w:
8372       NewIntNo = Intrinsic::x86_sse2_psra_w;
8373       break;
8374     case Intrinsic::x86_sse2_psrai_d:
8375       NewIntNo = Intrinsic::x86_sse2_psra_d;
8376       break;
8377     default: {
8378       ShAmtVT = MVT::v2i32;
8379       switch (IntNo) {
8380       case Intrinsic::x86_mmx_pslli_w:
8381         NewIntNo = Intrinsic::x86_mmx_psll_w;
8382         break;
8383       case Intrinsic::x86_mmx_pslli_d:
8384         NewIntNo = Intrinsic::x86_mmx_psll_d;
8385         break;
8386       case Intrinsic::x86_mmx_pslli_q:
8387         NewIntNo = Intrinsic::x86_mmx_psll_q;
8388         break;
8389       case Intrinsic::x86_mmx_psrli_w:
8390         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8391         break;
8392       case Intrinsic::x86_mmx_psrli_d:
8393         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8394         break;
8395       case Intrinsic::x86_mmx_psrli_q:
8396         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8397         break;
8398       case Intrinsic::x86_mmx_psrai_w:
8399         NewIntNo = Intrinsic::x86_mmx_psra_w;
8400         break;
8401       case Intrinsic::x86_mmx_psrai_d:
8402         NewIntNo = Intrinsic::x86_mmx_psra_d;
8403         break;
8404       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8405       }
8406       break;
8407     }
8408     }
8409
8410     // The vector shift intrinsics with scalars uses 32b shift amounts but
8411     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8412     // to be zero.
8413     SDValue ShOps[4];
8414     ShOps[0] = ShAmt;
8415     ShOps[1] = DAG.getConstant(0, MVT::i32);
8416     if (ShAmtVT == MVT::v4i32) {
8417       ShOps[2] = DAG.getUNDEF(MVT::i32);
8418       ShOps[3] = DAG.getUNDEF(MVT::i32);
8419       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8420     } else {
8421       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8422 // FIXME this must be lowered to get rid of the invalid type.
8423     }
8424
8425     EVT VT = Op.getValueType();
8426     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8427     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8428                        DAG.getConstant(NewIntNo, MVT::i32),
8429                        Op.getOperand(1), ShAmt);
8430   }
8431   }
8432 }
8433
8434 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8435                                            SelectionDAG &DAG) const {
8436   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8437   MFI->setReturnAddressIsTaken(true);
8438
8439   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8440   DebugLoc dl = Op.getDebugLoc();
8441
8442   if (Depth > 0) {
8443     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8444     SDValue Offset =
8445       DAG.getConstant(TD->getPointerSize(),
8446                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8447     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8448                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8449                                    FrameAddr, Offset),
8450                        MachinePointerInfo(), false, false, 0);
8451   }
8452
8453   // Just load the return address.
8454   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8455   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8456                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8457 }
8458
8459 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8460   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8461   MFI->setFrameAddressIsTaken(true);
8462
8463   EVT VT = Op.getValueType();
8464   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8465   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8466   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8467   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8468   while (Depth--)
8469     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8470                             MachinePointerInfo(),
8471                             false, false, 0);
8472   return FrameAddr;
8473 }
8474
8475 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8476                                                      SelectionDAG &DAG) const {
8477   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8478 }
8479
8480 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8481   MachineFunction &MF = DAG.getMachineFunction();
8482   SDValue Chain     = Op.getOperand(0);
8483   SDValue Offset    = Op.getOperand(1);
8484   SDValue Handler   = Op.getOperand(2);
8485   DebugLoc dl       = Op.getDebugLoc();
8486
8487   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8488                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8489                                      getPointerTy());
8490   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8491
8492   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8493                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8494   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8495   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8496                        false, false, 0);
8497   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8498   MF.getRegInfo().addLiveOut(StoreAddrReg);
8499
8500   return DAG.getNode(X86ISD::EH_RETURN, dl,
8501                      MVT::Other,
8502                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8503 }
8504
8505 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8506                                              SelectionDAG &DAG) const {
8507   SDValue Root = Op.getOperand(0);
8508   SDValue Trmp = Op.getOperand(1); // trampoline
8509   SDValue FPtr = Op.getOperand(2); // nested function
8510   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8511   DebugLoc dl  = Op.getDebugLoc();
8512
8513   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8514
8515   if (Subtarget->is64Bit()) {
8516     SDValue OutChains[6];
8517
8518     // Large code-model.
8519     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8520     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8521
8522     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8523     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8524
8525     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8526
8527     // Load the pointer to the nested function into R11.
8528     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8529     SDValue Addr = Trmp;
8530     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8531                                 Addr, MachinePointerInfo(TrmpAddr),
8532                                 false, false, 0);
8533
8534     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8535                        DAG.getConstant(2, MVT::i64));
8536     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8537                                 MachinePointerInfo(TrmpAddr, 2),
8538                                 false, false, 2);
8539
8540     // Load the 'nest' parameter value into R10.
8541     // R10 is specified in X86CallingConv.td
8542     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8544                        DAG.getConstant(10, MVT::i64));
8545     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8546                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8547                                 false, false, 0);
8548
8549     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8550                        DAG.getConstant(12, MVT::i64));
8551     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8552                                 MachinePointerInfo(TrmpAddr, 12),
8553                                 false, false, 2);
8554
8555     // Jump to the nested function.
8556     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8557     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8558                        DAG.getConstant(20, MVT::i64));
8559     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8560                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8561                                 false, false, 0);
8562
8563     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8564     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8565                        DAG.getConstant(22, MVT::i64));
8566     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8567                                 MachinePointerInfo(TrmpAddr, 22),
8568                                 false, false, 0);
8569
8570     SDValue Ops[] =
8571       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8572     return DAG.getMergeValues(Ops, 2, dl);
8573   } else {
8574     const Function *Func =
8575       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8576     CallingConv::ID CC = Func->getCallingConv();
8577     unsigned NestReg;
8578
8579     switch (CC) {
8580     default:
8581       llvm_unreachable("Unsupported calling convention");
8582     case CallingConv::C:
8583     case CallingConv::X86_StdCall: {
8584       // Pass 'nest' parameter in ECX.
8585       // Must be kept in sync with X86CallingConv.td
8586       NestReg = X86::ECX;
8587
8588       // Check that ECX wasn't needed by an 'inreg' parameter.
8589       const FunctionType *FTy = Func->getFunctionType();
8590       const AttrListPtr &Attrs = Func->getAttributes();
8591
8592       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8593         unsigned InRegCount = 0;
8594         unsigned Idx = 1;
8595
8596         for (FunctionType::param_iterator I = FTy->param_begin(),
8597              E = FTy->param_end(); I != E; ++I, ++Idx)
8598           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8599             // FIXME: should only count parameters that are lowered to integers.
8600             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8601
8602         if (InRegCount > 2) {
8603           report_fatal_error("Nest register in use - reduce number of inreg"
8604                              " parameters!");
8605         }
8606       }
8607       break;
8608     }
8609     case CallingConv::X86_FastCall:
8610     case CallingConv::X86_ThisCall:
8611     case CallingConv::Fast:
8612       // Pass 'nest' parameter in EAX.
8613       // Must be kept in sync with X86CallingConv.td
8614       NestReg = X86::EAX;
8615       break;
8616     }
8617
8618     SDValue OutChains[4];
8619     SDValue Addr, Disp;
8620
8621     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8622                        DAG.getConstant(10, MVT::i32));
8623     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8624
8625     // This is storing the opcode for MOV32ri.
8626     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8627     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8628     OutChains[0] = DAG.getStore(Root, dl,
8629                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8630                                 Trmp, MachinePointerInfo(TrmpAddr),
8631                                 false, false, 0);
8632
8633     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8634                        DAG.getConstant(1, MVT::i32));
8635     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8636                                 MachinePointerInfo(TrmpAddr, 1),
8637                                 false, false, 1);
8638
8639     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8640     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8641                        DAG.getConstant(5, MVT::i32));
8642     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8643                                 MachinePointerInfo(TrmpAddr, 5),
8644                                 false, false, 1);
8645
8646     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8647                        DAG.getConstant(6, MVT::i32));
8648     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8649                                 MachinePointerInfo(TrmpAddr, 6),
8650                                 false, false, 1);
8651
8652     SDValue Ops[] =
8653       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8654     return DAG.getMergeValues(Ops, 2, dl);
8655   }
8656 }
8657
8658 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8659                                             SelectionDAG &DAG) const {
8660   /*
8661    The rounding mode is in bits 11:10 of FPSR, and has the following
8662    settings:
8663      00 Round to nearest
8664      01 Round to -inf
8665      10 Round to +inf
8666      11 Round to 0
8667
8668   FLT_ROUNDS, on the other hand, expects the following:
8669     -1 Undefined
8670      0 Round to 0
8671      1 Round to nearest
8672      2 Round to +inf
8673      3 Round to -inf
8674
8675   To perform the conversion, we do:
8676     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8677   */
8678
8679   MachineFunction &MF = DAG.getMachineFunction();
8680   const TargetMachine &TM = MF.getTarget();
8681   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8682   unsigned StackAlignment = TFI.getStackAlignment();
8683   EVT VT = Op.getValueType();
8684   DebugLoc DL = Op.getDebugLoc();
8685
8686   // Save FP Control Word to stack slot
8687   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8688   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8689
8690
8691   MachineMemOperand *MMO =
8692    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8693                            MachineMemOperand::MOStore, 2, 2);
8694
8695   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8696   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8697                                           DAG.getVTList(MVT::Other),
8698                                           Ops, 2, MVT::i16, MMO);
8699
8700   // Load FP Control Word from stack slot
8701   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8702                             MachinePointerInfo(), false, false, 0);
8703
8704   // Transform as necessary
8705   SDValue CWD1 =
8706     DAG.getNode(ISD::SRL, DL, MVT::i16,
8707                 DAG.getNode(ISD::AND, DL, MVT::i16,
8708                             CWD, DAG.getConstant(0x800, MVT::i16)),
8709                 DAG.getConstant(11, MVT::i8));
8710   SDValue CWD2 =
8711     DAG.getNode(ISD::SRL, DL, MVT::i16,
8712                 DAG.getNode(ISD::AND, DL, MVT::i16,
8713                             CWD, DAG.getConstant(0x400, MVT::i16)),
8714                 DAG.getConstant(9, MVT::i8));
8715
8716   SDValue RetVal =
8717     DAG.getNode(ISD::AND, DL, MVT::i16,
8718                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8719                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8720                             DAG.getConstant(1, MVT::i16)),
8721                 DAG.getConstant(3, MVT::i16));
8722
8723
8724   return DAG.getNode((VT.getSizeInBits() < 16 ?
8725                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8726 }
8727
8728 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8729   EVT VT = Op.getValueType();
8730   EVT OpVT = VT;
8731   unsigned NumBits = VT.getSizeInBits();
8732   DebugLoc dl = Op.getDebugLoc();
8733
8734   Op = Op.getOperand(0);
8735   if (VT == MVT::i8) {
8736     // Zero extend to i32 since there is not an i8 bsr.
8737     OpVT = MVT::i32;
8738     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8739   }
8740
8741   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8742   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8743   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8744
8745   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8746   SDValue Ops[] = {
8747     Op,
8748     DAG.getConstant(NumBits+NumBits-1, OpVT),
8749     DAG.getConstant(X86::COND_E, MVT::i8),
8750     Op.getValue(1)
8751   };
8752   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8753
8754   // Finally xor with NumBits-1.
8755   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8756
8757   if (VT == MVT::i8)
8758     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8759   return Op;
8760 }
8761
8762 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8763   EVT VT = Op.getValueType();
8764   EVT OpVT = VT;
8765   unsigned NumBits = VT.getSizeInBits();
8766   DebugLoc dl = Op.getDebugLoc();
8767
8768   Op = Op.getOperand(0);
8769   if (VT == MVT::i8) {
8770     OpVT = MVT::i32;
8771     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8772   }
8773
8774   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8775   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8776   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8777
8778   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8779   SDValue Ops[] = {
8780     Op,
8781     DAG.getConstant(NumBits, OpVT),
8782     DAG.getConstant(X86::COND_E, MVT::i8),
8783     Op.getValue(1)
8784   };
8785   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8786
8787   if (VT == MVT::i8)
8788     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8789   return Op;
8790 }
8791
8792 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8793   EVT VT = Op.getValueType();
8794   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8795   DebugLoc dl = Op.getDebugLoc();
8796
8797   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8798   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8799   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8800   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8801   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8802   //
8803   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8804   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8805   //  return AloBlo + AloBhi + AhiBlo;
8806
8807   SDValue A = Op.getOperand(0);
8808   SDValue B = Op.getOperand(1);
8809
8810   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8811                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8812                        A, DAG.getConstant(32, MVT::i32));
8813   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8814                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8815                        B, DAG.getConstant(32, MVT::i32));
8816   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8817                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8818                        A, B);
8819   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8820                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8821                        A, Bhi);
8822   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8823                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8824                        Ahi, B);
8825   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8826                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8827                        AloBhi, DAG.getConstant(32, MVT::i32));
8828   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8830                        AhiBlo, DAG.getConstant(32, MVT::i32));
8831   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8832   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8833   return Res;
8834 }
8835
8836 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8837
8838   EVT VT = Op.getValueType();
8839   DebugLoc dl = Op.getDebugLoc();
8840   SDValue R = Op.getOperand(0);
8841   SDValue Amt = Op.getOperand(1);
8842
8843   LLVMContext *Context = DAG.getContext();
8844
8845   // Must have SSE2.
8846   if (!Subtarget->hasSSE2()) return SDValue();
8847
8848   // Optimize shl/srl/sra with constant shift amount.
8849   if (isSplatVector(Amt.getNode())) {
8850     SDValue SclrAmt = Amt->getOperand(0);
8851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8852       uint64_t ShiftAmt = C->getZExtValue();
8853
8854       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8855        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8856                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8857                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8858
8859       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8860        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8861                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8862                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8863
8864       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8865        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8866                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8867                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8868
8869       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8870        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8871                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8872                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8873
8874       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8875        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8876                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8877                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8878
8879       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8880        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8881                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8882                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8883
8884       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8885        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8886                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8887                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8888
8889       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8890        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8891                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8892                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8893     }
8894   }
8895
8896   // Lower SHL with variable shift amount.
8897   // Cannot lower SHL without SSE4.1 or later.
8898   if (!Subtarget->hasSSE41()) return SDValue();
8899
8900   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8901     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8902                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8903                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8904
8905     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8906
8907     std::vector<Constant*> CV(4, CI);
8908     Constant *C = ConstantVector::get(CV);
8909     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8910     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8911                                  MachinePointerInfo::getConstantPool(),
8912                                  false, false, 16);
8913
8914     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8915     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8916     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8917     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8918   }
8919   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8920     // a = a << 5;
8921     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8922                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8923                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8924
8925     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8926     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8927
8928     std::vector<Constant*> CVM1(16, CM1);
8929     std::vector<Constant*> CVM2(16, CM2);
8930     Constant *C = ConstantVector::get(CVM1);
8931     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8932     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8933                             MachinePointerInfo::getConstantPool(),
8934                             false, false, 16);
8935
8936     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8937     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8938     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8939                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8940                     DAG.getConstant(4, MVT::i32));
8941     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8942     // a += a
8943     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8944
8945     C = ConstantVector::get(CVM2);
8946     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8947     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8948                     MachinePointerInfo::getConstantPool(),
8949                     false, false, 16);
8950
8951     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8952     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8953     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8954                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8955                     DAG.getConstant(2, MVT::i32));
8956     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8957     // a += a
8958     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8959
8960     // return pblendv(r, r+r, a);
8961     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8962                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8963     return R;
8964   }
8965   return SDValue();
8966 }
8967
8968 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8969   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8970   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8971   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8972   // has only one use.
8973   SDNode *N = Op.getNode();
8974   SDValue LHS = N->getOperand(0);
8975   SDValue RHS = N->getOperand(1);
8976   unsigned BaseOp = 0;
8977   unsigned Cond = 0;
8978   DebugLoc DL = Op.getDebugLoc();
8979   switch (Op.getOpcode()) {
8980   default: llvm_unreachable("Unknown ovf instruction!");
8981   case ISD::SADDO:
8982     // A subtract of one will be selected as a INC. Note that INC doesn't
8983     // set CF, so we can't do this for UADDO.
8984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8985       if (C->isOne()) {
8986         BaseOp = X86ISD::INC;
8987         Cond = X86::COND_O;
8988         break;
8989       }
8990     BaseOp = X86ISD::ADD;
8991     Cond = X86::COND_O;
8992     break;
8993   case ISD::UADDO:
8994     BaseOp = X86ISD::ADD;
8995     Cond = X86::COND_B;
8996     break;
8997   case ISD::SSUBO:
8998     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8999     // set CF, so we can't do this for USUBO.
9000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9001       if (C->isOne()) {
9002         BaseOp = X86ISD::DEC;
9003         Cond = X86::COND_O;
9004         break;
9005       }
9006     BaseOp = X86ISD::SUB;
9007     Cond = X86::COND_O;
9008     break;
9009   case ISD::USUBO:
9010     BaseOp = X86ISD::SUB;
9011     Cond = X86::COND_B;
9012     break;
9013   case ISD::SMULO:
9014     BaseOp = X86ISD::SMUL;
9015     Cond = X86::COND_O;
9016     break;
9017   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9018     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9019                                  MVT::i32);
9020     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9021
9022     SDValue SetCC =
9023       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9024                   DAG.getConstant(X86::COND_O, MVT::i32),
9025                   SDValue(Sum.getNode(), 2));
9026
9027     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9028     return Sum;
9029   }
9030   }
9031
9032   // Also sets EFLAGS.
9033   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9034   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9035
9036   SDValue SetCC =
9037     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9038                 DAG.getConstant(Cond, MVT::i32),
9039                 SDValue(Sum.getNode(), 1));
9040
9041   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9042   return Sum;
9043 }
9044
9045 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9046   DebugLoc dl = Op.getDebugLoc();
9047
9048   if (!Subtarget->hasSSE2()) {
9049     SDValue Chain = Op.getOperand(0);
9050     SDValue Zero = DAG.getConstant(0,
9051                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9052     SDValue Ops[] = {
9053       DAG.getRegister(X86::ESP, MVT::i32), // Base
9054       DAG.getTargetConstant(1, MVT::i8),   // Scale
9055       DAG.getRegister(0, MVT::i32),        // Index
9056       DAG.getTargetConstant(0, MVT::i32),  // Disp
9057       DAG.getRegister(0, MVT::i32),        // Segment.
9058       Zero,
9059       Chain
9060     };
9061     SDNode *Res =
9062       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9063                           array_lengthof(Ops));
9064     return SDValue(Res, 0);
9065   }
9066
9067   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9068   if (!isDev)
9069     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9070
9071   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9072   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9073   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9074   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9075
9076   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9077   if (!Op1 && !Op2 && !Op3 && Op4)
9078     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9079
9080   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9081   if (Op1 && !Op2 && !Op3 && !Op4)
9082     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9083
9084   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9085   //           (MFENCE)>;
9086   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9087 }
9088
9089 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9090   EVT T = Op.getValueType();
9091   DebugLoc DL = Op.getDebugLoc();
9092   unsigned Reg = 0;
9093   unsigned size = 0;
9094   switch(T.getSimpleVT().SimpleTy) {
9095   default:
9096     assert(false && "Invalid value type!");
9097   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9098   case MVT::i16: Reg = X86::AX;  size = 2; break;
9099   case MVT::i32: Reg = X86::EAX; size = 4; break;
9100   case MVT::i64:
9101     assert(Subtarget->is64Bit() && "Node not type legal!");
9102     Reg = X86::RAX; size = 8;
9103     break;
9104   }
9105   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9106                                     Op.getOperand(2), SDValue());
9107   SDValue Ops[] = { cpIn.getValue(0),
9108                     Op.getOperand(1),
9109                     Op.getOperand(3),
9110                     DAG.getTargetConstant(size, MVT::i8),
9111                     cpIn.getValue(1) };
9112   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9113   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9114   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9115                                            Ops, 5, T, MMO);
9116   SDValue cpOut =
9117     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9118   return cpOut;
9119 }
9120
9121 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9122                                                  SelectionDAG &DAG) const {
9123   assert(Subtarget->is64Bit() && "Result not type legalized?");
9124   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9125   SDValue TheChain = Op.getOperand(0);
9126   DebugLoc dl = Op.getDebugLoc();
9127   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9128   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9129   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9130                                    rax.getValue(2));
9131   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9132                             DAG.getConstant(32, MVT::i8));
9133   SDValue Ops[] = {
9134     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9135     rdx.getValue(1)
9136   };
9137   return DAG.getMergeValues(Ops, 2, dl);
9138 }
9139
9140 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9141                                             SelectionDAG &DAG) const {
9142   EVT SrcVT = Op.getOperand(0).getValueType();
9143   EVT DstVT = Op.getValueType();
9144   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9145          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9146   assert((DstVT == MVT::i64 ||
9147           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9148          "Unexpected custom BITCAST");
9149   // i64 <=> MMX conversions are Legal.
9150   if (SrcVT==MVT::i64 && DstVT.isVector())
9151     return Op;
9152   if (DstVT==MVT::i64 && SrcVT.isVector())
9153     return Op;
9154   // MMX <=> MMX conversions are Legal.
9155   if (SrcVT.isVector() && DstVT.isVector())
9156     return Op;
9157   // All other conversions need to be expanded.
9158   return SDValue();
9159 }
9160
9161 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9162   SDNode *Node = Op.getNode();
9163   DebugLoc dl = Node->getDebugLoc();
9164   EVT T = Node->getValueType(0);
9165   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9166                               DAG.getConstant(0, T), Node->getOperand(2));
9167   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9168                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9169                        Node->getOperand(0),
9170                        Node->getOperand(1), negOp,
9171                        cast<AtomicSDNode>(Node)->getSrcValue(),
9172                        cast<AtomicSDNode>(Node)->getAlignment());
9173 }
9174
9175 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9176   EVT VT = Op.getNode()->getValueType(0);
9177
9178   // Let legalize expand this if it isn't a legal type yet.
9179   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9180     return SDValue();
9181
9182   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9183
9184   unsigned Opc;
9185   bool ExtraOp = false;
9186   switch (Op.getOpcode()) {
9187   default: assert(0 && "Invalid code");
9188   case ISD::ADDC: Opc = X86ISD::ADD; break;
9189   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9190   case ISD::SUBC: Opc = X86ISD::SUB; break;
9191   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9192   }
9193
9194   if (!ExtraOp)
9195     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9196                        Op.getOperand(1));
9197   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9198                      Op.getOperand(1), Op.getOperand(2));
9199 }
9200
9201 /// LowerOperation - Provide custom lowering hooks for some operations.
9202 ///
9203 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9204   switch (Op.getOpcode()) {
9205   default: llvm_unreachable("Should not custom lower this!");
9206   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9207   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9208   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9209   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9210   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9211   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9212   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9213   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9214   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9215   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9216   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9217   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9218   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9219   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9220   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9221   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9222   case ISD::SHL_PARTS:
9223   case ISD::SRA_PARTS:
9224   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9225   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9226   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9227   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9228   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9229   case ISD::FABS:               return LowerFABS(Op, DAG);
9230   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9231   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9232   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9233   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9234   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9235   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9236   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9237   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9238   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9239   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9240   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9241   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9242   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9243   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9244   case ISD::FRAME_TO_ARGS_OFFSET:
9245                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9246   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9247   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9248   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9249   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9250   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9251   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9252   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9253   case ISD::SRA:
9254   case ISD::SRL:
9255   case ISD::SHL:                return LowerShift(Op, DAG);
9256   case ISD::SADDO:
9257   case ISD::UADDO:
9258   case ISD::SSUBO:
9259   case ISD::USUBO:
9260   case ISD::SMULO:
9261   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9262   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9263   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9264   case ISD::ADDC:
9265   case ISD::ADDE:
9266   case ISD::SUBC:
9267   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9268   }
9269 }
9270
9271 void X86TargetLowering::
9272 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9273                         SelectionDAG &DAG, unsigned NewOp) const {
9274   EVT T = Node->getValueType(0);
9275   DebugLoc dl = Node->getDebugLoc();
9276   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9277
9278   SDValue Chain = Node->getOperand(0);
9279   SDValue In1 = Node->getOperand(1);
9280   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9281                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9282   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9283                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9284   SDValue Ops[] = { Chain, In1, In2L, In2H };
9285   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9286   SDValue Result =
9287     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9288                             cast<MemSDNode>(Node)->getMemOperand());
9289   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9290   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9291   Results.push_back(Result.getValue(2));
9292 }
9293
9294 /// ReplaceNodeResults - Replace a node with an illegal result type
9295 /// with a new node built out of custom code.
9296 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9297                                            SmallVectorImpl<SDValue>&Results,
9298                                            SelectionDAG &DAG) const {
9299   DebugLoc dl = N->getDebugLoc();
9300   switch (N->getOpcode()) {
9301   default:
9302     assert(false && "Do not know how to custom type legalize this operation!");
9303     return;
9304   case ISD::ADDC:
9305   case ISD::ADDE:
9306   case ISD::SUBC:
9307   case ISD::SUBE:
9308     // We don't want to expand or promote these.
9309     return;
9310   case ISD::FP_TO_SINT: {
9311     std::pair<SDValue,SDValue> Vals =
9312         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9313     SDValue FIST = Vals.first, StackSlot = Vals.second;
9314     if (FIST.getNode() != 0) {
9315       EVT VT = N->getValueType(0);
9316       // Return a load from the stack slot.
9317       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9318                                     MachinePointerInfo(), false, false, 0));
9319     }
9320     return;
9321   }
9322   case ISD::READCYCLECOUNTER: {
9323     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9324     SDValue TheChain = N->getOperand(0);
9325     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9326     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9327                                      rd.getValue(1));
9328     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9329                                      eax.getValue(2));
9330     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9331     SDValue Ops[] = { eax, edx };
9332     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9333     Results.push_back(edx.getValue(1));
9334     return;
9335   }
9336   case ISD::ATOMIC_CMP_SWAP: {
9337     EVT T = N->getValueType(0);
9338     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9339     SDValue cpInL, cpInH;
9340     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9341                         DAG.getConstant(0, MVT::i32));
9342     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9343                         DAG.getConstant(1, MVT::i32));
9344     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9345     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9346                              cpInL.getValue(1));
9347     SDValue swapInL, swapInH;
9348     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9349                           DAG.getConstant(0, MVT::i32));
9350     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9351                           DAG.getConstant(1, MVT::i32));
9352     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9353                                cpInH.getValue(1));
9354     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9355                                swapInL.getValue(1));
9356     SDValue Ops[] = { swapInH.getValue(0),
9357                       N->getOperand(1),
9358                       swapInH.getValue(1) };
9359     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9360     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9361     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9362                                              Ops, 3, T, MMO);
9363     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9364                                         MVT::i32, Result.getValue(1));
9365     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9366                                         MVT::i32, cpOutL.getValue(2));
9367     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9368     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9369     Results.push_back(cpOutH.getValue(1));
9370     return;
9371   }
9372   case ISD::ATOMIC_LOAD_ADD:
9373     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9374     return;
9375   case ISD::ATOMIC_LOAD_AND:
9376     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9377     return;
9378   case ISD::ATOMIC_LOAD_NAND:
9379     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9380     return;
9381   case ISD::ATOMIC_LOAD_OR:
9382     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9383     return;
9384   case ISD::ATOMIC_LOAD_SUB:
9385     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9386     return;
9387   case ISD::ATOMIC_LOAD_XOR:
9388     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9389     return;
9390   case ISD::ATOMIC_SWAP:
9391     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9392     return;
9393   }
9394 }
9395
9396 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9397   switch (Opcode) {
9398   default: return NULL;
9399   case X86ISD::BSF:                return "X86ISD::BSF";
9400   case X86ISD::BSR:                return "X86ISD::BSR";
9401   case X86ISD::SHLD:               return "X86ISD::SHLD";
9402   case X86ISD::SHRD:               return "X86ISD::SHRD";
9403   case X86ISD::FAND:               return "X86ISD::FAND";
9404   case X86ISD::FOR:                return "X86ISD::FOR";
9405   case X86ISD::FXOR:               return "X86ISD::FXOR";
9406   case X86ISD::FSRL:               return "X86ISD::FSRL";
9407   case X86ISD::FILD:               return "X86ISD::FILD";
9408   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9409   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9410   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9411   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9412   case X86ISD::FLD:                return "X86ISD::FLD";
9413   case X86ISD::FST:                return "X86ISD::FST";
9414   case X86ISD::CALL:               return "X86ISD::CALL";
9415   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9416   case X86ISD::BT:                 return "X86ISD::BT";
9417   case X86ISD::CMP:                return "X86ISD::CMP";
9418   case X86ISD::COMI:               return "X86ISD::COMI";
9419   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9420   case X86ISD::SETCC:              return "X86ISD::SETCC";
9421   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9422   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9423   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9424   case X86ISD::CMOV:               return "X86ISD::CMOV";
9425   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9426   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9427   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9428   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9429   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9430   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9431   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9432   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9433   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9434   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9435   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9436   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9437   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9438   case X86ISD::PANDN:              return "X86ISD::PANDN";
9439   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9440   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9441   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9442   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9443   case X86ISD::FMAX:               return "X86ISD::FMAX";
9444   case X86ISD::FMIN:               return "X86ISD::FMIN";
9445   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9446   case X86ISD::FRCP:               return "X86ISD::FRCP";
9447   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9448   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9449   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9450   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9451   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9452   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9453   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9454   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9455   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9456   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9457   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9458   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9459   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9460   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9461   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9462   case X86ISD::VSHL:               return "X86ISD::VSHL";
9463   case X86ISD::VSRL:               return "X86ISD::VSRL";
9464   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9465   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9466   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9467   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9468   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9469   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9470   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9471   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9472   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9473   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9474   case X86ISD::ADD:                return "X86ISD::ADD";
9475   case X86ISD::SUB:                return "X86ISD::SUB";
9476   case X86ISD::ADC:                return "X86ISD::ADC";
9477   case X86ISD::SBB:                return "X86ISD::SBB";
9478   case X86ISD::SMUL:               return "X86ISD::SMUL";
9479   case X86ISD::UMUL:               return "X86ISD::UMUL";
9480   case X86ISD::INC:                return "X86ISD::INC";
9481   case X86ISD::DEC:                return "X86ISD::DEC";
9482   case X86ISD::OR:                 return "X86ISD::OR";
9483   case X86ISD::XOR:                return "X86ISD::XOR";
9484   case X86ISD::AND:                return "X86ISD::AND";
9485   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9486   case X86ISD::PTEST:              return "X86ISD::PTEST";
9487   case X86ISD::TESTP:              return "X86ISD::TESTP";
9488   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9489   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9490   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9491   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9492   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9493   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9494   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9495   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9496   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9497   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9498   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9499   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9500   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9501   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9502   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9503   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9504   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9505   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9506   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9507   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9508   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9509   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9510   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9511   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9512   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9513   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9514   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9515   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9516   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9517   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9518   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9519   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9520   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9521   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9522   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9523   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9524   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9525   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9526   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9527   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9528   }
9529 }
9530
9531 // isLegalAddressingMode - Return true if the addressing mode represented
9532 // by AM is legal for this target, for a load/store of the specified type.
9533 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9534                                               const Type *Ty) const {
9535   // X86 supports extremely general addressing modes.
9536   CodeModel::Model M = getTargetMachine().getCodeModel();
9537   Reloc::Model R = getTargetMachine().getRelocationModel();
9538
9539   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9540   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9541     return false;
9542
9543   if (AM.BaseGV) {
9544     unsigned GVFlags =
9545       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9546
9547     // If a reference to this global requires an extra load, we can't fold it.
9548     if (isGlobalStubReference(GVFlags))
9549       return false;
9550
9551     // If BaseGV requires a register for the PIC base, we cannot also have a
9552     // BaseReg specified.
9553     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9554       return false;
9555
9556     // If lower 4G is not available, then we must use rip-relative addressing.
9557     if ((M != CodeModel::Small || R != Reloc::Static) &&
9558         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9559       return false;
9560   }
9561
9562   switch (AM.Scale) {
9563   case 0:
9564   case 1:
9565   case 2:
9566   case 4:
9567   case 8:
9568     // These scales always work.
9569     break;
9570   case 3:
9571   case 5:
9572   case 9:
9573     // These scales are formed with basereg+scalereg.  Only accept if there is
9574     // no basereg yet.
9575     if (AM.HasBaseReg)
9576       return false;
9577     break;
9578   default:  // Other stuff never works.
9579     return false;
9580   }
9581
9582   return true;
9583 }
9584
9585
9586 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9587   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9588     return false;
9589   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9590   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9591   if (NumBits1 <= NumBits2)
9592     return false;
9593   return true;
9594 }
9595
9596 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9597   if (!VT1.isInteger() || !VT2.isInteger())
9598     return false;
9599   unsigned NumBits1 = VT1.getSizeInBits();
9600   unsigned NumBits2 = VT2.getSizeInBits();
9601   if (NumBits1 <= NumBits2)
9602     return false;
9603   return true;
9604 }
9605
9606 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9607   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9608   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9609 }
9610
9611 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9612   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9613   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9614 }
9615
9616 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9617   // i16 instructions are longer (0x66 prefix) and potentially slower.
9618   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9619 }
9620
9621 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9622 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9623 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9624 /// are assumed to be legal.
9625 bool
9626 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9627                                       EVT VT) const {
9628   // Very little shuffling can be done for 64-bit vectors right now.
9629   if (VT.getSizeInBits() == 64)
9630     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9631
9632   // FIXME: pshufb, blends, shifts.
9633   return (VT.getVectorNumElements() == 2 ||
9634           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9635           isMOVLMask(M, VT) ||
9636           isSHUFPMask(M, VT) ||
9637           isPSHUFDMask(M, VT) ||
9638           isPSHUFHWMask(M, VT) ||
9639           isPSHUFLWMask(M, VT) ||
9640           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9641           isUNPCKLMask(M, VT) ||
9642           isUNPCKHMask(M, VT) ||
9643           isUNPCKL_v_undef_Mask(M, VT) ||
9644           isUNPCKH_v_undef_Mask(M, VT));
9645 }
9646
9647 bool
9648 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9649                                           EVT VT) const {
9650   unsigned NumElts = VT.getVectorNumElements();
9651   // FIXME: This collection of masks seems suspect.
9652   if (NumElts == 2)
9653     return true;
9654   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9655     return (isMOVLMask(Mask, VT)  ||
9656             isCommutedMOVLMask(Mask, VT, true) ||
9657             isSHUFPMask(Mask, VT) ||
9658             isCommutedSHUFPMask(Mask, VT));
9659   }
9660   return false;
9661 }
9662
9663 //===----------------------------------------------------------------------===//
9664 //                           X86 Scheduler Hooks
9665 //===----------------------------------------------------------------------===//
9666
9667 // private utility function
9668 MachineBasicBlock *
9669 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9670                                                        MachineBasicBlock *MBB,
9671                                                        unsigned regOpc,
9672                                                        unsigned immOpc,
9673                                                        unsigned LoadOpc,
9674                                                        unsigned CXchgOpc,
9675                                                        unsigned notOpc,
9676                                                        unsigned EAXreg,
9677                                                        TargetRegisterClass *RC,
9678                                                        bool invSrc) const {
9679   // For the atomic bitwise operator, we generate
9680   //   thisMBB:
9681   //   newMBB:
9682   //     ld  t1 = [bitinstr.addr]
9683   //     op  t2 = t1, [bitinstr.val]
9684   //     mov EAX = t1
9685   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9686   //     bz  newMBB
9687   //     fallthrough -->nextMBB
9688   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9689   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9690   MachineFunction::iterator MBBIter = MBB;
9691   ++MBBIter;
9692
9693   /// First build the CFG
9694   MachineFunction *F = MBB->getParent();
9695   MachineBasicBlock *thisMBB = MBB;
9696   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9697   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9698   F->insert(MBBIter, newMBB);
9699   F->insert(MBBIter, nextMBB);
9700
9701   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9702   nextMBB->splice(nextMBB->begin(), thisMBB,
9703                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9704                   thisMBB->end());
9705   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9706
9707   // Update thisMBB to fall through to newMBB
9708   thisMBB->addSuccessor(newMBB);
9709
9710   // newMBB jumps to itself and fall through to nextMBB
9711   newMBB->addSuccessor(nextMBB);
9712   newMBB->addSuccessor(newMBB);
9713
9714   // Insert instructions into newMBB based on incoming instruction
9715   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9716          "unexpected number of operands");
9717   DebugLoc dl = bInstr->getDebugLoc();
9718   MachineOperand& destOper = bInstr->getOperand(0);
9719   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9720   int numArgs = bInstr->getNumOperands() - 1;
9721   for (int i=0; i < numArgs; ++i)
9722     argOpers[i] = &bInstr->getOperand(i+1);
9723
9724   // x86 address has 4 operands: base, index, scale, and displacement
9725   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9726   int valArgIndx = lastAddrIndx + 1;
9727
9728   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9729   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9730   for (int i=0; i <= lastAddrIndx; ++i)
9731     (*MIB).addOperand(*argOpers[i]);
9732
9733   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9734   if (invSrc) {
9735     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9736   }
9737   else
9738     tt = t1;
9739
9740   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9741   assert((argOpers[valArgIndx]->isReg() ||
9742           argOpers[valArgIndx]->isImm()) &&
9743          "invalid operand");
9744   if (argOpers[valArgIndx]->isReg())
9745     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9746   else
9747     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9748   MIB.addReg(tt);
9749   (*MIB).addOperand(*argOpers[valArgIndx]);
9750
9751   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9752   MIB.addReg(t1);
9753
9754   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9755   for (int i=0; i <= lastAddrIndx; ++i)
9756     (*MIB).addOperand(*argOpers[i]);
9757   MIB.addReg(t2);
9758   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9759   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9760                     bInstr->memoperands_end());
9761
9762   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9763   MIB.addReg(EAXreg);
9764
9765   // insert branch
9766   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9767
9768   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9769   return nextMBB;
9770 }
9771
9772 // private utility function:  64 bit atomics on 32 bit host.
9773 MachineBasicBlock *
9774 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9775                                                        MachineBasicBlock *MBB,
9776                                                        unsigned regOpcL,
9777                                                        unsigned regOpcH,
9778                                                        unsigned immOpcL,
9779                                                        unsigned immOpcH,
9780                                                        bool invSrc) const {
9781   // For the atomic bitwise operator, we generate
9782   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9783   //     ld t1,t2 = [bitinstr.addr]
9784   //   newMBB:
9785   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9786   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9787   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9788   //     mov ECX, EBX <- t5, t6
9789   //     mov EAX, EDX <- t1, t2
9790   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9791   //     mov t3, t4 <- EAX, EDX
9792   //     bz  newMBB
9793   //     result in out1, out2
9794   //     fallthrough -->nextMBB
9795
9796   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9797   const unsigned LoadOpc = X86::MOV32rm;
9798   const unsigned NotOpc = X86::NOT32r;
9799   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9800   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9801   MachineFunction::iterator MBBIter = MBB;
9802   ++MBBIter;
9803
9804   /// First build the CFG
9805   MachineFunction *F = MBB->getParent();
9806   MachineBasicBlock *thisMBB = MBB;
9807   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9808   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9809   F->insert(MBBIter, newMBB);
9810   F->insert(MBBIter, nextMBB);
9811
9812   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9813   nextMBB->splice(nextMBB->begin(), thisMBB,
9814                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9815                   thisMBB->end());
9816   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9817
9818   // Update thisMBB to fall through to newMBB
9819   thisMBB->addSuccessor(newMBB);
9820
9821   // newMBB jumps to itself and fall through to nextMBB
9822   newMBB->addSuccessor(nextMBB);
9823   newMBB->addSuccessor(newMBB);
9824
9825   DebugLoc dl = bInstr->getDebugLoc();
9826   // Insert instructions into newMBB based on incoming instruction
9827   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9828   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9829          "unexpected number of operands");
9830   MachineOperand& dest1Oper = bInstr->getOperand(0);
9831   MachineOperand& dest2Oper = bInstr->getOperand(1);
9832   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9833   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9834     argOpers[i] = &bInstr->getOperand(i+2);
9835
9836     // We use some of the operands multiple times, so conservatively just
9837     // clear any kill flags that might be present.
9838     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9839       argOpers[i]->setIsKill(false);
9840   }
9841
9842   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9843   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9844
9845   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9846   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9847   for (int i=0; i <= lastAddrIndx; ++i)
9848     (*MIB).addOperand(*argOpers[i]);
9849   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9850   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9851   // add 4 to displacement.
9852   for (int i=0; i <= lastAddrIndx-2; ++i)
9853     (*MIB).addOperand(*argOpers[i]);
9854   MachineOperand newOp3 = *(argOpers[3]);
9855   if (newOp3.isImm())
9856     newOp3.setImm(newOp3.getImm()+4);
9857   else
9858     newOp3.setOffset(newOp3.getOffset()+4);
9859   (*MIB).addOperand(newOp3);
9860   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9861
9862   // t3/4 are defined later, at the bottom of the loop
9863   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9864   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9865   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9866     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9867   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9868     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9869
9870   // The subsequent operations should be using the destination registers of
9871   //the PHI instructions.
9872   if (invSrc) {
9873     t1 = F->getRegInfo().createVirtualRegister(RC);
9874     t2 = F->getRegInfo().createVirtualRegister(RC);
9875     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9876     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9877   } else {
9878     t1 = dest1Oper.getReg();
9879     t2 = dest2Oper.getReg();
9880   }
9881
9882   int valArgIndx = lastAddrIndx + 1;
9883   assert((argOpers[valArgIndx]->isReg() ||
9884           argOpers[valArgIndx]->isImm()) &&
9885          "invalid operand");
9886   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9887   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9888   if (argOpers[valArgIndx]->isReg())
9889     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9890   else
9891     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9892   if (regOpcL != X86::MOV32rr)
9893     MIB.addReg(t1);
9894   (*MIB).addOperand(*argOpers[valArgIndx]);
9895   assert(argOpers[valArgIndx + 1]->isReg() ==
9896          argOpers[valArgIndx]->isReg());
9897   assert(argOpers[valArgIndx + 1]->isImm() ==
9898          argOpers[valArgIndx]->isImm());
9899   if (argOpers[valArgIndx + 1]->isReg())
9900     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9901   else
9902     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9903   if (regOpcH != X86::MOV32rr)
9904     MIB.addReg(t2);
9905   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9906
9907   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9908   MIB.addReg(t1);
9909   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9910   MIB.addReg(t2);
9911
9912   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9913   MIB.addReg(t5);
9914   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9915   MIB.addReg(t6);
9916
9917   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9918   for (int i=0; i <= lastAddrIndx; ++i)
9919     (*MIB).addOperand(*argOpers[i]);
9920
9921   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9922   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9923                     bInstr->memoperands_end());
9924
9925   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9926   MIB.addReg(X86::EAX);
9927   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9928   MIB.addReg(X86::EDX);
9929
9930   // insert branch
9931   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9932
9933   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9934   return nextMBB;
9935 }
9936
9937 // private utility function
9938 MachineBasicBlock *
9939 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9940                                                       MachineBasicBlock *MBB,
9941                                                       unsigned cmovOpc) const {
9942   // For the atomic min/max operator, we generate
9943   //   thisMBB:
9944   //   newMBB:
9945   //     ld t1 = [min/max.addr]
9946   //     mov t2 = [min/max.val]
9947   //     cmp  t1, t2
9948   //     cmov[cond] t2 = t1
9949   //     mov EAX = t1
9950   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9951   //     bz   newMBB
9952   //     fallthrough -->nextMBB
9953   //
9954   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9955   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9956   MachineFunction::iterator MBBIter = MBB;
9957   ++MBBIter;
9958
9959   /// First build the CFG
9960   MachineFunction *F = MBB->getParent();
9961   MachineBasicBlock *thisMBB = MBB;
9962   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9963   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9964   F->insert(MBBIter, newMBB);
9965   F->insert(MBBIter, nextMBB);
9966
9967   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9968   nextMBB->splice(nextMBB->begin(), thisMBB,
9969                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9970                   thisMBB->end());
9971   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9972
9973   // Update thisMBB to fall through to newMBB
9974   thisMBB->addSuccessor(newMBB);
9975
9976   // newMBB jumps to newMBB and fall through to nextMBB
9977   newMBB->addSuccessor(nextMBB);
9978   newMBB->addSuccessor(newMBB);
9979
9980   DebugLoc dl = mInstr->getDebugLoc();
9981   // Insert instructions into newMBB based on incoming instruction
9982   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9983          "unexpected number of operands");
9984   MachineOperand& destOper = mInstr->getOperand(0);
9985   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9986   int numArgs = mInstr->getNumOperands() - 1;
9987   for (int i=0; i < numArgs; ++i)
9988     argOpers[i] = &mInstr->getOperand(i+1);
9989
9990   // x86 address has 4 operands: base, index, scale, and displacement
9991   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9992   int valArgIndx = lastAddrIndx + 1;
9993
9994   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9995   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9996   for (int i=0; i <= lastAddrIndx; ++i)
9997     (*MIB).addOperand(*argOpers[i]);
9998
9999   // We only support register and immediate values
10000   assert((argOpers[valArgIndx]->isReg() ||
10001           argOpers[valArgIndx]->isImm()) &&
10002          "invalid operand");
10003
10004   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10005   if (argOpers[valArgIndx]->isReg())
10006     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10007   else
10008     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10009   (*MIB).addOperand(*argOpers[valArgIndx]);
10010
10011   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10012   MIB.addReg(t1);
10013
10014   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10015   MIB.addReg(t1);
10016   MIB.addReg(t2);
10017
10018   // Generate movc
10019   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10020   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10021   MIB.addReg(t2);
10022   MIB.addReg(t1);
10023
10024   // Cmp and exchange if none has modified the memory location
10025   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10026   for (int i=0; i <= lastAddrIndx; ++i)
10027     (*MIB).addOperand(*argOpers[i]);
10028   MIB.addReg(t3);
10029   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10030   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10031                     mInstr->memoperands_end());
10032
10033   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10034   MIB.addReg(X86::EAX);
10035
10036   // insert branch
10037   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10038
10039   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10040   return nextMBB;
10041 }
10042
10043 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10044 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10045 // in the .td file.
10046 MachineBasicBlock *
10047 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10048                             unsigned numArgs, bool memArg) const {
10049   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10050          "Target must have SSE4.2 or AVX features enabled");
10051
10052   DebugLoc dl = MI->getDebugLoc();
10053   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10054   unsigned Opc;
10055   if (!Subtarget->hasAVX()) {
10056     if (memArg)
10057       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10058     else
10059       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10060   } else {
10061     if (memArg)
10062       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10063     else
10064       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10065   }
10066
10067   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10068   for (unsigned i = 0; i < numArgs; ++i) {
10069     MachineOperand &Op = MI->getOperand(i+1);
10070     if (!(Op.isReg() && Op.isImplicit()))
10071       MIB.addOperand(Op);
10072   }
10073   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10074     .addReg(X86::XMM0);
10075
10076   MI->eraseFromParent();
10077   return BB;
10078 }
10079
10080 MachineBasicBlock *
10081 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10082   DebugLoc dl = MI->getDebugLoc();
10083   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10084
10085   // Address into RAX/EAX, other two args into ECX, EDX.
10086   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10087   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10088   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10089   for (int i = 0; i < X86::AddrNumOperands; ++i)
10090     MIB.addOperand(MI->getOperand(i));
10091
10092   unsigned ValOps = X86::AddrNumOperands;
10093   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10094     .addReg(MI->getOperand(ValOps).getReg());
10095   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10096     .addReg(MI->getOperand(ValOps+1).getReg());
10097
10098   // The instruction doesn't actually take any operands though.
10099   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10100
10101   MI->eraseFromParent(); // The pseudo is gone now.
10102   return BB;
10103 }
10104
10105 MachineBasicBlock *
10106 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10107   DebugLoc dl = MI->getDebugLoc();
10108   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10109
10110   // First arg in ECX, the second in EAX.
10111   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10112     .addReg(MI->getOperand(0).getReg());
10113   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10114     .addReg(MI->getOperand(1).getReg());
10115
10116   // The instruction doesn't actually take any operands though.
10117   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10118
10119   MI->eraseFromParent(); // The pseudo is gone now.
10120   return BB;
10121 }
10122
10123 MachineBasicBlock *
10124 X86TargetLowering::EmitVAARG64WithCustomInserter(
10125                    MachineInstr *MI,
10126                    MachineBasicBlock *MBB) const {
10127   // Emit va_arg instruction on X86-64.
10128
10129   // Operands to this pseudo-instruction:
10130   // 0  ) Output        : destination address (reg)
10131   // 1-5) Input         : va_list address (addr, i64mem)
10132   // 6  ) ArgSize       : Size (in bytes) of vararg type
10133   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10134   // 8  ) Align         : Alignment of type
10135   // 9  ) EFLAGS (implicit-def)
10136
10137   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10138   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10139
10140   unsigned DestReg = MI->getOperand(0).getReg();
10141   MachineOperand &Base = MI->getOperand(1);
10142   MachineOperand &Scale = MI->getOperand(2);
10143   MachineOperand &Index = MI->getOperand(3);
10144   MachineOperand &Disp = MI->getOperand(4);
10145   MachineOperand &Segment = MI->getOperand(5);
10146   unsigned ArgSize = MI->getOperand(6).getImm();
10147   unsigned ArgMode = MI->getOperand(7).getImm();
10148   unsigned Align = MI->getOperand(8).getImm();
10149
10150   // Memory Reference
10151   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10152   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10153   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10154
10155   // Machine Information
10156   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10157   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10158   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10159   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10160   DebugLoc DL = MI->getDebugLoc();
10161
10162   // struct va_list {
10163   //   i32   gp_offset
10164   //   i32   fp_offset
10165   //   i64   overflow_area (address)
10166   //   i64   reg_save_area (address)
10167   // }
10168   // sizeof(va_list) = 24
10169   // alignment(va_list) = 8
10170
10171   unsigned TotalNumIntRegs = 6;
10172   unsigned TotalNumXMMRegs = 8;
10173   bool UseGPOffset = (ArgMode == 1);
10174   bool UseFPOffset = (ArgMode == 2);
10175   unsigned MaxOffset = TotalNumIntRegs * 8 +
10176                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10177
10178   /* Align ArgSize to a multiple of 8 */
10179   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10180   bool NeedsAlign = (Align > 8);
10181
10182   MachineBasicBlock *thisMBB = MBB;
10183   MachineBasicBlock *overflowMBB;
10184   MachineBasicBlock *offsetMBB;
10185   MachineBasicBlock *endMBB;
10186
10187   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10188   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10189   unsigned OffsetReg = 0;
10190
10191   if (!UseGPOffset && !UseFPOffset) {
10192     // If we only pull from the overflow region, we don't create a branch.
10193     // We don't need to alter control flow.
10194     OffsetDestReg = 0; // unused
10195     OverflowDestReg = DestReg;
10196
10197     offsetMBB = NULL;
10198     overflowMBB = thisMBB;
10199     endMBB = thisMBB;
10200   } else {
10201     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10202     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10203     // If not, pull from overflow_area. (branch to overflowMBB)
10204     //
10205     //       thisMBB
10206     //         |     .
10207     //         |        .
10208     //     offsetMBB   overflowMBB
10209     //         |        .
10210     //         |     .
10211     //        endMBB
10212
10213     // Registers for the PHI in endMBB
10214     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10215     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10216
10217     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10218     MachineFunction *MF = MBB->getParent();
10219     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10220     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10221     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10222
10223     MachineFunction::iterator MBBIter = MBB;
10224     ++MBBIter;
10225
10226     // Insert the new basic blocks
10227     MF->insert(MBBIter, offsetMBB);
10228     MF->insert(MBBIter, overflowMBB);
10229     MF->insert(MBBIter, endMBB);
10230
10231     // Transfer the remainder of MBB and its successor edges to endMBB.
10232     endMBB->splice(endMBB->begin(), thisMBB,
10233                     llvm::next(MachineBasicBlock::iterator(MI)),
10234                     thisMBB->end());
10235     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10236
10237     // Make offsetMBB and overflowMBB successors of thisMBB
10238     thisMBB->addSuccessor(offsetMBB);
10239     thisMBB->addSuccessor(overflowMBB);
10240
10241     // endMBB is a successor of both offsetMBB and overflowMBB
10242     offsetMBB->addSuccessor(endMBB);
10243     overflowMBB->addSuccessor(endMBB);
10244
10245     // Load the offset value into a register
10246     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10247     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10248       .addOperand(Base)
10249       .addOperand(Scale)
10250       .addOperand(Index)
10251       .addDisp(Disp, UseFPOffset ? 4 : 0)
10252       .addOperand(Segment)
10253       .setMemRefs(MMOBegin, MMOEnd);
10254
10255     // Check if there is enough room left to pull this argument.
10256     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10257       .addReg(OffsetReg)
10258       .addImm(MaxOffset + 8 - ArgSizeA8);
10259
10260     // Branch to "overflowMBB" if offset >= max
10261     // Fall through to "offsetMBB" otherwise
10262     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10263       .addMBB(overflowMBB);
10264   }
10265
10266   // In offsetMBB, emit code to use the reg_save_area.
10267   if (offsetMBB) {
10268     assert(OffsetReg != 0);
10269
10270     // Read the reg_save_area address.
10271     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10272     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10273       .addOperand(Base)
10274       .addOperand(Scale)
10275       .addOperand(Index)
10276       .addDisp(Disp, 16)
10277       .addOperand(Segment)
10278       .setMemRefs(MMOBegin, MMOEnd);
10279
10280     // Zero-extend the offset
10281     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10282       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10283         .addImm(0)
10284         .addReg(OffsetReg)
10285         .addImm(X86::sub_32bit);
10286
10287     // Add the offset to the reg_save_area to get the final address.
10288     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10289       .addReg(OffsetReg64)
10290       .addReg(RegSaveReg);
10291
10292     // Compute the offset for the next argument
10293     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10294     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10295       .addReg(OffsetReg)
10296       .addImm(UseFPOffset ? 16 : 8);
10297
10298     // Store it back into the va_list.
10299     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10300       .addOperand(Base)
10301       .addOperand(Scale)
10302       .addOperand(Index)
10303       .addDisp(Disp, UseFPOffset ? 4 : 0)
10304       .addOperand(Segment)
10305       .addReg(NextOffsetReg)
10306       .setMemRefs(MMOBegin, MMOEnd);
10307
10308     // Jump to endMBB
10309     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10310       .addMBB(endMBB);
10311   }
10312
10313   //
10314   // Emit code to use overflow area
10315   //
10316
10317   // Load the overflow_area address into a register.
10318   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10319   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10320     .addOperand(Base)
10321     .addOperand(Scale)
10322     .addOperand(Index)
10323     .addDisp(Disp, 8)
10324     .addOperand(Segment)
10325     .setMemRefs(MMOBegin, MMOEnd);
10326
10327   // If we need to align it, do so. Otherwise, just copy the address
10328   // to OverflowDestReg.
10329   if (NeedsAlign) {
10330     // Align the overflow address
10331     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10332     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10333
10334     // aligned_addr = (addr + (align-1)) & ~(align-1)
10335     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10336       .addReg(OverflowAddrReg)
10337       .addImm(Align-1);
10338
10339     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10340       .addReg(TmpReg)
10341       .addImm(~(uint64_t)(Align-1));
10342   } else {
10343     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10344       .addReg(OverflowAddrReg);
10345   }
10346
10347   // Compute the next overflow address after this argument.
10348   // (the overflow address should be kept 8-byte aligned)
10349   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10350   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10351     .addReg(OverflowDestReg)
10352     .addImm(ArgSizeA8);
10353
10354   // Store the new overflow address.
10355   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10356     .addOperand(Base)
10357     .addOperand(Scale)
10358     .addOperand(Index)
10359     .addDisp(Disp, 8)
10360     .addOperand(Segment)
10361     .addReg(NextAddrReg)
10362     .setMemRefs(MMOBegin, MMOEnd);
10363
10364   // If we branched, emit the PHI to the front of endMBB.
10365   if (offsetMBB) {
10366     BuildMI(*endMBB, endMBB->begin(), DL,
10367             TII->get(X86::PHI), DestReg)
10368       .addReg(OffsetDestReg).addMBB(offsetMBB)
10369       .addReg(OverflowDestReg).addMBB(overflowMBB);
10370   }
10371
10372   // Erase the pseudo instruction
10373   MI->eraseFromParent();
10374
10375   return endMBB;
10376 }
10377
10378 MachineBasicBlock *
10379 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10380                                                  MachineInstr *MI,
10381                                                  MachineBasicBlock *MBB) const {
10382   // Emit code to save XMM registers to the stack. The ABI says that the
10383   // number of registers to save is given in %al, so it's theoretically
10384   // possible to do an indirect jump trick to avoid saving all of them,
10385   // however this code takes a simpler approach and just executes all
10386   // of the stores if %al is non-zero. It's less code, and it's probably
10387   // easier on the hardware branch predictor, and stores aren't all that
10388   // expensive anyway.
10389
10390   // Create the new basic blocks. One block contains all the XMM stores,
10391   // and one block is the final destination regardless of whether any
10392   // stores were performed.
10393   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10394   MachineFunction *F = MBB->getParent();
10395   MachineFunction::iterator MBBIter = MBB;
10396   ++MBBIter;
10397   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10398   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10399   F->insert(MBBIter, XMMSaveMBB);
10400   F->insert(MBBIter, EndMBB);
10401
10402   // Transfer the remainder of MBB and its successor edges to EndMBB.
10403   EndMBB->splice(EndMBB->begin(), MBB,
10404                  llvm::next(MachineBasicBlock::iterator(MI)),
10405                  MBB->end());
10406   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10407
10408   // The original block will now fall through to the XMM save block.
10409   MBB->addSuccessor(XMMSaveMBB);
10410   // The XMMSaveMBB will fall through to the end block.
10411   XMMSaveMBB->addSuccessor(EndMBB);
10412
10413   // Now add the instructions.
10414   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10415   DebugLoc DL = MI->getDebugLoc();
10416
10417   unsigned CountReg = MI->getOperand(0).getReg();
10418   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10419   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10420
10421   if (!Subtarget->isTargetWin64()) {
10422     // If %al is 0, branch around the XMM save block.
10423     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10424     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10425     MBB->addSuccessor(EndMBB);
10426   }
10427
10428   // In the XMM save block, save all the XMM argument registers.
10429   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10430     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10431     MachineMemOperand *MMO =
10432       F->getMachineMemOperand(
10433           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10434         MachineMemOperand::MOStore,
10435         /*Size=*/16, /*Align=*/16);
10436     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10437       .addFrameIndex(RegSaveFrameIndex)
10438       .addImm(/*Scale=*/1)
10439       .addReg(/*IndexReg=*/0)
10440       .addImm(/*Disp=*/Offset)
10441       .addReg(/*Segment=*/0)
10442       .addReg(MI->getOperand(i).getReg())
10443       .addMemOperand(MMO);
10444   }
10445
10446   MI->eraseFromParent();   // The pseudo instruction is gone now.
10447
10448   return EndMBB;
10449 }
10450
10451 MachineBasicBlock *
10452 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10453                                      MachineBasicBlock *BB) const {
10454   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10455   DebugLoc DL = MI->getDebugLoc();
10456
10457   // To "insert" a SELECT_CC instruction, we actually have to insert the
10458   // diamond control-flow pattern.  The incoming instruction knows the
10459   // destination vreg to set, the condition code register to branch on, the
10460   // true/false values to select between, and a branch opcode to use.
10461   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10462   MachineFunction::iterator It = BB;
10463   ++It;
10464
10465   //  thisMBB:
10466   //  ...
10467   //   TrueVal = ...
10468   //   cmpTY ccX, r1, r2
10469   //   bCC copy1MBB
10470   //   fallthrough --> copy0MBB
10471   MachineBasicBlock *thisMBB = BB;
10472   MachineFunction *F = BB->getParent();
10473   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10474   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10475   F->insert(It, copy0MBB);
10476   F->insert(It, sinkMBB);
10477
10478   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10479   // live into the sink and copy blocks.
10480   const MachineFunction *MF = BB->getParent();
10481   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10482   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10483
10484   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10485     const MachineOperand &MO = MI->getOperand(I);
10486     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10487     unsigned Reg = MO.getReg();
10488     if (Reg != X86::EFLAGS) continue;
10489     copy0MBB->addLiveIn(Reg);
10490     sinkMBB->addLiveIn(Reg);
10491   }
10492
10493   // Transfer the remainder of BB and its successor edges to sinkMBB.
10494   sinkMBB->splice(sinkMBB->begin(), BB,
10495                   llvm::next(MachineBasicBlock::iterator(MI)),
10496                   BB->end());
10497   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10498
10499   // Add the true and fallthrough blocks as its successors.
10500   BB->addSuccessor(copy0MBB);
10501   BB->addSuccessor(sinkMBB);
10502
10503   // Create the conditional branch instruction.
10504   unsigned Opc =
10505     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10506   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10507
10508   //  copy0MBB:
10509   //   %FalseValue = ...
10510   //   # fallthrough to sinkMBB
10511   copy0MBB->addSuccessor(sinkMBB);
10512
10513   //  sinkMBB:
10514   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10515   //  ...
10516   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10517           TII->get(X86::PHI), MI->getOperand(0).getReg())
10518     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10519     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10520
10521   MI->eraseFromParent();   // The pseudo instruction is gone now.
10522   return sinkMBB;
10523 }
10524
10525 MachineBasicBlock *
10526 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10527                                           MachineBasicBlock *BB) const {
10528   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10529   DebugLoc DL = MI->getDebugLoc();
10530
10531   assert(!Subtarget->isTargetEnvMacho());
10532
10533   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10534   // non-trivial part is impdef of ESP.
10535
10536   if (Subtarget->isTargetWin64()) {
10537     if (Subtarget->isTargetCygMing()) {
10538       // ___chkstk(Mingw64):
10539       // Clobbers R10, R11, RAX and EFLAGS.
10540       // Updates RSP.
10541       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10542         .addExternalSymbol("___chkstk")
10543         .addReg(X86::RAX, RegState::Implicit)
10544         .addReg(X86::RSP, RegState::Implicit)
10545         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10546         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10547         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10548     } else {
10549       // __chkstk(MSVCRT): does not update stack pointer.
10550       // Clobbers R10, R11 and EFLAGS.
10551       // FIXME: RAX(allocated size) might be reused and not killed.
10552       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10553         .addExternalSymbol("__chkstk")
10554         .addReg(X86::RAX, RegState::Implicit)
10555         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10556       // RAX has the offset to subtracted from RSP.
10557       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10558         .addReg(X86::RSP)
10559         .addReg(X86::RAX);
10560     }
10561   } else {
10562     const char *StackProbeSymbol =
10563       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10564
10565     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10566       .addExternalSymbol(StackProbeSymbol)
10567       .addReg(X86::EAX, RegState::Implicit)
10568       .addReg(X86::ESP, RegState::Implicit)
10569       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10570       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10571       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10572   }
10573
10574   MI->eraseFromParent();   // The pseudo instruction is gone now.
10575   return BB;
10576 }
10577
10578 MachineBasicBlock *
10579 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10580                                       MachineBasicBlock *BB) const {
10581   // This is pretty easy.  We're taking the value that we received from
10582   // our load from the relocation, sticking it in either RDI (x86-64)
10583   // or EAX and doing an indirect call.  The return value will then
10584   // be in the normal return register.
10585   const X86InstrInfo *TII
10586     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10587   DebugLoc DL = MI->getDebugLoc();
10588   MachineFunction *F = BB->getParent();
10589
10590   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10591   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10592
10593   if (Subtarget->is64Bit()) {
10594     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10595                                       TII->get(X86::MOV64rm), X86::RDI)
10596     .addReg(X86::RIP)
10597     .addImm(0).addReg(0)
10598     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10599                       MI->getOperand(3).getTargetFlags())
10600     .addReg(0);
10601     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10602     addDirectMem(MIB, X86::RDI);
10603   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10604     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10605                                       TII->get(X86::MOV32rm), X86::EAX)
10606     .addReg(0)
10607     .addImm(0).addReg(0)
10608     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10609                       MI->getOperand(3).getTargetFlags())
10610     .addReg(0);
10611     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10612     addDirectMem(MIB, X86::EAX);
10613   } else {
10614     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10615                                       TII->get(X86::MOV32rm), X86::EAX)
10616     .addReg(TII->getGlobalBaseReg(F))
10617     .addImm(0).addReg(0)
10618     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10619                       MI->getOperand(3).getTargetFlags())
10620     .addReg(0);
10621     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10622     addDirectMem(MIB, X86::EAX);
10623   }
10624
10625   MI->eraseFromParent(); // The pseudo instruction is gone now.
10626   return BB;
10627 }
10628
10629 MachineBasicBlock *
10630 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10631                                                MachineBasicBlock *BB) const {
10632   switch (MI->getOpcode()) {
10633   default: assert(false && "Unexpected instr type to insert");
10634   case X86::TAILJMPd64:
10635   case X86::TAILJMPr64:
10636   case X86::TAILJMPm64:
10637     assert(!"TAILJMP64 would not be touched here.");
10638   case X86::TCRETURNdi64:
10639   case X86::TCRETURNri64:
10640   case X86::TCRETURNmi64:
10641     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10642     // On AMD64, additional defs should be added before register allocation.
10643     if (!Subtarget->isTargetWin64()) {
10644       MI->addRegisterDefined(X86::RSI);
10645       MI->addRegisterDefined(X86::RDI);
10646       MI->addRegisterDefined(X86::XMM6);
10647       MI->addRegisterDefined(X86::XMM7);
10648       MI->addRegisterDefined(X86::XMM8);
10649       MI->addRegisterDefined(X86::XMM9);
10650       MI->addRegisterDefined(X86::XMM10);
10651       MI->addRegisterDefined(X86::XMM11);
10652       MI->addRegisterDefined(X86::XMM12);
10653       MI->addRegisterDefined(X86::XMM13);
10654       MI->addRegisterDefined(X86::XMM14);
10655       MI->addRegisterDefined(X86::XMM15);
10656     }
10657     return BB;
10658   case X86::WIN_ALLOCA:
10659     return EmitLoweredWinAlloca(MI, BB);
10660   case X86::TLSCall_32:
10661   case X86::TLSCall_64:
10662     return EmitLoweredTLSCall(MI, BB);
10663   case X86::CMOV_GR8:
10664   case X86::CMOV_FR32:
10665   case X86::CMOV_FR64:
10666   case X86::CMOV_V4F32:
10667   case X86::CMOV_V2F64:
10668   case X86::CMOV_V2I64:
10669   case X86::CMOV_GR16:
10670   case X86::CMOV_GR32:
10671   case X86::CMOV_RFP32:
10672   case X86::CMOV_RFP64:
10673   case X86::CMOV_RFP80:
10674     return EmitLoweredSelect(MI, BB);
10675
10676   case X86::FP32_TO_INT16_IN_MEM:
10677   case X86::FP32_TO_INT32_IN_MEM:
10678   case X86::FP32_TO_INT64_IN_MEM:
10679   case X86::FP64_TO_INT16_IN_MEM:
10680   case X86::FP64_TO_INT32_IN_MEM:
10681   case X86::FP64_TO_INT64_IN_MEM:
10682   case X86::FP80_TO_INT16_IN_MEM:
10683   case X86::FP80_TO_INT32_IN_MEM:
10684   case X86::FP80_TO_INT64_IN_MEM: {
10685     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10686     DebugLoc DL = MI->getDebugLoc();
10687
10688     // Change the floating point control register to use "round towards zero"
10689     // mode when truncating to an integer value.
10690     MachineFunction *F = BB->getParent();
10691     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10692     addFrameReference(BuildMI(*BB, MI, DL,
10693                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10694
10695     // Load the old value of the high byte of the control word...
10696     unsigned OldCW =
10697       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10698     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10699                       CWFrameIdx);
10700
10701     // Set the high part to be round to zero...
10702     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10703       .addImm(0xC7F);
10704
10705     // Reload the modified control word now...
10706     addFrameReference(BuildMI(*BB, MI, DL,
10707                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10708
10709     // Restore the memory image of control word to original value
10710     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10711       .addReg(OldCW);
10712
10713     // Get the X86 opcode to use.
10714     unsigned Opc;
10715     switch (MI->getOpcode()) {
10716     default: llvm_unreachable("illegal opcode!");
10717     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10718     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10719     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10720     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10721     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10722     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10723     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10724     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10725     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10726     }
10727
10728     X86AddressMode AM;
10729     MachineOperand &Op = MI->getOperand(0);
10730     if (Op.isReg()) {
10731       AM.BaseType = X86AddressMode::RegBase;
10732       AM.Base.Reg = Op.getReg();
10733     } else {
10734       AM.BaseType = X86AddressMode::FrameIndexBase;
10735       AM.Base.FrameIndex = Op.getIndex();
10736     }
10737     Op = MI->getOperand(1);
10738     if (Op.isImm())
10739       AM.Scale = Op.getImm();
10740     Op = MI->getOperand(2);
10741     if (Op.isImm())
10742       AM.IndexReg = Op.getImm();
10743     Op = MI->getOperand(3);
10744     if (Op.isGlobal()) {
10745       AM.GV = Op.getGlobal();
10746     } else {
10747       AM.Disp = Op.getImm();
10748     }
10749     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10750                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10751
10752     // Reload the original control word now.
10753     addFrameReference(BuildMI(*BB, MI, DL,
10754                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10755
10756     MI->eraseFromParent();   // The pseudo instruction is gone now.
10757     return BB;
10758   }
10759     // String/text processing lowering.
10760   case X86::PCMPISTRM128REG:
10761   case X86::VPCMPISTRM128REG:
10762     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10763   case X86::PCMPISTRM128MEM:
10764   case X86::VPCMPISTRM128MEM:
10765     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10766   case X86::PCMPESTRM128REG:
10767   case X86::VPCMPESTRM128REG:
10768     return EmitPCMP(MI, BB, 5, false /* in mem */);
10769   case X86::PCMPESTRM128MEM:
10770   case X86::VPCMPESTRM128MEM:
10771     return EmitPCMP(MI, BB, 5, true /* in mem */);
10772
10773     // Thread synchronization.
10774   case X86::MONITOR:
10775     return EmitMonitor(MI, BB);
10776   case X86::MWAIT:
10777     return EmitMwait(MI, BB);
10778
10779     // Atomic Lowering.
10780   case X86::ATOMAND32:
10781     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10782                                                X86::AND32ri, X86::MOV32rm,
10783                                                X86::LCMPXCHG32,
10784                                                X86::NOT32r, X86::EAX,
10785                                                X86::GR32RegisterClass);
10786   case X86::ATOMOR32:
10787     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10788                                                X86::OR32ri, X86::MOV32rm,
10789                                                X86::LCMPXCHG32,
10790                                                X86::NOT32r, X86::EAX,
10791                                                X86::GR32RegisterClass);
10792   case X86::ATOMXOR32:
10793     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10794                                                X86::XOR32ri, X86::MOV32rm,
10795                                                X86::LCMPXCHG32,
10796                                                X86::NOT32r, X86::EAX,
10797                                                X86::GR32RegisterClass);
10798   case X86::ATOMNAND32:
10799     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10800                                                X86::AND32ri, X86::MOV32rm,
10801                                                X86::LCMPXCHG32,
10802                                                X86::NOT32r, X86::EAX,
10803                                                X86::GR32RegisterClass, true);
10804   case X86::ATOMMIN32:
10805     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10806   case X86::ATOMMAX32:
10807     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10808   case X86::ATOMUMIN32:
10809     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10810   case X86::ATOMUMAX32:
10811     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10812
10813   case X86::ATOMAND16:
10814     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10815                                                X86::AND16ri, X86::MOV16rm,
10816                                                X86::LCMPXCHG16,
10817                                                X86::NOT16r, X86::AX,
10818                                                X86::GR16RegisterClass);
10819   case X86::ATOMOR16:
10820     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10821                                                X86::OR16ri, X86::MOV16rm,
10822                                                X86::LCMPXCHG16,
10823                                                X86::NOT16r, X86::AX,
10824                                                X86::GR16RegisterClass);
10825   case X86::ATOMXOR16:
10826     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10827                                                X86::XOR16ri, X86::MOV16rm,
10828                                                X86::LCMPXCHG16,
10829                                                X86::NOT16r, X86::AX,
10830                                                X86::GR16RegisterClass);
10831   case X86::ATOMNAND16:
10832     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10833                                                X86::AND16ri, X86::MOV16rm,
10834                                                X86::LCMPXCHG16,
10835                                                X86::NOT16r, X86::AX,
10836                                                X86::GR16RegisterClass, true);
10837   case X86::ATOMMIN16:
10838     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10839   case X86::ATOMMAX16:
10840     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10841   case X86::ATOMUMIN16:
10842     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10843   case X86::ATOMUMAX16:
10844     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10845
10846   case X86::ATOMAND8:
10847     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10848                                                X86::AND8ri, X86::MOV8rm,
10849                                                X86::LCMPXCHG8,
10850                                                X86::NOT8r, X86::AL,
10851                                                X86::GR8RegisterClass);
10852   case X86::ATOMOR8:
10853     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10854                                                X86::OR8ri, X86::MOV8rm,
10855                                                X86::LCMPXCHG8,
10856                                                X86::NOT8r, X86::AL,
10857                                                X86::GR8RegisterClass);
10858   case X86::ATOMXOR8:
10859     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10860                                                X86::XOR8ri, X86::MOV8rm,
10861                                                X86::LCMPXCHG8,
10862                                                X86::NOT8r, X86::AL,
10863                                                X86::GR8RegisterClass);
10864   case X86::ATOMNAND8:
10865     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10866                                                X86::AND8ri, X86::MOV8rm,
10867                                                X86::LCMPXCHG8,
10868                                                X86::NOT8r, X86::AL,
10869                                                X86::GR8RegisterClass, true);
10870   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10871   // This group is for 64-bit host.
10872   case X86::ATOMAND64:
10873     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10874                                                X86::AND64ri32, X86::MOV64rm,
10875                                                X86::LCMPXCHG64,
10876                                                X86::NOT64r, X86::RAX,
10877                                                X86::GR64RegisterClass);
10878   case X86::ATOMOR64:
10879     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10880                                                X86::OR64ri32, X86::MOV64rm,
10881                                                X86::LCMPXCHG64,
10882                                                X86::NOT64r, X86::RAX,
10883                                                X86::GR64RegisterClass);
10884   case X86::ATOMXOR64:
10885     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10886                                                X86::XOR64ri32, X86::MOV64rm,
10887                                                X86::LCMPXCHG64,
10888                                                X86::NOT64r, X86::RAX,
10889                                                X86::GR64RegisterClass);
10890   case X86::ATOMNAND64:
10891     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10892                                                X86::AND64ri32, X86::MOV64rm,
10893                                                X86::LCMPXCHG64,
10894                                                X86::NOT64r, X86::RAX,
10895                                                X86::GR64RegisterClass, true);
10896   case X86::ATOMMIN64:
10897     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10898   case X86::ATOMMAX64:
10899     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10900   case X86::ATOMUMIN64:
10901     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10902   case X86::ATOMUMAX64:
10903     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10904
10905   // This group does 64-bit operations on a 32-bit host.
10906   case X86::ATOMAND6432:
10907     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10908                                                X86::AND32rr, X86::AND32rr,
10909                                                X86::AND32ri, X86::AND32ri,
10910                                                false);
10911   case X86::ATOMOR6432:
10912     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10913                                                X86::OR32rr, X86::OR32rr,
10914                                                X86::OR32ri, X86::OR32ri,
10915                                                false);
10916   case X86::ATOMXOR6432:
10917     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10918                                                X86::XOR32rr, X86::XOR32rr,
10919                                                X86::XOR32ri, X86::XOR32ri,
10920                                                false);
10921   case X86::ATOMNAND6432:
10922     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10923                                                X86::AND32rr, X86::AND32rr,
10924                                                X86::AND32ri, X86::AND32ri,
10925                                                true);
10926   case X86::ATOMADD6432:
10927     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10928                                                X86::ADD32rr, X86::ADC32rr,
10929                                                X86::ADD32ri, X86::ADC32ri,
10930                                                false);
10931   case X86::ATOMSUB6432:
10932     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10933                                                X86::SUB32rr, X86::SBB32rr,
10934                                                X86::SUB32ri, X86::SBB32ri,
10935                                                false);
10936   case X86::ATOMSWAP6432:
10937     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10938                                                X86::MOV32rr, X86::MOV32rr,
10939                                                X86::MOV32ri, X86::MOV32ri,
10940                                                false);
10941   case X86::VASTART_SAVE_XMM_REGS:
10942     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10943
10944   case X86::VAARG_64:
10945     return EmitVAARG64WithCustomInserter(MI, BB);
10946   }
10947 }
10948
10949 //===----------------------------------------------------------------------===//
10950 //                           X86 Optimization Hooks
10951 //===----------------------------------------------------------------------===//
10952
10953 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10954                                                        const APInt &Mask,
10955                                                        APInt &KnownZero,
10956                                                        APInt &KnownOne,
10957                                                        const SelectionDAG &DAG,
10958                                                        unsigned Depth) const {
10959   unsigned Opc = Op.getOpcode();
10960   assert((Opc >= ISD::BUILTIN_OP_END ||
10961           Opc == ISD::INTRINSIC_WO_CHAIN ||
10962           Opc == ISD::INTRINSIC_W_CHAIN ||
10963           Opc == ISD::INTRINSIC_VOID) &&
10964          "Should use MaskedValueIsZero if you don't know whether Op"
10965          " is a target node!");
10966
10967   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10968   switch (Opc) {
10969   default: break;
10970   case X86ISD::ADD:
10971   case X86ISD::SUB:
10972   case X86ISD::ADC:
10973   case X86ISD::SBB:
10974   case X86ISD::SMUL:
10975   case X86ISD::UMUL:
10976   case X86ISD::INC:
10977   case X86ISD::DEC:
10978   case X86ISD::OR:
10979   case X86ISD::XOR:
10980   case X86ISD::AND:
10981     // These nodes' second result is a boolean.
10982     if (Op.getResNo() == 0)
10983       break;
10984     // Fallthrough
10985   case X86ISD::SETCC:
10986     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10987                                        Mask.getBitWidth() - 1);
10988     break;
10989   }
10990 }
10991
10992 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10993                                                          unsigned Depth) const {
10994   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10995   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10996     return Op.getValueType().getScalarType().getSizeInBits();
10997
10998   // Fallback case.
10999   return 1;
11000 }
11001
11002 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11003 /// node is a GlobalAddress + offset.
11004 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11005                                        const GlobalValue* &GA,
11006                                        int64_t &Offset) const {
11007   if (N->getOpcode() == X86ISD::Wrapper) {
11008     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11009       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11010       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11011       return true;
11012     }
11013   }
11014   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11015 }
11016
11017 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11018 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11019 /// if the load addresses are consecutive, non-overlapping, and in the right
11020 /// order.
11021 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11022                                      TargetLowering::DAGCombinerInfo &DCI) {
11023   DebugLoc dl = N->getDebugLoc();
11024   EVT VT = N->getValueType(0);
11025
11026   if (VT.getSizeInBits() != 128)
11027     return SDValue();
11028
11029   // Don't create instructions with illegal types after legalize types has run.
11030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11031   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11032     return SDValue();
11033
11034   SmallVector<SDValue, 16> Elts;
11035   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11036     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11037
11038   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11039 }
11040
11041 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11042 /// generation and convert it from being a bunch of shuffles and extracts
11043 /// to a simple store and scalar loads to extract the elements.
11044 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11045                                                 const TargetLowering &TLI) {
11046   SDValue InputVector = N->getOperand(0);
11047
11048   // Only operate on vectors of 4 elements, where the alternative shuffling
11049   // gets to be more expensive.
11050   if (InputVector.getValueType() != MVT::v4i32)
11051     return SDValue();
11052
11053   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11054   // single use which is a sign-extend or zero-extend, and all elements are
11055   // used.
11056   SmallVector<SDNode *, 4> Uses;
11057   unsigned ExtractedElements = 0;
11058   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11059        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11060     if (UI.getUse().getResNo() != InputVector.getResNo())
11061       return SDValue();
11062
11063     SDNode *Extract = *UI;
11064     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11065       return SDValue();
11066
11067     if (Extract->getValueType(0) != MVT::i32)
11068       return SDValue();
11069     if (!Extract->hasOneUse())
11070       return SDValue();
11071     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11072         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11073       return SDValue();
11074     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11075       return SDValue();
11076
11077     // Record which element was extracted.
11078     ExtractedElements |=
11079       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11080
11081     Uses.push_back(Extract);
11082   }
11083
11084   // If not all the elements were used, this may not be worthwhile.
11085   if (ExtractedElements != 15)
11086     return SDValue();
11087
11088   // Ok, we've now decided to do the transformation.
11089   DebugLoc dl = InputVector.getDebugLoc();
11090
11091   // Store the value to a temporary stack slot.
11092   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11093   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11094                             MachinePointerInfo(), false, false, 0);
11095
11096   // Replace each use (extract) with a load of the appropriate element.
11097   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11098        UE = Uses.end(); UI != UE; ++UI) {
11099     SDNode *Extract = *UI;
11100
11101     // cOMpute the element's address.
11102     SDValue Idx = Extract->getOperand(1);
11103     unsigned EltSize =
11104         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11105     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11106     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11107
11108     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11109                                      StackPtr, OffsetVal);
11110
11111     // Load the scalar.
11112     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11113                                      ScalarAddr, MachinePointerInfo(),
11114                                      false, false, 0);
11115
11116     // Replace the exact with the load.
11117     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11118   }
11119
11120   // The replacement was made in place; don't return anything.
11121   return SDValue();
11122 }
11123
11124 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11125 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11126                                     const X86Subtarget *Subtarget) {
11127   DebugLoc DL = N->getDebugLoc();
11128   SDValue Cond = N->getOperand(0);
11129   // Get the LHS/RHS of the select.
11130   SDValue LHS = N->getOperand(1);
11131   SDValue RHS = N->getOperand(2);
11132
11133   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11134   // instructions match the semantics of the common C idiom x<y?x:y but not
11135   // x<=y?x:y, because of how they handle negative zero (which can be
11136   // ignored in unsafe-math mode).
11137   if (Subtarget->hasSSE2() &&
11138       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11139       Cond.getOpcode() == ISD::SETCC) {
11140     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11141
11142     unsigned Opcode = 0;
11143     // Check for x CC y ? x : y.
11144     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11145         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11146       switch (CC) {
11147       default: break;
11148       case ISD::SETULT:
11149         // Converting this to a min would handle NaNs incorrectly, and swapping
11150         // the operands would cause it to handle comparisons between positive
11151         // and negative zero incorrectly.
11152         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11153           if (!UnsafeFPMath &&
11154               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11155             break;
11156           std::swap(LHS, RHS);
11157         }
11158         Opcode = X86ISD::FMIN;
11159         break;
11160       case ISD::SETOLE:
11161         // Converting this to a min would handle comparisons between positive
11162         // and negative zero incorrectly.
11163         if (!UnsafeFPMath &&
11164             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11165           break;
11166         Opcode = X86ISD::FMIN;
11167         break;
11168       case ISD::SETULE:
11169         // Converting this to a min would handle both negative zeros and NaNs
11170         // incorrectly, but we can swap the operands to fix both.
11171         std::swap(LHS, RHS);
11172       case ISD::SETOLT:
11173       case ISD::SETLT:
11174       case ISD::SETLE:
11175         Opcode = X86ISD::FMIN;
11176         break;
11177
11178       case ISD::SETOGE:
11179         // Converting this to a max would handle comparisons between positive
11180         // and negative zero incorrectly.
11181         if (!UnsafeFPMath &&
11182             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11183           break;
11184         Opcode = X86ISD::FMAX;
11185         break;
11186       case ISD::SETUGT:
11187         // Converting this to a max would handle NaNs incorrectly, and swapping
11188         // the operands would cause it to handle comparisons between positive
11189         // and negative zero incorrectly.
11190         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11191           if (!UnsafeFPMath &&
11192               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11193             break;
11194           std::swap(LHS, RHS);
11195         }
11196         Opcode = X86ISD::FMAX;
11197         break;
11198       case ISD::SETUGE:
11199         // Converting this to a max would handle both negative zeros and NaNs
11200         // incorrectly, but we can swap the operands to fix both.
11201         std::swap(LHS, RHS);
11202       case ISD::SETOGT:
11203       case ISD::SETGT:
11204       case ISD::SETGE:
11205         Opcode = X86ISD::FMAX;
11206         break;
11207       }
11208     // Check for x CC y ? y : x -- a min/max with reversed arms.
11209     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11210                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11211       switch (CC) {
11212       default: break;
11213       case ISD::SETOGE:
11214         // Converting this to a min would handle comparisons between positive
11215         // and negative zero incorrectly, and swapping the operands would
11216         // cause it to handle NaNs incorrectly.
11217         if (!UnsafeFPMath &&
11218             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11219           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11220             break;
11221           std::swap(LHS, RHS);
11222         }
11223         Opcode = X86ISD::FMIN;
11224         break;
11225       case ISD::SETUGT:
11226         // Converting this to a min would handle NaNs incorrectly.
11227         if (!UnsafeFPMath &&
11228             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11229           break;
11230         Opcode = X86ISD::FMIN;
11231         break;
11232       case ISD::SETUGE:
11233         // Converting this to a min would handle both negative zeros and NaNs
11234         // incorrectly, but we can swap the operands to fix both.
11235         std::swap(LHS, RHS);
11236       case ISD::SETOGT:
11237       case ISD::SETGT:
11238       case ISD::SETGE:
11239         Opcode = X86ISD::FMIN;
11240         break;
11241
11242       case ISD::SETULT:
11243         // Converting this to a max would handle NaNs incorrectly.
11244         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11245           break;
11246         Opcode = X86ISD::FMAX;
11247         break;
11248       case ISD::SETOLE:
11249         // Converting this to a max would handle comparisons between positive
11250         // and negative zero incorrectly, and swapping the operands would
11251         // cause it to handle NaNs incorrectly.
11252         if (!UnsafeFPMath &&
11253             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11254           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11255             break;
11256           std::swap(LHS, RHS);
11257         }
11258         Opcode = X86ISD::FMAX;
11259         break;
11260       case ISD::SETULE:
11261         // Converting this to a max would handle both negative zeros and NaNs
11262         // incorrectly, but we can swap the operands to fix both.
11263         std::swap(LHS, RHS);
11264       case ISD::SETOLT:
11265       case ISD::SETLT:
11266       case ISD::SETLE:
11267         Opcode = X86ISD::FMAX;
11268         break;
11269       }
11270     }
11271
11272     if (Opcode)
11273       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11274   }
11275
11276   // If this is a select between two integer constants, try to do some
11277   // optimizations.
11278   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11279     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11280       // Don't do this for crazy integer types.
11281       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11282         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11283         // so that TrueC (the true value) is larger than FalseC.
11284         bool NeedsCondInvert = false;
11285
11286         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11287             // Efficiently invertible.
11288             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11289              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11290               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11291           NeedsCondInvert = true;
11292           std::swap(TrueC, FalseC);
11293         }
11294
11295         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11296         if (FalseC->getAPIntValue() == 0 &&
11297             TrueC->getAPIntValue().isPowerOf2()) {
11298           if (NeedsCondInvert) // Invert the condition if needed.
11299             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11300                                DAG.getConstant(1, Cond.getValueType()));
11301
11302           // Zero extend the condition if needed.
11303           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11304
11305           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11306           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11307                              DAG.getConstant(ShAmt, MVT::i8));
11308         }
11309
11310         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11311         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11312           if (NeedsCondInvert) // Invert the condition if needed.
11313             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11314                                DAG.getConstant(1, Cond.getValueType()));
11315
11316           // Zero extend the condition if needed.
11317           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11318                              FalseC->getValueType(0), Cond);
11319           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11320                              SDValue(FalseC, 0));
11321         }
11322
11323         // Optimize cases that will turn into an LEA instruction.  This requires
11324         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11325         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11326           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11327           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11328
11329           bool isFastMultiplier = false;
11330           if (Diff < 10) {
11331             switch ((unsigned char)Diff) {
11332               default: break;
11333               case 1:  // result = add base, cond
11334               case 2:  // result = lea base(    , cond*2)
11335               case 3:  // result = lea base(cond, cond*2)
11336               case 4:  // result = lea base(    , cond*4)
11337               case 5:  // result = lea base(cond, cond*4)
11338               case 8:  // result = lea base(    , cond*8)
11339               case 9:  // result = lea base(cond, cond*8)
11340                 isFastMultiplier = true;
11341                 break;
11342             }
11343           }
11344
11345           if (isFastMultiplier) {
11346             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11347             if (NeedsCondInvert) // Invert the condition if needed.
11348               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11349                                  DAG.getConstant(1, Cond.getValueType()));
11350
11351             // Zero extend the condition if needed.
11352             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11353                                Cond);
11354             // Scale the condition by the difference.
11355             if (Diff != 1)
11356               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11357                                  DAG.getConstant(Diff, Cond.getValueType()));
11358
11359             // Add the base if non-zero.
11360             if (FalseC->getAPIntValue() != 0)
11361               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11362                                  SDValue(FalseC, 0));
11363             return Cond;
11364           }
11365         }
11366       }
11367   }
11368
11369   return SDValue();
11370 }
11371
11372 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11373 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11374                                   TargetLowering::DAGCombinerInfo &DCI) {
11375   DebugLoc DL = N->getDebugLoc();
11376
11377   // If the flag operand isn't dead, don't touch this CMOV.
11378   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11379     return SDValue();
11380
11381   SDValue FalseOp = N->getOperand(0);
11382   SDValue TrueOp = N->getOperand(1);
11383   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11384   SDValue Cond = N->getOperand(3);
11385   if (CC == X86::COND_E || CC == X86::COND_NE) {
11386     switch (Cond.getOpcode()) {
11387     default: break;
11388     case X86ISD::BSR:
11389     case X86ISD::BSF:
11390       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11391       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11392         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11393     }
11394   }
11395
11396   // If this is a select between two integer constants, try to do some
11397   // optimizations.  Note that the operands are ordered the opposite of SELECT
11398   // operands.
11399   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11400     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11401       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11402       // larger than FalseC (the false value).
11403       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11404         CC = X86::GetOppositeBranchCondition(CC);
11405         std::swap(TrueC, FalseC);
11406       }
11407
11408       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11409       // This is efficient for any integer data type (including i8/i16) and
11410       // shift amount.
11411       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11412         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11413                            DAG.getConstant(CC, MVT::i8), Cond);
11414
11415         // Zero extend the condition if needed.
11416         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11417
11418         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11419         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11420                            DAG.getConstant(ShAmt, MVT::i8));
11421         if (N->getNumValues() == 2)  // Dead flag value?
11422           return DCI.CombineTo(N, Cond, SDValue());
11423         return Cond;
11424       }
11425
11426       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11427       // for any integer data type, including i8/i16.
11428       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11429         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11430                            DAG.getConstant(CC, MVT::i8), Cond);
11431
11432         // Zero extend the condition if needed.
11433         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11434                            FalseC->getValueType(0), Cond);
11435         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11436                            SDValue(FalseC, 0));
11437
11438         if (N->getNumValues() == 2)  // Dead flag value?
11439           return DCI.CombineTo(N, Cond, SDValue());
11440         return Cond;
11441       }
11442
11443       // Optimize cases that will turn into an LEA instruction.  This requires
11444       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11445       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11446         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11447         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11448
11449         bool isFastMultiplier = false;
11450         if (Diff < 10) {
11451           switch ((unsigned char)Diff) {
11452           default: break;
11453           case 1:  // result = add base, cond
11454           case 2:  // result = lea base(    , cond*2)
11455           case 3:  // result = lea base(cond, cond*2)
11456           case 4:  // result = lea base(    , cond*4)
11457           case 5:  // result = lea base(cond, cond*4)
11458           case 8:  // result = lea base(    , cond*8)
11459           case 9:  // result = lea base(cond, cond*8)
11460             isFastMultiplier = true;
11461             break;
11462           }
11463         }
11464
11465         if (isFastMultiplier) {
11466           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11467           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11468                              DAG.getConstant(CC, MVT::i8), Cond);
11469           // Zero extend the condition if needed.
11470           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11471                              Cond);
11472           // Scale the condition by the difference.
11473           if (Diff != 1)
11474             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11475                                DAG.getConstant(Diff, Cond.getValueType()));
11476
11477           // Add the base if non-zero.
11478           if (FalseC->getAPIntValue() != 0)
11479             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11480                                SDValue(FalseC, 0));
11481           if (N->getNumValues() == 2)  // Dead flag value?
11482             return DCI.CombineTo(N, Cond, SDValue());
11483           return Cond;
11484         }
11485       }
11486     }
11487   }
11488   return SDValue();
11489 }
11490
11491
11492 /// PerformMulCombine - Optimize a single multiply with constant into two
11493 /// in order to implement it with two cheaper instructions, e.g.
11494 /// LEA + SHL, LEA + LEA.
11495 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11496                                  TargetLowering::DAGCombinerInfo &DCI) {
11497   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11498     return SDValue();
11499
11500   EVT VT = N->getValueType(0);
11501   if (VT != MVT::i64)
11502     return SDValue();
11503
11504   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11505   if (!C)
11506     return SDValue();
11507   uint64_t MulAmt = C->getZExtValue();
11508   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11509     return SDValue();
11510
11511   uint64_t MulAmt1 = 0;
11512   uint64_t MulAmt2 = 0;
11513   if ((MulAmt % 9) == 0) {
11514     MulAmt1 = 9;
11515     MulAmt2 = MulAmt / 9;
11516   } else if ((MulAmt % 5) == 0) {
11517     MulAmt1 = 5;
11518     MulAmt2 = MulAmt / 5;
11519   } else if ((MulAmt % 3) == 0) {
11520     MulAmt1 = 3;
11521     MulAmt2 = MulAmt / 3;
11522   }
11523   if (MulAmt2 &&
11524       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11525     DebugLoc DL = N->getDebugLoc();
11526
11527     if (isPowerOf2_64(MulAmt2) &&
11528         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11529       // If second multiplifer is pow2, issue it first. We want the multiply by
11530       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11531       // is an add.
11532       std::swap(MulAmt1, MulAmt2);
11533
11534     SDValue NewMul;
11535     if (isPowerOf2_64(MulAmt1))
11536       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11537                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11538     else
11539       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11540                            DAG.getConstant(MulAmt1, VT));
11541
11542     if (isPowerOf2_64(MulAmt2))
11543       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11544                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11545     else
11546       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11547                            DAG.getConstant(MulAmt2, VT));
11548
11549     // Do not add new nodes to DAG combiner worklist.
11550     DCI.CombineTo(N, NewMul, false);
11551   }
11552   return SDValue();
11553 }
11554
11555 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11556   SDValue N0 = N->getOperand(0);
11557   SDValue N1 = N->getOperand(1);
11558   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11559   EVT VT = N0.getValueType();
11560
11561   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11562   // since the result of setcc_c is all zero's or all ones.
11563   if (N1C && N0.getOpcode() == ISD::AND &&
11564       N0.getOperand(1).getOpcode() == ISD::Constant) {
11565     SDValue N00 = N0.getOperand(0);
11566     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11567         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11568           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11569          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11570       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11571       APInt ShAmt = N1C->getAPIntValue();
11572       Mask = Mask.shl(ShAmt);
11573       if (Mask != 0)
11574         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11575                            N00, DAG.getConstant(Mask, VT));
11576     }
11577   }
11578
11579   return SDValue();
11580 }
11581
11582 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11583 ///                       when possible.
11584 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11585                                    const X86Subtarget *Subtarget) {
11586   EVT VT = N->getValueType(0);
11587   if (!VT.isVector() && VT.isInteger() &&
11588       N->getOpcode() == ISD::SHL)
11589     return PerformSHLCombine(N, DAG);
11590
11591   // On X86 with SSE2 support, we can transform this to a vector shift if
11592   // all elements are shifted by the same amount.  We can't do this in legalize
11593   // because the a constant vector is typically transformed to a constant pool
11594   // so we have no knowledge of the shift amount.
11595   if (!Subtarget->hasSSE2())
11596     return SDValue();
11597
11598   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11599     return SDValue();
11600
11601   SDValue ShAmtOp = N->getOperand(1);
11602   EVT EltVT = VT.getVectorElementType();
11603   DebugLoc DL = N->getDebugLoc();
11604   SDValue BaseShAmt = SDValue();
11605   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11606     unsigned NumElts = VT.getVectorNumElements();
11607     unsigned i = 0;
11608     for (; i != NumElts; ++i) {
11609       SDValue Arg = ShAmtOp.getOperand(i);
11610       if (Arg.getOpcode() == ISD::UNDEF) continue;
11611       BaseShAmt = Arg;
11612       break;
11613     }
11614     for (; i != NumElts; ++i) {
11615       SDValue Arg = ShAmtOp.getOperand(i);
11616       if (Arg.getOpcode() == ISD::UNDEF) continue;
11617       if (Arg != BaseShAmt) {
11618         return SDValue();
11619       }
11620     }
11621   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11622              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11623     SDValue InVec = ShAmtOp.getOperand(0);
11624     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11625       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11626       unsigned i = 0;
11627       for (; i != NumElts; ++i) {
11628         SDValue Arg = InVec.getOperand(i);
11629         if (Arg.getOpcode() == ISD::UNDEF) continue;
11630         BaseShAmt = Arg;
11631         break;
11632       }
11633     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11634        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11635          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11636          if (C->getZExtValue() == SplatIdx)
11637            BaseShAmt = InVec.getOperand(1);
11638        }
11639     }
11640     if (BaseShAmt.getNode() == 0)
11641       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11642                               DAG.getIntPtrConstant(0));
11643   } else
11644     return SDValue();
11645
11646   // The shift amount is an i32.
11647   if (EltVT.bitsGT(MVT::i32))
11648     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11649   else if (EltVT.bitsLT(MVT::i32))
11650     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11651
11652   // The shift amount is identical so we can do a vector shift.
11653   SDValue  ValOp = N->getOperand(0);
11654   switch (N->getOpcode()) {
11655   default:
11656     llvm_unreachable("Unknown shift opcode!");
11657     break;
11658   case ISD::SHL:
11659     if (VT == MVT::v2i64)
11660       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11661                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11662                          ValOp, BaseShAmt);
11663     if (VT == MVT::v4i32)
11664       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11665                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11666                          ValOp, BaseShAmt);
11667     if (VT == MVT::v8i16)
11668       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11669                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11670                          ValOp, BaseShAmt);
11671     break;
11672   case ISD::SRA:
11673     if (VT == MVT::v4i32)
11674       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11675                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11676                          ValOp, BaseShAmt);
11677     if (VT == MVT::v8i16)
11678       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11679                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11680                          ValOp, BaseShAmt);
11681     break;
11682   case ISD::SRL:
11683     if (VT == MVT::v2i64)
11684       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11685                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11686                          ValOp, BaseShAmt);
11687     if (VT == MVT::v4i32)
11688       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11689                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11690                          ValOp, BaseShAmt);
11691     if (VT ==  MVT::v8i16)
11692       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11693                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11694                          ValOp, BaseShAmt);
11695     break;
11696   }
11697   return SDValue();
11698 }
11699
11700
11701 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11702 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11703 // and friends.  Likewise for OR -> CMPNEQSS.
11704 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11705                             TargetLowering::DAGCombinerInfo &DCI,
11706                             const X86Subtarget *Subtarget) {
11707   unsigned opcode;
11708
11709   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11710   // we're requiring SSE2 for both.
11711   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11712     SDValue N0 = N->getOperand(0);
11713     SDValue N1 = N->getOperand(1);
11714     SDValue CMP0 = N0->getOperand(1);
11715     SDValue CMP1 = N1->getOperand(1);
11716     DebugLoc DL = N->getDebugLoc();
11717
11718     // The SETCCs should both refer to the same CMP.
11719     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11720       return SDValue();
11721
11722     SDValue CMP00 = CMP0->getOperand(0);
11723     SDValue CMP01 = CMP0->getOperand(1);
11724     EVT     VT    = CMP00.getValueType();
11725
11726     if (VT == MVT::f32 || VT == MVT::f64) {
11727       bool ExpectingFlags = false;
11728       // Check for any users that want flags:
11729       for (SDNode::use_iterator UI = N->use_begin(),
11730              UE = N->use_end();
11731            !ExpectingFlags && UI != UE; ++UI)
11732         switch (UI->getOpcode()) {
11733         default:
11734         case ISD::BR_CC:
11735         case ISD::BRCOND:
11736         case ISD::SELECT:
11737           ExpectingFlags = true;
11738           break;
11739         case ISD::CopyToReg:
11740         case ISD::SIGN_EXTEND:
11741         case ISD::ZERO_EXTEND:
11742         case ISD::ANY_EXTEND:
11743           break;
11744         }
11745
11746       if (!ExpectingFlags) {
11747         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11748         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11749
11750         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11751           X86::CondCode tmp = cc0;
11752           cc0 = cc1;
11753           cc1 = tmp;
11754         }
11755
11756         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11757             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11758           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11759           X86ISD::NodeType NTOperator = is64BitFP ?
11760             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11761           // FIXME: need symbolic constants for these magic numbers.
11762           // See X86ATTInstPrinter.cpp:printSSECC().
11763           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11764           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11765                                               DAG.getConstant(x86cc, MVT::i8));
11766           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11767                                               OnesOrZeroesF);
11768           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11769                                       DAG.getConstant(1, MVT::i32));
11770           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11771           return OneBitOfTruth;
11772         }
11773       }
11774     }
11775   }
11776   return SDValue();
11777 }
11778
11779 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11780                                  TargetLowering::DAGCombinerInfo &DCI,
11781                                  const X86Subtarget *Subtarget) {
11782   if (DCI.isBeforeLegalizeOps())
11783     return SDValue();
11784
11785   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11786   if (R.getNode())
11787     return R;
11788
11789   // Want to form PANDN nodes, in the hopes of then easily combining them with
11790   // OR and AND nodes to form PBLEND/PSIGN.
11791   EVT VT = N->getValueType(0);
11792   if (VT != MVT::v2i64)
11793     return SDValue();
11794
11795   SDValue N0 = N->getOperand(0);
11796   SDValue N1 = N->getOperand(1);
11797   DebugLoc DL = N->getDebugLoc();
11798
11799   // Check LHS for vnot
11800   if (N0.getOpcode() == ISD::XOR &&
11801       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11802     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11803
11804   // Check RHS for vnot
11805   if (N1.getOpcode() == ISD::XOR &&
11806       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11807     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11808
11809   return SDValue();
11810 }
11811
11812 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11813                                 TargetLowering::DAGCombinerInfo &DCI,
11814                                 const X86Subtarget *Subtarget) {
11815   if (DCI.isBeforeLegalizeOps())
11816     return SDValue();
11817
11818   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11819   if (R.getNode())
11820     return R;
11821
11822   EVT VT = N->getValueType(0);
11823   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11824     return SDValue();
11825
11826   SDValue N0 = N->getOperand(0);
11827   SDValue N1 = N->getOperand(1);
11828
11829   // look for psign/blend
11830   if (Subtarget->hasSSSE3()) {
11831     if (VT == MVT::v2i64) {
11832       // Canonicalize pandn to RHS
11833       if (N0.getOpcode() == X86ISD::PANDN)
11834         std::swap(N0, N1);
11835       // or (and (m, x), (pandn m, y))
11836       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11837         SDValue Mask = N1.getOperand(0);
11838         SDValue X    = N1.getOperand(1);
11839         SDValue Y;
11840         if (N0.getOperand(0) == Mask)
11841           Y = N0.getOperand(1);
11842         if (N0.getOperand(1) == Mask)
11843           Y = N0.getOperand(0);
11844
11845         // Check to see if the mask appeared in both the AND and PANDN and
11846         if (!Y.getNode())
11847           return SDValue();
11848
11849         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11850         if (Mask.getOpcode() != ISD::BITCAST ||
11851             X.getOpcode() != ISD::BITCAST ||
11852             Y.getOpcode() != ISD::BITCAST)
11853           return SDValue();
11854
11855         // Look through mask bitcast.
11856         Mask = Mask.getOperand(0);
11857         EVT MaskVT = Mask.getValueType();
11858
11859         // Validate that the Mask operand is a vector sra node.  The sra node
11860         // will be an intrinsic.
11861         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11862           return SDValue();
11863
11864         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11865         // there is no psrai.b
11866         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11867         case Intrinsic::x86_sse2_psrai_w:
11868         case Intrinsic::x86_sse2_psrai_d:
11869           break;
11870         default: return SDValue();
11871         }
11872
11873         // Check that the SRA is all signbits.
11874         SDValue SraC = Mask.getOperand(2);
11875         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11876         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11877         if ((SraAmt + 1) != EltBits)
11878           return SDValue();
11879
11880         DebugLoc DL = N->getDebugLoc();
11881
11882         // Now we know we at least have a plendvb with the mask val.  See if
11883         // we can form a psignb/w/d.
11884         // psign = x.type == y.type == mask.type && y = sub(0, x);
11885         X = X.getOperand(0);
11886         Y = Y.getOperand(0);
11887         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11888             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11889             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11890           unsigned Opc = 0;
11891           switch (EltBits) {
11892           case 8: Opc = X86ISD::PSIGNB; break;
11893           case 16: Opc = X86ISD::PSIGNW; break;
11894           case 32: Opc = X86ISD::PSIGND; break;
11895           default: break;
11896           }
11897           if (Opc) {
11898             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11899             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11900           }
11901         }
11902         // PBLENDVB only available on SSE 4.1
11903         if (!Subtarget->hasSSE41())
11904           return SDValue();
11905
11906         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11907         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11908         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11909         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11910         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11911       }
11912     }
11913   }
11914
11915   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11916   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11917     std::swap(N0, N1);
11918   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11919     return SDValue();
11920   if (!N0.hasOneUse() || !N1.hasOneUse())
11921     return SDValue();
11922
11923   SDValue ShAmt0 = N0.getOperand(1);
11924   if (ShAmt0.getValueType() != MVT::i8)
11925     return SDValue();
11926   SDValue ShAmt1 = N1.getOperand(1);
11927   if (ShAmt1.getValueType() != MVT::i8)
11928     return SDValue();
11929   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11930     ShAmt0 = ShAmt0.getOperand(0);
11931   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11932     ShAmt1 = ShAmt1.getOperand(0);
11933
11934   DebugLoc DL = N->getDebugLoc();
11935   unsigned Opc = X86ISD::SHLD;
11936   SDValue Op0 = N0.getOperand(0);
11937   SDValue Op1 = N1.getOperand(0);
11938   if (ShAmt0.getOpcode() == ISD::SUB) {
11939     Opc = X86ISD::SHRD;
11940     std::swap(Op0, Op1);
11941     std::swap(ShAmt0, ShAmt1);
11942   }
11943
11944   unsigned Bits = VT.getSizeInBits();
11945   if (ShAmt1.getOpcode() == ISD::SUB) {
11946     SDValue Sum = ShAmt1.getOperand(0);
11947     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11948       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11949       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11950         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11951       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11952         return DAG.getNode(Opc, DL, VT,
11953                            Op0, Op1,
11954                            DAG.getNode(ISD::TRUNCATE, DL,
11955                                        MVT::i8, ShAmt0));
11956     }
11957   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11958     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11959     if (ShAmt0C &&
11960         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11961       return DAG.getNode(Opc, DL, VT,
11962                          N0.getOperand(0), N1.getOperand(0),
11963                          DAG.getNode(ISD::TRUNCATE, DL,
11964                                        MVT::i8, ShAmt0));
11965   }
11966
11967   return SDValue();
11968 }
11969
11970 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11971 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11972                                    const X86Subtarget *Subtarget) {
11973   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11974   // the FP state in cases where an emms may be missing.
11975   // A preferable solution to the general problem is to figure out the right
11976   // places to insert EMMS.  This qualifies as a quick hack.
11977
11978   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11979   StoreSDNode *St = cast<StoreSDNode>(N);
11980   EVT VT = St->getValue().getValueType();
11981   if (VT.getSizeInBits() != 64)
11982     return SDValue();
11983
11984   const Function *F = DAG.getMachineFunction().getFunction();
11985   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11986   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11987     && Subtarget->hasSSE2();
11988   if ((VT.isVector() ||
11989        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11990       isa<LoadSDNode>(St->getValue()) &&
11991       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11992       St->getChain().hasOneUse() && !St->isVolatile()) {
11993     SDNode* LdVal = St->getValue().getNode();
11994     LoadSDNode *Ld = 0;
11995     int TokenFactorIndex = -1;
11996     SmallVector<SDValue, 8> Ops;
11997     SDNode* ChainVal = St->getChain().getNode();
11998     // Must be a store of a load.  We currently handle two cases:  the load
11999     // is a direct child, and it's under an intervening TokenFactor.  It is
12000     // possible to dig deeper under nested TokenFactors.
12001     if (ChainVal == LdVal)
12002       Ld = cast<LoadSDNode>(St->getChain());
12003     else if (St->getValue().hasOneUse() &&
12004              ChainVal->getOpcode() == ISD::TokenFactor) {
12005       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12006         if (ChainVal->getOperand(i).getNode() == LdVal) {
12007           TokenFactorIndex = i;
12008           Ld = cast<LoadSDNode>(St->getValue());
12009         } else
12010           Ops.push_back(ChainVal->getOperand(i));
12011       }
12012     }
12013
12014     if (!Ld || !ISD::isNormalLoad(Ld))
12015       return SDValue();
12016
12017     // If this is not the MMX case, i.e. we are just turning i64 load/store
12018     // into f64 load/store, avoid the transformation if there are multiple
12019     // uses of the loaded value.
12020     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12021       return SDValue();
12022
12023     DebugLoc LdDL = Ld->getDebugLoc();
12024     DebugLoc StDL = N->getDebugLoc();
12025     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12026     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12027     // pair instead.
12028     if (Subtarget->is64Bit() || F64IsLegal) {
12029       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12030       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12031                                   Ld->getPointerInfo(), Ld->isVolatile(),
12032                                   Ld->isNonTemporal(), Ld->getAlignment());
12033       SDValue NewChain = NewLd.getValue(1);
12034       if (TokenFactorIndex != -1) {
12035         Ops.push_back(NewChain);
12036         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12037                                Ops.size());
12038       }
12039       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12040                           St->getPointerInfo(),
12041                           St->isVolatile(), St->isNonTemporal(),
12042                           St->getAlignment());
12043     }
12044
12045     // Otherwise, lower to two pairs of 32-bit loads / stores.
12046     SDValue LoAddr = Ld->getBasePtr();
12047     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12048                                  DAG.getConstant(4, MVT::i32));
12049
12050     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12051                                Ld->getPointerInfo(),
12052                                Ld->isVolatile(), Ld->isNonTemporal(),
12053                                Ld->getAlignment());
12054     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12055                                Ld->getPointerInfo().getWithOffset(4),
12056                                Ld->isVolatile(), Ld->isNonTemporal(),
12057                                MinAlign(Ld->getAlignment(), 4));
12058
12059     SDValue NewChain = LoLd.getValue(1);
12060     if (TokenFactorIndex != -1) {
12061       Ops.push_back(LoLd);
12062       Ops.push_back(HiLd);
12063       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12064                              Ops.size());
12065     }
12066
12067     LoAddr = St->getBasePtr();
12068     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12069                          DAG.getConstant(4, MVT::i32));
12070
12071     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12072                                 St->getPointerInfo(),
12073                                 St->isVolatile(), St->isNonTemporal(),
12074                                 St->getAlignment());
12075     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12076                                 St->getPointerInfo().getWithOffset(4),
12077                                 St->isVolatile(),
12078                                 St->isNonTemporal(),
12079                                 MinAlign(St->getAlignment(), 4));
12080     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12081   }
12082   return SDValue();
12083 }
12084
12085 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12086 /// X86ISD::FXOR nodes.
12087 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12088   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12089   // F[X]OR(0.0, x) -> x
12090   // F[X]OR(x, 0.0) -> x
12091   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12092     if (C->getValueAPF().isPosZero())
12093       return N->getOperand(1);
12094   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12095     if (C->getValueAPF().isPosZero())
12096       return N->getOperand(0);
12097   return SDValue();
12098 }
12099
12100 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12101 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12102   // FAND(0.0, x) -> 0.0
12103   // FAND(x, 0.0) -> 0.0
12104   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12105     if (C->getValueAPF().isPosZero())
12106       return N->getOperand(0);
12107   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12108     if (C->getValueAPF().isPosZero())
12109       return N->getOperand(1);
12110   return SDValue();
12111 }
12112
12113 static SDValue PerformBTCombine(SDNode *N,
12114                                 SelectionDAG &DAG,
12115                                 TargetLowering::DAGCombinerInfo &DCI) {
12116   // BT ignores high bits in the bit index operand.
12117   SDValue Op1 = N->getOperand(1);
12118   if (Op1.hasOneUse()) {
12119     unsigned BitWidth = Op1.getValueSizeInBits();
12120     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12121     APInt KnownZero, KnownOne;
12122     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12123                                           !DCI.isBeforeLegalizeOps());
12124     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12125     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12126         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12127       DCI.CommitTargetLoweringOpt(TLO);
12128   }
12129   return SDValue();
12130 }
12131
12132 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12133   SDValue Op = N->getOperand(0);
12134   if (Op.getOpcode() == ISD::BITCAST)
12135     Op = Op.getOperand(0);
12136   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12137   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12138       VT.getVectorElementType().getSizeInBits() ==
12139       OpVT.getVectorElementType().getSizeInBits()) {
12140     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12141   }
12142   return SDValue();
12143 }
12144
12145 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12146   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12147   //           (and (i32 x86isd::setcc_carry), 1)
12148   // This eliminates the zext. This transformation is necessary because
12149   // ISD::SETCC is always legalized to i8.
12150   DebugLoc dl = N->getDebugLoc();
12151   SDValue N0 = N->getOperand(0);
12152   EVT VT = N->getValueType(0);
12153   if (N0.getOpcode() == ISD::AND &&
12154       N0.hasOneUse() &&
12155       N0.getOperand(0).hasOneUse()) {
12156     SDValue N00 = N0.getOperand(0);
12157     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12158       return SDValue();
12159     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12160     if (!C || C->getZExtValue() != 1)
12161       return SDValue();
12162     return DAG.getNode(ISD::AND, dl, VT,
12163                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12164                                    N00.getOperand(0), N00.getOperand(1)),
12165                        DAG.getConstant(1, VT));
12166   }
12167
12168   return SDValue();
12169 }
12170
12171 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12172 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12173   unsigned X86CC = N->getConstantOperandVal(0);
12174   SDValue EFLAG = N->getOperand(1);
12175   DebugLoc DL = N->getDebugLoc();
12176
12177   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12178   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12179   // cases.
12180   if (X86CC == X86::COND_B)
12181     return DAG.getNode(ISD::AND, DL, MVT::i8,
12182                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12183                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12184                        DAG.getConstant(1, MVT::i8));
12185
12186   return SDValue();
12187 }
12188
12189 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12190                                         const X86TargetLowering *XTLI) {
12191   SDValue Op0 = N->getOperand(0);
12192   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12193   // a 32-bit target where SSE doesn't support i64->FP operations.
12194   if (Op0.getOpcode() == ISD::LOAD) {
12195     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12196     EVT VT = Ld->getValueType(0);
12197     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12198         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12199         !XTLI->getSubtarget()->is64Bit() &&
12200         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12201       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12202                                           Ld->getChain(), Op0, DAG);
12203       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12204       return FILDChain;
12205     }
12206   }
12207   return SDValue();
12208 }
12209
12210 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12211 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12212                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12213   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12214   // the result is either zero or one (depending on the input carry bit).
12215   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12216   if (X86::isZeroNode(N->getOperand(0)) &&
12217       X86::isZeroNode(N->getOperand(1)) &&
12218       // We don't have a good way to replace an EFLAGS use, so only do this when
12219       // dead right now.
12220       SDValue(N, 1).use_empty()) {
12221     DebugLoc DL = N->getDebugLoc();
12222     EVT VT = N->getValueType(0);
12223     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12224     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12225                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12226                                            DAG.getConstant(X86::COND_B,MVT::i8),
12227                                            N->getOperand(2)),
12228                                DAG.getConstant(1, VT));
12229     return DCI.CombineTo(N, Res1, CarryOut);
12230   }
12231
12232   return SDValue();
12233 }
12234
12235 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12236 //      (add Y, (setne X, 0)) -> sbb -1, Y
12237 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12238 //      (sub (setne X, 0), Y) -> adc -1, Y
12239 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12240   DebugLoc DL = N->getDebugLoc();
12241
12242   // Look through ZExts.
12243   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12244   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12245     return SDValue();
12246
12247   SDValue SetCC = Ext.getOperand(0);
12248   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12249     return SDValue();
12250
12251   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12252   if (CC != X86::COND_E && CC != X86::COND_NE)
12253     return SDValue();
12254
12255   SDValue Cmp = SetCC.getOperand(1);
12256   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12257       !X86::isZeroNode(Cmp.getOperand(1)) ||
12258       !Cmp.getOperand(0).getValueType().isInteger())
12259     return SDValue();
12260
12261   SDValue CmpOp0 = Cmp.getOperand(0);
12262   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12263                                DAG.getConstant(1, CmpOp0.getValueType()));
12264
12265   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12266   if (CC == X86::COND_NE)
12267     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12268                        DL, OtherVal.getValueType(), OtherVal,
12269                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12270   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12271                      DL, OtherVal.getValueType(), OtherVal,
12272                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12273 }
12274
12275 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12276                                              DAGCombinerInfo &DCI) const {
12277   SelectionDAG &DAG = DCI.DAG;
12278   switch (N->getOpcode()) {
12279   default: break;
12280   case ISD::EXTRACT_VECTOR_ELT:
12281     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12282   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12283   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12284   case ISD::ADD:
12285   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12286   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12287   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12288   case ISD::SHL:
12289   case ISD::SRA:
12290   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12291   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12292   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12293   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12294   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12295   case X86ISD::FXOR:
12296   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12297   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12298   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12299   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12300   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12301   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12302   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12303   case X86ISD::SHUFPD:
12304   case X86ISD::PALIGN:
12305   case X86ISD::PUNPCKHBW:
12306   case X86ISD::PUNPCKHWD:
12307   case X86ISD::PUNPCKHDQ:
12308   case X86ISD::PUNPCKHQDQ:
12309   case X86ISD::UNPCKHPS:
12310   case X86ISD::UNPCKHPD:
12311   case X86ISD::PUNPCKLBW:
12312   case X86ISD::PUNPCKLWD:
12313   case X86ISD::PUNPCKLDQ:
12314   case X86ISD::PUNPCKLQDQ:
12315   case X86ISD::UNPCKLPS:
12316   case X86ISD::UNPCKLPD:
12317   case X86ISD::VUNPCKLPS:
12318   case X86ISD::VUNPCKLPD:
12319   case X86ISD::VUNPCKLPSY:
12320   case X86ISD::VUNPCKLPDY:
12321   case X86ISD::MOVHLPS:
12322   case X86ISD::MOVLHPS:
12323   case X86ISD::PSHUFD:
12324   case X86ISD::PSHUFHW:
12325   case X86ISD::PSHUFLW:
12326   case X86ISD::MOVSS:
12327   case X86ISD::MOVSD:
12328   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12329   }
12330
12331   return SDValue();
12332 }
12333
12334 /// isTypeDesirableForOp - Return true if the target has native support for
12335 /// the specified value type and it is 'desirable' to use the type for the
12336 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12337 /// instruction encodings are longer and some i16 instructions are slow.
12338 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12339   if (!isTypeLegal(VT))
12340     return false;
12341   if (VT != MVT::i16)
12342     return true;
12343
12344   switch (Opc) {
12345   default:
12346     return true;
12347   case ISD::LOAD:
12348   case ISD::SIGN_EXTEND:
12349   case ISD::ZERO_EXTEND:
12350   case ISD::ANY_EXTEND:
12351   case ISD::SHL:
12352   case ISD::SRL:
12353   case ISD::SUB:
12354   case ISD::ADD:
12355   case ISD::MUL:
12356   case ISD::AND:
12357   case ISD::OR:
12358   case ISD::XOR:
12359     return false;
12360   }
12361 }
12362
12363 /// IsDesirableToPromoteOp - This method query the target whether it is
12364 /// beneficial for dag combiner to promote the specified node. If true, it
12365 /// should return the desired promotion type by reference.
12366 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12367   EVT VT = Op.getValueType();
12368   if (VT != MVT::i16)
12369     return false;
12370
12371   bool Promote = false;
12372   bool Commute = false;
12373   switch (Op.getOpcode()) {
12374   default: break;
12375   case ISD::LOAD: {
12376     LoadSDNode *LD = cast<LoadSDNode>(Op);
12377     // If the non-extending load has a single use and it's not live out, then it
12378     // might be folded.
12379     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12380                                                      Op.hasOneUse()*/) {
12381       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12382              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12383         // The only case where we'd want to promote LOAD (rather then it being
12384         // promoted as an operand is when it's only use is liveout.
12385         if (UI->getOpcode() != ISD::CopyToReg)
12386           return false;
12387       }
12388     }
12389     Promote = true;
12390     break;
12391   }
12392   case ISD::SIGN_EXTEND:
12393   case ISD::ZERO_EXTEND:
12394   case ISD::ANY_EXTEND:
12395     Promote = true;
12396     break;
12397   case ISD::SHL:
12398   case ISD::SRL: {
12399     SDValue N0 = Op.getOperand(0);
12400     // Look out for (store (shl (load), x)).
12401     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12402       return false;
12403     Promote = true;
12404     break;
12405   }
12406   case ISD::ADD:
12407   case ISD::MUL:
12408   case ISD::AND:
12409   case ISD::OR:
12410   case ISD::XOR:
12411     Commute = true;
12412     // fallthrough
12413   case ISD::SUB: {
12414     SDValue N0 = Op.getOperand(0);
12415     SDValue N1 = Op.getOperand(1);
12416     if (!Commute && MayFoldLoad(N1))
12417       return false;
12418     // Avoid disabling potential load folding opportunities.
12419     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12420       return false;
12421     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12422       return false;
12423     Promote = true;
12424   }
12425   }
12426
12427   PVT = MVT::i32;
12428   return Promote;
12429 }
12430
12431 //===----------------------------------------------------------------------===//
12432 //                           X86 Inline Assembly Support
12433 //===----------------------------------------------------------------------===//
12434
12435 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12436   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12437
12438   std::string AsmStr = IA->getAsmString();
12439
12440   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12441   SmallVector<StringRef, 4> AsmPieces;
12442   SplitString(AsmStr, AsmPieces, ";\n");
12443
12444   switch (AsmPieces.size()) {
12445   default: return false;
12446   case 1:
12447     AsmStr = AsmPieces[0];
12448     AsmPieces.clear();
12449     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12450
12451     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12452     // we will turn this bswap into something that will be lowered to logical ops
12453     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12454     // so don't worry about this.
12455     // bswap $0
12456     if (AsmPieces.size() == 2 &&
12457         (AsmPieces[0] == "bswap" ||
12458          AsmPieces[0] == "bswapq" ||
12459          AsmPieces[0] == "bswapl") &&
12460         (AsmPieces[1] == "$0" ||
12461          AsmPieces[1] == "${0:q}")) {
12462       // No need to check constraints, nothing other than the equivalent of
12463       // "=r,0" would be valid here.
12464       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12465       if (!Ty || Ty->getBitWidth() % 16 != 0)
12466         return false;
12467       return IntrinsicLowering::LowerToByteSwap(CI);
12468     }
12469     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12470     if (CI->getType()->isIntegerTy(16) &&
12471         AsmPieces.size() == 3 &&
12472         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12473         AsmPieces[1] == "$$8," &&
12474         AsmPieces[2] == "${0:w}" &&
12475         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12476       AsmPieces.clear();
12477       const std::string &ConstraintsStr = IA->getConstraintString();
12478       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12479       std::sort(AsmPieces.begin(), AsmPieces.end());
12480       if (AsmPieces.size() == 4 &&
12481           AsmPieces[0] == "~{cc}" &&
12482           AsmPieces[1] == "~{dirflag}" &&
12483           AsmPieces[2] == "~{flags}" &&
12484           AsmPieces[3] == "~{fpsr}") {
12485         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12486         if (!Ty || Ty->getBitWidth() % 16 != 0)
12487           return false;
12488         return IntrinsicLowering::LowerToByteSwap(CI);
12489       }
12490     }
12491     break;
12492   case 3:
12493     if (CI->getType()->isIntegerTy(32) &&
12494         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12495       SmallVector<StringRef, 4> Words;
12496       SplitString(AsmPieces[0], Words, " \t,");
12497       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12498           Words[2] == "${0:w}") {
12499         Words.clear();
12500         SplitString(AsmPieces[1], Words, " \t,");
12501         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12502             Words[2] == "$0") {
12503           Words.clear();
12504           SplitString(AsmPieces[2], Words, " \t,");
12505           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12506               Words[2] == "${0:w}") {
12507             AsmPieces.clear();
12508             const std::string &ConstraintsStr = IA->getConstraintString();
12509             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12510             std::sort(AsmPieces.begin(), AsmPieces.end());
12511             if (AsmPieces.size() == 4 &&
12512                 AsmPieces[0] == "~{cc}" &&
12513                 AsmPieces[1] == "~{dirflag}" &&
12514                 AsmPieces[2] == "~{flags}" &&
12515                 AsmPieces[3] == "~{fpsr}") {
12516               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12517               if (!Ty || Ty->getBitWidth() % 16 != 0)
12518                 return false;
12519               return IntrinsicLowering::LowerToByteSwap(CI);
12520             }
12521           }
12522         }
12523       }
12524     }
12525
12526     if (CI->getType()->isIntegerTy(64)) {
12527       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12528       if (Constraints.size() >= 2 &&
12529           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12530           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12531         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12532         SmallVector<StringRef, 4> Words;
12533         SplitString(AsmPieces[0], Words, " \t");
12534         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12535           Words.clear();
12536           SplitString(AsmPieces[1], Words, " \t");
12537           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12538             Words.clear();
12539             SplitString(AsmPieces[2], Words, " \t,");
12540             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12541                 Words[2] == "%edx") {
12542               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12543               if (!Ty || Ty->getBitWidth() % 16 != 0)
12544                 return false;
12545               return IntrinsicLowering::LowerToByteSwap(CI);
12546             }
12547           }
12548         }
12549       }
12550     }
12551     break;
12552   }
12553   return false;
12554 }
12555
12556
12557
12558 /// getConstraintType - Given a constraint letter, return the type of
12559 /// constraint it is for this target.
12560 X86TargetLowering::ConstraintType
12561 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12562   if (Constraint.size() == 1) {
12563     switch (Constraint[0]) {
12564     case 'R':
12565     case 'q':
12566     case 'Q':
12567     case 'f':
12568     case 't':
12569     case 'u':
12570     case 'y':
12571     case 'x':
12572     case 'Y':
12573       return C_RegisterClass;
12574     case 'a':
12575     case 'b':
12576     case 'c':
12577     case 'd':
12578     case 'S':
12579     case 'D':
12580     case 'A':
12581       return C_Register;
12582     case 'I':
12583     case 'J':
12584     case 'K':
12585     case 'L':
12586     case 'M':
12587     case 'N':
12588     case 'G':
12589     case 'C':
12590     case 'e':
12591     case 'Z':
12592       return C_Other;
12593     default:
12594       break;
12595     }
12596   }
12597   return TargetLowering::getConstraintType(Constraint);
12598 }
12599
12600 /// Examine constraint type and operand type and determine a weight value.
12601 /// This object must already have been set up with the operand type
12602 /// and the current alternative constraint selected.
12603 TargetLowering::ConstraintWeight
12604   X86TargetLowering::getSingleConstraintMatchWeight(
12605     AsmOperandInfo &info, const char *constraint) const {
12606   ConstraintWeight weight = CW_Invalid;
12607   Value *CallOperandVal = info.CallOperandVal;
12608     // If we don't have a value, we can't do a match,
12609     // but allow it at the lowest weight.
12610   if (CallOperandVal == NULL)
12611     return CW_Default;
12612   const Type *type = CallOperandVal->getType();
12613   // Look at the constraint type.
12614   switch (*constraint) {
12615   default:
12616     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12617   case 'R':
12618   case 'q':
12619   case 'Q':
12620   case 'a':
12621   case 'b':
12622   case 'c':
12623   case 'd':
12624   case 'S':
12625   case 'D':
12626   case 'A':
12627     if (CallOperandVal->getType()->isIntegerTy())
12628       weight = CW_SpecificReg;
12629     break;
12630   case 'f':
12631   case 't':
12632   case 'u':
12633       if (type->isFloatingPointTy())
12634         weight = CW_SpecificReg;
12635       break;
12636   case 'y':
12637       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12638         weight = CW_SpecificReg;
12639       break;
12640   case 'x':
12641   case 'Y':
12642     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12643       weight = CW_Register;
12644     break;
12645   case 'I':
12646     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12647       if (C->getZExtValue() <= 31)
12648         weight = CW_Constant;
12649     }
12650     break;
12651   case 'J':
12652     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12653       if (C->getZExtValue() <= 63)
12654         weight = CW_Constant;
12655     }
12656     break;
12657   case 'K':
12658     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12659       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12660         weight = CW_Constant;
12661     }
12662     break;
12663   case 'L':
12664     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12665       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12666         weight = CW_Constant;
12667     }
12668     break;
12669   case 'M':
12670     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12671       if (C->getZExtValue() <= 3)
12672         weight = CW_Constant;
12673     }
12674     break;
12675   case 'N':
12676     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12677       if (C->getZExtValue() <= 0xff)
12678         weight = CW_Constant;
12679     }
12680     break;
12681   case 'G':
12682   case 'C':
12683     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12684       weight = CW_Constant;
12685     }
12686     break;
12687   case 'e':
12688     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12689       if ((C->getSExtValue() >= -0x80000000LL) &&
12690           (C->getSExtValue() <= 0x7fffffffLL))
12691         weight = CW_Constant;
12692     }
12693     break;
12694   case 'Z':
12695     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12696       if (C->getZExtValue() <= 0xffffffff)
12697         weight = CW_Constant;
12698     }
12699     break;
12700   }
12701   return weight;
12702 }
12703
12704 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12705 /// with another that has more specific requirements based on the type of the
12706 /// corresponding operand.
12707 const char *X86TargetLowering::
12708 LowerXConstraint(EVT ConstraintVT) const {
12709   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12710   // 'f' like normal targets.
12711   if (ConstraintVT.isFloatingPoint()) {
12712     if (Subtarget->hasXMMInt())
12713       return "Y";
12714     if (Subtarget->hasXMM())
12715       return "x";
12716   }
12717
12718   return TargetLowering::LowerXConstraint(ConstraintVT);
12719 }
12720
12721 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12722 /// vector.  If it is invalid, don't add anything to Ops.
12723 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12724                                                      std::string &Constraint,
12725                                                      std::vector<SDValue>&Ops,
12726                                                      SelectionDAG &DAG) const {
12727   SDValue Result(0, 0);
12728
12729   // Only support length 1 constraints for now.
12730   if (Constraint.length() > 1) return;
12731
12732   char ConstraintLetter = Constraint[0];
12733   switch (ConstraintLetter) {
12734   default: break;
12735   case 'I':
12736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12737       if (C->getZExtValue() <= 31) {
12738         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12739         break;
12740       }
12741     }
12742     return;
12743   case 'J':
12744     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12745       if (C->getZExtValue() <= 63) {
12746         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12747         break;
12748       }
12749     }
12750     return;
12751   case 'K':
12752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12753       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12754         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12755         break;
12756       }
12757     }
12758     return;
12759   case 'N':
12760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12761       if (C->getZExtValue() <= 255) {
12762         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12763         break;
12764       }
12765     }
12766     return;
12767   case 'e': {
12768     // 32-bit signed value
12769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12770       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12771                                            C->getSExtValue())) {
12772         // Widen to 64 bits here to get it sign extended.
12773         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12774         break;
12775       }
12776     // FIXME gcc accepts some relocatable values here too, but only in certain
12777     // memory models; it's complicated.
12778     }
12779     return;
12780   }
12781   case 'Z': {
12782     // 32-bit unsigned value
12783     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12784       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12785                                            C->getZExtValue())) {
12786         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12787         break;
12788       }
12789     }
12790     // FIXME gcc accepts some relocatable values here too, but only in certain
12791     // memory models; it's complicated.
12792     return;
12793   }
12794   case 'i': {
12795     // Literal immediates are always ok.
12796     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12797       // Widen to 64 bits here to get it sign extended.
12798       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12799       break;
12800     }
12801
12802     // In any sort of PIC mode addresses need to be computed at runtime by
12803     // adding in a register or some sort of table lookup.  These can't
12804     // be used as immediates.
12805     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12806       return;
12807
12808     // If we are in non-pic codegen mode, we allow the address of a global (with
12809     // an optional displacement) to be used with 'i'.
12810     GlobalAddressSDNode *GA = 0;
12811     int64_t Offset = 0;
12812
12813     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12814     while (1) {
12815       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12816         Offset += GA->getOffset();
12817         break;
12818       } else if (Op.getOpcode() == ISD::ADD) {
12819         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12820           Offset += C->getZExtValue();
12821           Op = Op.getOperand(0);
12822           continue;
12823         }
12824       } else if (Op.getOpcode() == ISD::SUB) {
12825         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12826           Offset += -C->getZExtValue();
12827           Op = Op.getOperand(0);
12828           continue;
12829         }
12830       }
12831
12832       // Otherwise, this isn't something we can handle, reject it.
12833       return;
12834     }
12835
12836     const GlobalValue *GV = GA->getGlobal();
12837     // If we require an extra load to get this address, as in PIC mode, we
12838     // can't accept it.
12839     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12840                                                         getTargetMachine())))
12841       return;
12842
12843     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12844                                         GA->getValueType(0), Offset);
12845     break;
12846   }
12847   }
12848
12849   if (Result.getNode()) {
12850     Ops.push_back(Result);
12851     return;
12852   }
12853   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12854 }
12855
12856 std::vector<unsigned> X86TargetLowering::
12857 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12858                                   EVT VT) const {
12859   if (Constraint.size() == 1) {
12860     // FIXME: not handling fp-stack yet!
12861     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12862     default: break;  // Unknown constraint letter
12863     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12864       if (Subtarget->is64Bit()) {
12865         if (VT == MVT::i32)
12866           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12867                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12868                                        X86::R10D,X86::R11D,X86::R12D,
12869                                        X86::R13D,X86::R14D,X86::R15D,
12870                                        X86::EBP, X86::ESP, 0);
12871         else if (VT == MVT::i16)
12872           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12873                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12874                                        X86::R10W,X86::R11W,X86::R12W,
12875                                        X86::R13W,X86::R14W,X86::R15W,
12876                                        X86::BP,  X86::SP, 0);
12877         else if (VT == MVT::i8)
12878           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12879                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12880                                        X86::R10B,X86::R11B,X86::R12B,
12881                                        X86::R13B,X86::R14B,X86::R15B,
12882                                        X86::BPL, X86::SPL, 0);
12883
12884         else if (VT == MVT::i64)
12885           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12886                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12887                                        X86::R10, X86::R11, X86::R12,
12888                                        X86::R13, X86::R14, X86::R15,
12889                                        X86::RBP, X86::RSP, 0);
12890
12891         break;
12892       }
12893       // 32-bit fallthrough
12894     case 'Q':   // Q_REGS
12895       if (VT == MVT::i32)
12896         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12897       else if (VT == MVT::i16)
12898         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12899       else if (VT == MVT::i8)
12900         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12901       else if (VT == MVT::i64)
12902         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12903       break;
12904     }
12905   }
12906
12907   return std::vector<unsigned>();
12908 }
12909
12910 std::pair<unsigned, const TargetRegisterClass*>
12911 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12912                                                 EVT VT) const {
12913   // First, see if this is a constraint that directly corresponds to an LLVM
12914   // register class.
12915   if (Constraint.size() == 1) {
12916     // GCC Constraint Letters
12917     switch (Constraint[0]) {
12918     default: break;
12919     case 'r':   // GENERAL_REGS
12920     case 'l':   // INDEX_REGS
12921       if (VT == MVT::i8)
12922         return std::make_pair(0U, X86::GR8RegisterClass);
12923       if (VT == MVT::i16)
12924         return std::make_pair(0U, X86::GR16RegisterClass);
12925       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12926         return std::make_pair(0U, X86::GR32RegisterClass);
12927       return std::make_pair(0U, X86::GR64RegisterClass);
12928     case 'R':   // LEGACY_REGS
12929       if (VT == MVT::i8)
12930         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12931       if (VT == MVT::i16)
12932         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12933       if (VT == MVT::i32 || !Subtarget->is64Bit())
12934         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12935       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12936     case 'f':  // FP Stack registers.
12937       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12938       // value to the correct fpstack register class.
12939       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12940         return std::make_pair(0U, X86::RFP32RegisterClass);
12941       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12942         return std::make_pair(0U, X86::RFP64RegisterClass);
12943       return std::make_pair(0U, X86::RFP80RegisterClass);
12944     case 'y':   // MMX_REGS if MMX allowed.
12945       if (!Subtarget->hasMMX()) break;
12946       return std::make_pair(0U, X86::VR64RegisterClass);
12947     case 'Y':   // SSE_REGS if SSE2 allowed
12948       if (!Subtarget->hasXMMInt()) break;
12949       // FALL THROUGH.
12950     case 'x':   // SSE_REGS if SSE1 allowed
12951       if (!Subtarget->hasXMM()) break;
12952
12953       switch (VT.getSimpleVT().SimpleTy) {
12954       default: break;
12955       // Scalar SSE types.
12956       case MVT::f32:
12957       case MVT::i32:
12958         return std::make_pair(0U, X86::FR32RegisterClass);
12959       case MVT::f64:
12960       case MVT::i64:
12961         return std::make_pair(0U, X86::FR64RegisterClass);
12962       // Vector types.
12963       case MVT::v16i8:
12964       case MVT::v8i16:
12965       case MVT::v4i32:
12966       case MVT::v2i64:
12967       case MVT::v4f32:
12968       case MVT::v2f64:
12969         return std::make_pair(0U, X86::VR128RegisterClass);
12970       }
12971       break;
12972     }
12973   }
12974
12975   // Use the default implementation in TargetLowering to convert the register
12976   // constraint into a member of a register class.
12977   std::pair<unsigned, const TargetRegisterClass*> Res;
12978   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12979
12980   // Not found as a standard register?
12981   if (Res.second == 0) {
12982     // Map st(0) -> st(7) -> ST0
12983     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12984         tolower(Constraint[1]) == 's' &&
12985         tolower(Constraint[2]) == 't' &&
12986         Constraint[3] == '(' &&
12987         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12988         Constraint[5] == ')' &&
12989         Constraint[6] == '}') {
12990
12991       Res.first = X86::ST0+Constraint[4]-'0';
12992       Res.second = X86::RFP80RegisterClass;
12993       return Res;
12994     }
12995
12996     // GCC allows "st(0)" to be called just plain "st".
12997     if (StringRef("{st}").equals_lower(Constraint)) {
12998       Res.first = X86::ST0;
12999       Res.second = X86::RFP80RegisterClass;
13000       return Res;
13001     }
13002
13003     // flags -> EFLAGS
13004     if (StringRef("{flags}").equals_lower(Constraint)) {
13005       Res.first = X86::EFLAGS;
13006       Res.second = X86::CCRRegisterClass;
13007       return Res;
13008     }
13009
13010     // 'A' means EAX + EDX.
13011     if (Constraint == "A") {
13012       Res.first = X86::EAX;
13013       Res.second = X86::GR32_ADRegisterClass;
13014       return Res;
13015     }
13016     return Res;
13017   }
13018
13019   // Otherwise, check to see if this is a register class of the wrong value
13020   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13021   // turn into {ax},{dx}.
13022   if (Res.second->hasType(VT))
13023     return Res;   // Correct type already, nothing to do.
13024
13025   // All of the single-register GCC register classes map their values onto
13026   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13027   // really want an 8-bit or 32-bit register, map to the appropriate register
13028   // class and return the appropriate register.
13029   if (Res.second == X86::GR16RegisterClass) {
13030     if (VT == MVT::i8) {
13031       unsigned DestReg = 0;
13032       switch (Res.first) {
13033       default: break;
13034       case X86::AX: DestReg = X86::AL; break;
13035       case X86::DX: DestReg = X86::DL; break;
13036       case X86::CX: DestReg = X86::CL; break;
13037       case X86::BX: DestReg = X86::BL; break;
13038       }
13039       if (DestReg) {
13040         Res.first = DestReg;
13041         Res.second = X86::GR8RegisterClass;
13042       }
13043     } else if (VT == MVT::i32) {
13044       unsigned DestReg = 0;
13045       switch (Res.first) {
13046       default: break;
13047       case X86::AX: DestReg = X86::EAX; break;
13048       case X86::DX: DestReg = X86::EDX; break;
13049       case X86::CX: DestReg = X86::ECX; break;
13050       case X86::BX: DestReg = X86::EBX; break;
13051       case X86::SI: DestReg = X86::ESI; break;
13052       case X86::DI: DestReg = X86::EDI; break;
13053       case X86::BP: DestReg = X86::EBP; break;
13054       case X86::SP: DestReg = X86::ESP; break;
13055       }
13056       if (DestReg) {
13057         Res.first = DestReg;
13058         Res.second = X86::GR32RegisterClass;
13059       }
13060     } else if (VT == MVT::i64) {
13061       unsigned DestReg = 0;
13062       switch (Res.first) {
13063       default: break;
13064       case X86::AX: DestReg = X86::RAX; break;
13065       case X86::DX: DestReg = X86::RDX; break;
13066       case X86::CX: DestReg = X86::RCX; break;
13067       case X86::BX: DestReg = X86::RBX; break;
13068       case X86::SI: DestReg = X86::RSI; break;
13069       case X86::DI: DestReg = X86::RDI; break;
13070       case X86::BP: DestReg = X86::RBP; break;
13071       case X86::SP: DestReg = X86::RSP; break;
13072       }
13073       if (DestReg) {
13074         Res.first = DestReg;
13075         Res.second = X86::GR64RegisterClass;
13076       }
13077     }
13078   } else if (Res.second == X86::FR32RegisterClass ||
13079              Res.second == X86::FR64RegisterClass ||
13080              Res.second == X86::VR128RegisterClass) {
13081     // Handle references to XMM physical registers that got mapped into the
13082     // wrong class.  This can happen with constraints like {xmm0} where the
13083     // target independent register mapper will just pick the first match it can
13084     // find, ignoring the required type.
13085     if (VT == MVT::f32)
13086       Res.second = X86::FR32RegisterClass;
13087     else if (VT == MVT::f64)
13088       Res.second = X86::FR64RegisterClass;
13089     else if (X86::VR128RegisterClass->hasType(VT))
13090       Res.second = X86::VR128RegisterClass;
13091   }
13092
13093   return Res;
13094 }